--- title: Introduction project: Total.js V5 version: 0.0.20 section: guides language: en license: MIT url: https://totaljs.es/docs/total-js-v5/0-0-20/guides/introduction/ updated: 2026-11-19T20:13:56.297Z --- # Introduction > What Total.js framework v5 is, what the total5 package includes and the main concepts of a Total.js application. Total.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. It is published on npm as `total5`, under the MIT license, by Peter Širka. The source code lives in the `totaljs/framework5` repository on GitHub. ```bash $ npm install total5@beta ``` ## One package, no dependencies The `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()`. ```js require('total5'); ROUTE('GET /', function($) { $.plain('Hello world'); }); F.http({ port: 8000 }); ``` The package also installs two command-line tools, `total5` and `flow5`. They are described in [Command line](../command-line/). ## What the package includes The package is a set of modules. Each module covers one area of a typical application: | Area | Modules | Main API | |------|---------|----------| | HTTP server and routing | `http.js`, `routing.js`, `controller.js` | `ROUTE()`, the controller `$` | | Actions and schemas | `builders.js`, `jsonschema.js` | `NEWACTION()`, `ACTION()`, `NEWSCHEMA()` | | Views and templates | `viewengine.js`, `tangular.js`, `templates.js`, `markdown.js` | `$.view()`, `TEMPLATE()` | | WebSocket | `websocket.js` | `ROUTE('SOCKET ...')`, `WEBSOCKETCLIENT()` | | NoSQL embedded database | `nosql.js`, `nosql-*.js` | `NOSQL()` | | Query builder for SQL databases | `querybuilder.js` | `DATA`, `DB()`, `NEWDB()` | | File storage | `filestorage.js` | `FILESTORAGE()` | | Outgoing HTTP requests | `utils.js`, `builders.js` | `REQUEST()`, `RESTBuilder`, `AJAX()` | | Mail | `mail.js` | `MAIL()`, `HTMLMAIL()`, `Mail` | | Scheduling | `cron.js` | `CRON()` | | Images | `images.js` | `Image` | | Plugins and components | `index.js`, `components.js` | `plugins/` directory, `NEWCOMPONENT()` | | Flow engine | `flow.js`, `flowstream.js`, `flow-flowstream.js` | FlowStream, `flow5` | | Total.js Message Service | `tms.js` | `NEWPUBLISH()`, `NEWSUBSCRIBE()`, `PUBLISH()`, `SUBSCRIBE()` | | API services | `api.js` | `API()`, `NEWAPI()` | | Workers and threads | `workers.js`, `cluster.js` | `NEWTHREAD()`, `NEWTHREADPOOL()` | | Python scripts | `pypeline.js` | `PYPELINE()` | | Utilities | `utils.js`, `htmlparser.js`, `minificators.js`, `macros.js` | `U`, `NEWMACRO()` | | AI models | `aimodel.js` | `NEWAIMODEL()`, `AIMODEL()`, `AIPARSER()` | | Proxy | `proxy.js` | `PROXYSERVER()`, `PROXYCLIENT()` | | Other modules | `ldap.js`, `cms.js`, `uibuilder.js`, `openclient.js`, `bundles.js`, `edit.js` | `LDAP()`, `OPENCLIENT()`, bundles, remote editing | | Start and watcher | `debug.js`, `release.js` | `Total.run()` (`F.run()`) | ## Main concepts ### Application directory A 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/). ### Routes and the controller A 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). ```js exports.install = function() { ROUTE('GET /', function($) { $.plain('Hello world'); }); }; ``` See [Routing](../routing/) and [Controller](../controller/). Static files, middleware and authorization are in [Middleware](../middleware/), [Static files](../static-files/) and [Authorization](../authorization/). ### Actions Actions 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. ```js NEWACTION('hello', { name: 'Say hello', action: function($) { $.success('Hello from an action'); } }); ROUTE('GET /api/hello/ --> hello'); ``` See [Actions](../actions/) and [JSON schemas](../json-schemas/). ### Views The view engine renders HTML templates from the `views` directory with models, layouts and helpers. See [Views](../views/) and [Localization](../localization/). ### Configuration The `config` file in the application root holds key/value settings, read into the global `CONF` object. See [Configuration](../configuration/). ### Data The 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/). ### Plugins and components A plugin is a self-contained part of an application in `plugins//`, with its own controllers, actions, schemas and definitions. Components (`NEWCOMPONENT()`) compile reusable HTML components. See [Plugins and components](../plugins-and-components/). ### FlowStream FlowStream 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/). ### TMS and APIs The 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/). ### AI models The `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/). ### Everything else WebSocket, 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/). ## Where to go next 1. [Installation and first app](../installation/): install the package, write the start script and the first route. 2. [Application structure](../application-structure/): the full list of directories and files. 3. [Routing](../routing/) and [Actions](../actions/): the two parts every application uses. --- title: Installation and first app project: Total.js V5 version: 0.0.20 section: guides language: en license: MIT url: https://totaljs.es/docs/total-js-v5/0-0-20/guides/installation/ updated: 2026-11-18T16:59:54.646Z --- # Installation and first app > Install the total5 package, write the start script, add a first route and action, and run the app in debug and release mode. This 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. ## Requirements Total.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: ```bash $ node --version $ npm --version ``` ## Install the package Create a directory for the application and install the package from npm: ```bash $ mkdir myapp $ cd myapp $ npm init -y $ npm install total5@beta ``` The 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/)). ## The start script Create `index.js` in the application root. This is the official start script of Total.js 5: ```js require('total5'); const options = {}; // options.ip = '127.0.0.1'; // options.port = parseInt(process.argv[2]); // options.unixsocket = PATH.join(F.tmpdir, 'app_name.socket'); // options.unixsocket777 = true; // options.config = { name: 'Total.js' }; // options.inspector = 9229; // options.watch = ['private']; // options.livereload = 'https://yourhostname'; // options.watcher = false; // disables watcher // options.edit = 'wss://www.yourcodeinstance.com/?id=projectname' options.release = process.argv.includes('--release'); // Service mode: options.servicemode = process.argv.includes('--service') || process.argv.includes('--servicemode'); // options.servicemode = 'definitions,modules,config'; // Cluster: // options.tz = 'utc'; // options.cluster = 'auto'; // options.limit = 10; Total.run(options); ``` Start 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. `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. The commented lines are the other start options: | Option | Description | |--------|-------------| | `ip` | IP address to listen on. Default `0.0.0.0` (`CONF.$ip`). | | `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`. | | `unixsocket` | Listen on a Unix socket instead of an IP and port. | | `unixsocket777` | Gives the Unix socket the permissions 777. | | `config` | An object with configuration keys applied before the app loads, for example `{ name: 'My app' }`. | | `inspector` | With the watcher: starts the app with the Node.js inspector on this port (`--inspect=9229`). | | `watch` | With the watcher: an array of extra directories the watcher observes. | | `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. | | `watcher` | `false` runs the application in release mode in the current process, without the watcher. | | `edit` | Connects the application to the Total.js Code Editor. | | `release` | `true` runs the application with `DEBUG = false`. | | `servicemode` | `true` loads the application without the HTTP server. A comma-separated string (for example `'config,modules,definitions'`) loads only those parts. | | `cluster` | A number of processes, or `'auto'` (see [Workers and threads](../workers-and-threads/)). | | `limit` | With `cluster: 'auto'`: the maximum number of processes. | | `tz` | With `cluster`: the time zone of the processes (`process.env.TZ`), `'utc'` by default. | Every option is described in the [reference](../../reference/application-structure/). The 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. ## Folder structure The framework loads these files and directories from the application root when it starts. All of them are optional: create only the ones you use. ```text myapp/ ├── index.js start script ├── config configuration (key : value per line) ├── .env environment variables ├── version application version (first line) ├── controllers/ routes: *.js files with exports.install ├── actions/ NEWACTION() definitions ├── schemas/ NEWSCHEMA() definitions ├── models/ business logic ├── definitions/ startup code: delegates, helpers, globals ├── modules/ modules with exports.install ├── extensions/ extensions of the framework ├── middleware/ NEWMIDDLEWARE() definitions ├── plugins/ plugins: plugins//index.js ├── jsonschemas/ JSON schemas (*.json or *.txt) ├── resources/ localization (*.resource) ├── views/ HTML views ├── public/ static files (CSS, JS, images) ├── flowstreams/ FlowStream schemas ├── databases/ NoSQL databases and file storages ├── logs/ log files └── tmp/ temporary files ``` Every `.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/). ## First route Create `controllers/default.js`: ```js exports.install = function() { ROUTE('GET /', index); ROUTE('GET /api/hello/ --> hello'); ROUTE('POST /api/greet/ --> greet'); }; function index($) { $.plain('Hello world'); } ``` `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/). ## First action Create `actions/hello.js`: ```js NEWACTION('hello', { name: 'Say hello', action: function($) { $.success('Hello from an action'); } }); NEWACTION('greet', { input: '*name:String', action: function($, model) { $.callback({ message: 'Hello ' + model.name }); } }); ``` The `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: ```bash $ curl -X POST -H 'Content-Type: application/json' -d '{"name":"Peter"}' http://127.0.0.1:8000/api/greet/ {"message":"Hello Peter"} $ curl -X POST -H 'Content-Type: application/json' -d '{}' http://127.0.0.1:8000/api/greet/ [{"name":"name","error":"The field \"name\" is invalid","path":"name"}] ``` Actions and inline schemas are covered in [Actions](../actions/) and [JSON schemas](../json-schemas/). ## Configuration Create a `config` file with one `key : value` pair per line: ```text name : My first app ``` The value is available as `CONF.name` and is printed when the app starts. See [Configuration](../configuration/). ## Run in debug mode ```bash $ node index.js ``` The debug module starts a watcher process (`Total.js watcher PID: ...`), which starts the application in a child process and prints the start information: ```text ==================================================== PID : 75692 ... Name : My first app Version : 1.0.0 Mode : debug Compiled : 2 files (4ms) ==================================================== http://0.0.0.0:8000/ ``` Open `http://127.0.0.1:8000/` in the browser: the page shows `Hello world`. Press `Ctrl+C` in the terminal to stop the application. In debug mode: - `DEBUG` is `true`. - 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. - The watcher writes an `index.pid` file with its process ID. Deleting the file stops the watcher and the application. - The framework writes `index.js.map`, a JSON list of the registered routes and actions. Pass a port as an argument when the start script does not set one: ```bash $ node index.js 8001 ``` ## Run in release mode ```bash $ node index.js --release ``` With the start script above, `--release` switches `DEBUG` to `false`, but the watcher keeps running and restarts the application when a file changes. For 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. ## Next steps - [Your first form](../first-form/): show a form, receive its data and answer with a new page. - [Application structure](../application-structure/) describes every directory. - [Routing](../routing/), [Controller](../controller/) and [Actions](../actions/) cover the request flow. - [Views](../views/) renders HTML pages from the `views` directory. --- title: Your first form project: Total.js V5 version: 0.0.20 section: guides language: en license: MIT url: https://totaljs.es/docs/total-js-v5/0-0-20/guides/first-form/ updated: 2026-11-18T15:59:56.968Z --- # Your first form > Show a form, receive its data and answer with a new page. This 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/). ## Create the layout Every view is rendered into a layout, so create it first: ```html @{title} @{body} ``` `@{title}` prints the title of the page and `@{body}` prints the view. ## Create the form This view shows the form, and a message when there is one: ```html @{title('Contact')}

Contact

@{if model.error}

@{model.error}

@{fi}
``` The `name` attribute of the input is the name of the field that the application receives. ## Create the result page This view shows the name that was sent: ```html @{title('Thank you')}

Hello @{model.name}

Send another name

``` ## Add the routes One route shows the form and the other one receives it: ```js // controllers/contact.js exports.install = function() { ROUTE('GET /contact/', form); ROUTE('POST /contact/', send); }; function form($) { $.view('contact', { name: '', error: '' }); } function send($) { var name = ($.body.name || '').trim(); if (!name) { $.view('contact', { name: '', error: 'Write your name.' }); return; } $.view('thanks', { name: name }); } ``` `$.body` contains the fields of the form. `$.view(name, model)` renders a view, and the view reads those values from `model`. ## Try it Start the application: ```bash $ node index.js ``` Open `http://127.0.0.1:8000/contact/` in the browser and try both cases: - Send the form with the field empty: the page shows `Write your name.` - Write a name and send it: the page shows `Hello` and the name. `@{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. ## Next steps - [Views](../views/): layouts and the commands of a view. - [Controller](../controller/): the data of a request and the responses. - [Actions](../actions/): validate the data of larger forms. --- title: Migrating from Total.js 4 project: Total.js V5 version: 0.0.20 section: guides language: en license: MIT url: https://totaljs.es/docs/total-js-v5/0-0-20/guides/migrating-from-total4/ updated: 2026-11-18T16:59:59.647Z --- # Migrating from Total.js 4 > Move a Total.js 4 application to Total.js 5, area by area, with the code before and after each change. This 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. ## Recommended order of work 1. Replace the `total4` package with `total5` and update the [start script](#start-script). 2. Rename the [configuration keys](#configuration) and add types to numeric values. 3. Turn [schemas into actions](#schemas-and-actions) and update the routes that call them. 4. Replace `this` with `$` in [routes and controllers](#routes) and in [middleware](#middleware). 5. Check [views](#views) and [mail views](#mail): folders, layouts and titles. 6. Update [NoSQL](#nosql) queries, [RESTBuilder](#restbuilder) error handling, [WebSockets](#websockets) and [file storage](#file-storage). 7. Replace [`SCHEDULE()`](#scheduling), [operations and tasks](#operations-and-tasks), and `MODULE()` and `MODEL()` [calls](#modules-models-and-definitions). 8. Rewrite the [unit tests](#unit-tests) and run the application. ## Start script | Total.js 4 | Total.js 5 | | --- | --- | | `npm install total4` | `npm install total5@beta` | | `require('total4/debug')(options)` | `require('total5'); Total.run(options)` | | `require('total4/release')(options)` | `options.release = true; Total.run(options)` | Before: ```js const options = {}; // options.ip = '127.0.0.1'; options.port = parseInt(process.argv[2]); // options.config = { name: 'My app' }; var type = process.argv.indexOf('--release', 1) !== -1 ? 'release' : 'debug'; require('total4/' + type)(options); ``` After: ```js require('total5'); const options = {}; // options.ip = '127.0.0.1'; options.port = parseInt(process.argv[2]); // options.config = { name: 'My app' }; options.release = process.argv.includes('--release'); Total.run(options); ``` Both scripts start in debug mode, and in release mode with `node index.js --release`. See [Installation](../installation/). ## Schemas and actions `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`. | Total.js 4 | Total.js 5 | | --- | --- | | `schema.define('name', 'String(30)', true)` | `input: '*name:String(30)'` | | `schema.define('role', ['admin', 'user'])` | `input: 'role:{admin\|user}'` | | `schema.setInsert(fn)`, `setQuery(fn)`, `setRead(fn)`... | `NEWACTION('Users/insert', { action: fn })` | | `ROUTE('POST /api/users/ *Users --> insert')` | `ROUTE('POST /api/users/ --> Users/insert')` | | `$.id` | `params: '*id:String'` and `$.params.id` | | `.callback($.callback)` | `.callback($)` | | `$.invalid('age', 'Message')` | `$.invalid('Message', 'age')` | | `CALL('Math --> double', data)` | `ACTION('Math/double', data)` | Before: ```js NEWSCHEMA('Users', function(schema) { schema.define('name', 'String(30)', true); schema.define('email', 'Email', true); schema.define('age', Number); schema.define('role', ['admin', 'user']); schema.setInsert(function($, model) { model.id = 'A1'; $.success(model); }); }); ``` ```js exports.install = function() { ROUTE('POST /api/users/ *Users --> insert'); }; ``` After: ```js NEWACTION('Users/insert', { input: '*name:String(30), *email:Email, age:Number, role:{admin|user}', action: function($, model) { model.id = 'A1'; $.success(model); } }); ``` ```js exports.install = function() { ROUTE('POST /api/users/ --> Users/insert'); }; ``` ### Custom validators A validator function in `schema.define()` moves into the action. Before: ```js NEWSCHEMA('Signup', function(schema) { schema.define('name', 'String(30)', true); schema.define('age', Number, value => value >= 18, 'You must be an adult'); schema.setInsert(function($, model) { $.success(model.age); }); }); ``` After: ```js NEWACTION('Signup/insert', { input: '*name:String(30), age:Number', action: function($, model) { if (model.age < 18) { $.invalid('You must be an adult', 'age'); return; } $.success(model.age); } }); ``` ### Schemas that already use `schema.action()` These schemas keep working. Only the route changes: `*Tags --> list` becomes `--> Tags/list`. ```js NEWSCHEMA('Tags', function(schema) { schema.action('list', { name: 'List of tags', query: 'limit:Number', action: function($) { $.callback(['a', 'b', 'c'].slice(0, $.query.limit || 3)); } }); schema.action('create', { name: 'Create a tag', input: '*name:String(20)', action: function($, model) { $.success(model.name); } }); }); ``` ```js exports.install = function() { ROUTE('GET /api/tags/ --> Tags/list'); ROUTE('POST /api/tags/ --> Tags/create'); }; ``` ### Values and errors your clients will notice | Case | Total.js 4 | Total.js 5 | | --- | --- | --- | | Optional `Number` is missing | The field is `0` | The field is left out | | Optional enum is missing | The field is left out | The field is `''` | | Enum value is not in the list | Value dropped, request accepted | `400` with an error for the field | | Keys of a required-field error | `name`, `error`, `path`, `prefix` | `name`, `error`, `path` | | Keys of an error from `$.invalid()` with a field | `name`, `error` | `error`, `path` | A client that reads `name` from your own errors has to read `path` instead. See [Actions](../actions/) and [JSON schemas](../json-schemas/). ## Routes | Total.js 4 | Total.js 5 | | --- | --- | | `function detail(id) { this.json({ id: id }); }` | `function detail($) { $.json({ id: $.params.id }); }` | | `ROUTE('/about/', fn)` | `ROUTE('GET /about/', fn)`: the method is required | | `{page:number}` converts the value | `{page}` is a string: `$.params.page.parseInt()` | | `ROUTE('POST /upload/', fn, ['upload'], 1024)` | `ROUTE('POST /upload/ @upload <1MB', fn)` | | `ROUTE('POST /import/', fn, 1024)` | `ROUTE('POST /import/ <1MB', fn)` | | `ROUTE('+GET /admin/ @admin', fn)` | `ROUTE('+GET /admin/', fn)` and `UNAUTHORIZED($, 'admin')` in the handler | | `ROUTE('API /api/ -users_list *Users --> list')` | `ROUTE('API /api/ users_list --> Users/list')` | | `ROUTE('API /api/ +users_save *Users --> save')` | `ROUTE('API /api/ users_save --> Users/save')` | A 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/). Before: ```js exports.install = function() { ROUTE('GET /users/{id}/orders/{order}/', detail); }; function detail(id, order) { this.json({ id: id, order: order, params: this.params }); } ``` After: ```js exports.install = function() { ROUTE('GET /users/{id}/orders/{order}/', detail); }; function detail($) { $.json({ id: $.params.id, order: $.params.order, params: $.params }); } ``` ## Controllers Handlers receive the controller as `$`. `this` is no longer the controller in HTTP routes. | Total.js 4 | Total.js 5 | | --- | --- | | `this.status = 201` | `$.response.status = 201` | | `this.header('X-Version', '1')` | `$.response.headers['x-version'] = '1'` | | `this.nocache()` | `$.response.headers['cache-control'] = 'private, no-cache, no-store, max-age=0'` | | `this.content('1', 'text/xml')` | `$.xml('1')` | | `this.content('id;name', 'text/csv')` | `$.binary(Buffer.from('id;name'), 'text/csv')` | | `this.nocontent()` | `$.empty()` | | `this.throw404()`, `this.throw403()` | `$.fallback(404)`, `$.fallback(403)` | | `this.throw500('Problem')` | `$.fallback(500, 'Problem')` | | `this.file('docs/a.txt', 'report.txt')` | `$.file(PATH.public('docs/a.txt'), 'report.txt')` | | `this.success(true, 42)` | `$.success(42)` | | `this.success(false)` | `$.json({ success: false })` | | `this.invalid('email', 'Message')` | `var err = new ErrorBuilder(); err.push('Message', 'email'); $.invalid(err);` | | `file.isImage()` | `file.isImage` | | `this.mail(email, subject, view, model)` | `MAIL(email, subject, view, model)` | These 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)`. An error route sets the status in the same way: ```js exports.install = function() { ROUTE('GET /missing/', missing); ROUTE('GET /denied/', denied); ROUTE('GET /broken/', broken); ROUTE('#404', notfound); }; function missing($) { $.fallback(404); } function denied($) { $.fallback(403); } function broken($) { $.fallback(500, 'Unexpected problem'); } function notfound($) { $.response.status = 404; $.plain('My 404 page'); } ``` See [Controller](../controller/). ## Views The syntax of view files does not change: expressions, conditions, loops, sections, partial views and helpers from `DEF.helpers` work as before. | Total.js 4 | Total.js 5 | | --- | --- | | `this.view('detail')` in `controllers/users.js` finds `views/users/detail.html` | `$.view('users/detail')`: the name always starts in `views/` | | The layout can read `model` | Set `@{repository.name = model.name}` in the view and read `repository` in the layout | | `this.title('Products')` | `@{title('Products')}` in the view | | `this.repository.page = 'list'` | `@{repository.page = 'list'}` in the view | | `VIEW('mail/order', model)` | `F.view('mail/order', model)`, with `@{layout('')}` in the view | | The title of the home page gets ` - ` and `CONF.name` | The title of the home page stays as you wrote it | Before: ```html @{model.name}@{body} ``` After: ```html @{repository.name}@{body} ``` ```html @{repository.name = model.name}

@{model.name}

``` See [Views](../views/). ## Middleware | Total.js 4 | Total.js 5 | | --- | --- | | `MIDDLEWARE('name', function($) { $.next(); })` | `NEWMIDDLEWARE('name', function($, next) { next(); })` | | `$.res.throw401()` | `$.invalid(401)` | | `$.res.setHeader('x-stamp', 'yes')` | `$.response.headers['x-stamp'] = 'yes'` | | `ROUTE('GET /private/', fn, ['#apikey'])` | `ROUTE('GET /private/ #apikey', fn)` | | `ROUTE('GET /open/ &stamp', fn)` | `ROUTE('GET /open/ #stamp', fn)` | | `USE('poweredby', ['web'])` | Third argument `'routes'`, inside `ON('ready')` | Before: ```js MIDDLEWARE('poweredby', function($) { $.res.setHeader('x-server', 'myapp'); $.next(); }); USE('poweredby', ['web']); ``` After: ```js ON('ready', function() { NEWMIDDLEWARE('poweredby', function($, next) { $.response.headers['x-server'] = 'myapp'; next(); }, 'routes'); }); ``` See [Middleware](../middleware/). ## WebSockets A `SOCKET` route keeps its structure, and `this` still works inside its handler. | Total.js 4 | Total.js 5 | | --- | --- | | `function room(name) {}` | `function room($) { var name = $.params.name; }` | | `ROUTE('SOCKET /feed/', fn, ['json'], 64)` | `ROUTE('SOCKET /feed/ <64kB', fn)` | | `ROUTE('SOCKET /terminal/', fn, ['text'])` | `ROUTE('SOCKET /terminal/ @text', fn)` | | `client.send(text)` on a text route | `client.send(text, true)` | | `client.close('finished', 4000)` | `client.close(4000, 'finished')` | | A refused `+SOCKET` client connects and is closed with `4001` | The handshake is refused and the client sees `1006` | See [WebSockets](../websockets/). ## NoSQL Existing `.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. | Total.js 4 | Total.js 5 | | --- | --- | | `find()` starts with the oldest document | `find()` starts with the newest document: add `sort()` when the order matters | | `find2()` | `find()` | | `one()` | `read()` | | `sort('age_desc')` | `sort('age', true)` | | `NOSQL('users').count()` | `DATA.count('nosql/users')` | | `NOSQL('users').list()` | `DATA.list('nosql/users')` | | `rule('doc.age > arg.min', { min: 45 })` | `query('doc.age > 45')` | | `update({ '-score': 3 })` | `update({ '+score': -3 })` | | `TABLE('users')` | `NOSQL('users')` | `TABLE()` does not exist in Total.js 5, so move the rows of `.table` files into a NoSQL database yourself. Before: ```js exports.install = function() { ROUTE('GET /run/', run); }; async function run() { var db = NOSQL('users'); await db.insert({ id: '1', name: 'Ann', age: 30, score: 10 }).promise(); await db.insert({ id: '2', name: 'Bob', age: 40, score: 10 }).promise(); await db.insert({ id: '3', name: 'Cid', age: 50, score: 10 }).promise(); var one = await db.one().where('id', '2').fields('name').promise(); var count = await db.count().where('age', '>', 35).promise(); var list = await db.list().sort('age_desc').fields('name').paginate(1, 2).promise(); var rule = await db.find().rule('doc.age > arg.min', { min: 45 }).fields('name').promise(); await db.update({ '-score': 3 }).where('id', '1').promise(); var score = await db.read().id('1').fields('score').promise(); this.json({ one: one, count: count.count, items: list.items, pages: list.pages, total: list.count, rule: rule, score: score }); } ``` After: ```js exports.install = function() { ROUTE('GET /run/', run); }; async function run($) { var db = NOSQL('users'); await db.insert({ id: '1', name: 'Ann', age: 30, score: 10 }).promise(); await db.insert({ id: '2', name: 'Bob', age: 40, score: 10 }).promise(); await db.insert({ id: '3', name: 'Cid', age: 50, score: 10 }).promise(); var one = await db.read().where('id', '2').fields('name').promise(); var count = await DATA.count('nosql/users').where('age', '>', 35).promise(); var list = await DATA.list('nosql/users').sort('age', true).fields('name').paginate(1, 2).promise(); var rule = await db.find().query('doc.age > 45').fields('name').promise(); await db.update({ '+score': -3 }).where('id', '1').promise(); var score = await db.read().id('1').fields('score').promise(); $.json({ one: one, count: count.count, items: list.items, pages: list.pages, total: list.count, rule: rule, score: score }); } ``` See [NoSQL database](../nosql/). ## RESTBuilder | Total.js 4 | Total.js 5 | | --- | --- | | A status of `400` or higher is an error only with `.strict()` | A status of `400` or higher is always an error | | `.callback($.callback)` in an operation | `.callback($)` in an action | Code that reads `output.status` after a failed request has to handle `err` first. See [HTTP requests](../http-requests/). ## Configuration | Total.js 4 | Total.js 5 | | --- | --- | | `default_root` | `$root` | | `default_timezone` | `$timezone` | | `default_cookies_samesite` | `$cookiesamesite` | | `default_cookies_secure` | `$cookiesecure` | | `default_xpoweredby` | `$xpoweredby` | | `allow_custom_titles` | `$customtitles` | | `allow_gzip` | `$httpcompress` | | `limit : 50` is a number | `limit (number) : 50`: without a type the value is a string | | `smtp (object) : { port: 465 }` | `smtp (json) : { "port": 465 }` | | `config-release` | Not loaded: keep the values in `config` | Before: ```text name : Shop default_root : /app/ default_timezone : Europe/Bratislava default_cookies_samesite : Strict default_cookies_secure : true default_xpoweredby : MyServer allow_custom_titles : true allow_gzip : false ``` After: ```text name : Shop $root : /app/ $timezone : Europe/Bratislava $cookiesamesite : Strict $cookiesecure : true $xpoweredby : MyServer $customtitles : true $httpcompress : false ``` `CORS()`, `name`, `(array)` values and `mail_smtp_options` written as a JavaScript object work as before. See [Configuration](../configuration/). ## Authorization The `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()`. | Total.js 4 | Total.js 5 | | --- | --- | | `SESSION()` with `ondata` | `AUTH(opt)` with `opt.onread` | | `session.setcookie($, options, callback)` | `opt.authcookie($, UID(), userid, '1 hour')` | | `session.remove2(userid)` and clearing the cookie | `opt.logout($)` in an action | Before: ```js var session = SESSION(); session.ondata = function(meta, next) { next(null, { id: meta.id, name: 'Peter' }); }; AUTH(function($) { session.getcookie($, { name: 'sid', expire: '1 hour', key: 'session-key' }, function(err, user) { if (user) $.success(user); else $.invalid(); }); }); MAIN.session = session; ``` After: ```js var opt = {}; opt.secret = 'session-key'; opt.cookie = 'sid'; opt.expire = '1 hour'; opt.onread = function(meta, next) { next(null, { id: meta.userid, name: 'Peter' }); }; AUTH(opt); MAIN.session = opt; ``` ```js NEWACTION('Account/logout', { action: function($) { MAIN.session.logout($); $.success(); } }); ``` `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/). ## Localization Resource files and `@(Text)` in views stay the same, and the generated keys are identical. | Total.js 4 | Total.js 5 | | --- | --- | | `LOCALIZE(function(req, res) {})` | `LOCALIZE(function($) {})` | | `RESOURCE('sk', 'title')` | `F.resource('sk', 'title')` | | `TRANSLATOR('sk', '@(Welcome)')` | `TRANSLATE('sk', '@(Welcome)')` | | `TRANSLATE('sk', 'Welcome')` | `TRANSLATE('sk', '@(Welcome)')` | See [Localization](../localization/). ## Mail | Total.js 4 | Total.js 5 | | --- | --- | | `MAIL()` renders the view without a layout | `MAIL()` renders the view into `views/layout.html` | | `ON('mail', fn)` | `ON('$mail', fn)` | | `message.address_to` | `message.email_to` | Start 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. Before: ```html

Hello @{model.name}

``` After: ```html @{layout('')}

Hello @{model.name}

``` See [Sending email](../mail/). ## File storage The arguments of `save()` change order: the custom data now comes before the callback. | Total.js 4 | Total.js 5 | | --- | --- | | `fs.save(id, name, data, callback, custom)` | `fs.save(id, name, data, custom, callback)` | `read()` and `$.filefs()` do not change. See [File storage](../file-storage/). ## Scheduling | Total.js 4 | Total.js 5 | | --- | --- | | `SCHEDULE('* * * * *', fn)` | `CRON('* * * * *', fn)` | | `SCHEDULE('03:00', '1 day', fn)` | `CRON('0 3 * * *', fn)` | Before: ```js MAIN.runs = 0; SCHEDULE('* * * * *', function() { MAIN.runs++; }); ``` After: ```js MAIN.runs = 0; CRON('* * * * *', function() { MAIN.runs++; }); ``` See [Scheduling and events](../scheduling-and-events/). ## Operations and tasks `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. | Total.js 4 | Total.js 5 | | --- | --- | | `NEWOPERATION('order_price', fn)` | `NEWACTION('order_price', { input: '...', action: fn })` | | `OPERATION('order_price', value, callback)` | `ACTION('order_price', value).callback(callback)` | | `RUN('order_check, order_price', value, callback)` | `await ACTION(...).promise($)` for each step | | `NEWTASK('order', fn)` and `TASK('order/check', ...)` | `NEWACTION('order', { action: fn })` | Before: ```js exports.install = function() { ROUTE('POST /order/', order); ROUTE('POST /chain/', chain); }; function order() { var self = this; OPERATION('order_price', self.body, function(err, response) { self.json({ err: err ? err.toString() : null, response: response }); }); } function chain() { var self = this; RUN('order_check, order_price', self.body, function(err, response) { if (err) self.invalid(err); else self.json(response.order_price); }); } ``` After: ```js NEWACTION('order_check', { input: '*email:String, count:Number', action: function($, model) { model.email = model.email.toLowerCase(); $.callback(model); } }); NEWACTION('order_price', { input: 'email:String, count:Number', action: function($, model) { $.callback({ email: model.email, price: model.count * 10 }); } }); ``` ```js exports.install = function() { ROUTE('POST /order/', order); ROUTE('POST /chain/', chain); }; function order($) { ACTION('order_price', $.body).callback(function(err, response) { $.json({ err: err ? err.toString() : null, response: response }); }); } async function chain($) { var model = await ACTION('order_check', $.body).promise($); $.json(await ACTION('order_price', model).promise($)); } ``` See [Actions](../actions/). ## Modules, models and definitions Files in `definitions/` and `modules/` load as before, and `MAIN`, `FUNC`, `PATH` and `ON('ready')` do not change. | Total.js 4 | Total.js 5 | | --- | --- | | `MODULE('greeter').greet('Peter')` | `MODS.greeter.greet('Peter')` | | `MODEL('price').total(2, 5)` | `require(PATH.root('models/price.js')).total(2, 5)` | | `CACHE('products', value, '5 minutes')` | `CACHE.set('products', value, '5 minutes')` | | `CACHE('products')` | `CACHE.read('products')` | See [Application structure](../application-structure/). ## Unit tests `TESTER()` is replaced by the `Test` object of `total5/test`. Before: ```js require('total4'); TESTER(function(group, start) { group('Strings', function(test) { test('slug()', function(next) { next('Hello World'.slug() === 'hello-world' ? undefined : 'Unexpected slug'); }); test('capitalize()', function(next) { next('total'.capitalize() === 'Total' ? undefined : 'Unexpected value'); }); }); start(); }); ``` After: ```js require('total5/test'); Test.push('Strings', function(next) { Test.print('slug()', 'Hello World'.slug() === 'hello-world' ? null : 'Unexpected slug'); Test.print('capitalize()', 'total'.capitalize() === 'Total' ? null : 'Unexpected value'); next(); }); Test.run(); ``` See [Unit tests](../unit-tests/). ## Command line | Total.js 4 | Total.js 5 | | --- | --- | | `total4 translate` | `total5 translate "$PWD/translate.resource"` | Give `total5 translate` the full path of the output file. See [Command line](../command-line/). ## A complete application This 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). ### Total.js 4 `index.js` ```js const options = {}; options.port = parseInt(process.argv[2]); var type = process.argv.indexOf('--release', 1) !== -1 ? 'release' : 'debug'; require('total4/' + type)(options); ``` `config` ```text name : Notes apitoken : secret mail_notify : admin@example.com mail_from : notes@example.com mail_smtp : 127.0.0.1 mail_smtp_options : { port: 19854 } maxnotes : 100 ``` `definitions/auth.js` ```js AUTH(function($) { if ($.headers['x-token'] === CONF.apitoken) $.success({ id: '1', name: 'Admin' }); else $.invalid(); }); ``` `definitions/jobs.js` ```js MAIN.ticks = 0; SCHEDULE('* * * * *', function() { MAIN.ticks++; }); ``` `schemas/notes.js` ```js NEWSCHEMA('Notes', function(schema) { schema.define('title', 'String(50)', value => value && value !== 'spam', 'This title is not allowed'); schema.define('body', 'String(500)'); schema.setQuery(function($) { NOSQL('notes').find().sort('dtcreated_desc').fields('id,title').take(CONF.maxnotes).callback($.callback); }); schema.setRead(function($) { NOSQL('notes').read().id($.id).fields('id,title,body').callback(function(err, note) { if (note) $.callback(note); else $.invalid(404); }); }); schema.setInsert(function($, model) { model.id = UID(); model.dtcreated = new Date(); NOSQL('notes').insert(model).callback(function() { MAIL(CONF.mail_notify, 'New note', 'mail/note', model); MAIN.live && MAIN.live.send({ type: 'note', title: model.title }); $.success(model.id); }); }); schema.setRemove(function($) { NOSQL('notes').remove().id($.id).callback($.done()); }); }); ``` `controllers/api.js` ```js exports.install = function() { ROUTE('GET /api/notes/ *Notes --> query'); ROUTE('GET /api/notes/{id}/ *Notes --> read'); ROUTE('+POST /api/notes/ *Notes --> insert'); ROUTE('+DELETE /api/notes/{id}/ *Notes --> remove'); ROUTE('GET /api/stats/', stats); ROUTE('SOCKET /live/', live); }; function stats() { this.json({ ticks: MAIN.ticks }); } function live() { MAIN.live = this; } ``` `controllers/default.js` ```js exports.install = function() { ROUTE('GET /', index); }; function index() { var self = this; self.title('Latest notes'); NOSQL('notes').find().sort('dtcreated_desc').fields('title').callback(function(err, notes) { self.view('index', notes); }); } ``` `views/layout.html` ```html @{import('meta')} @{body} ``` `views/index.html` ```html

@{config.name}

``` `views/mail/note.html` ```html

New note: @{model.title}

``` ### Total.js 5 `definitions/auth.js` and `views/layout.html` stay the same. `index.js` ```js require('total5'); const options = {}; options.port = parseInt(process.argv[2]); options.release = process.argv.includes('--release'); Total.run(options); ``` `config` ```text name : Notes apitoken : secret mail_notify : admin@example.com mail_from : notes@example.com mail_smtp : 127.0.0.1 mail_smtp_options : { port: 19854 } maxnotes (number) : 100 ``` `definitions/jobs.js` ```js MAIN.ticks = 0; CRON('* * * * *', function() { MAIN.ticks++; }); ``` `actions/notes.js` ```js NEWACTION('Notes/query', { action: function($) { NOSQL('notes').find().sort('dtcreated', true).fields('id,title').take(CONF.maxnotes).callback($); } }); NEWACTION('Notes/read', { params: '*id:String', action: function($) { NOSQL('notes').read().id($.params.id).fields('id,title,body').callback(function(err, note) { if (note) $.callback(note); else $.invalid(404); }); } }); NEWACTION('Notes/insert', { input: '*title:String(50), body:String(500)', action: function($, model) { if (model.title === 'spam') { $.invalid('This title is not allowed', 'title'); return; } model.id = UID(); model.dtcreated = new Date(); NOSQL('notes').insert(model).callback(function() { MAIL(CONF.mail_notify, 'New note', 'mail/note', model); MAIN.live && MAIN.live.send({ type: 'note', title: model.title }); $.success(model.id); }); } }); NEWACTION('Notes/remove', { params: '*id:String', action: function($) { NOSQL('notes').remove().id($.params.id).callback($.done()); } }); ``` `controllers/api.js` ```js exports.install = function() { ROUTE('GET /api/notes/ --> Notes/query'); ROUTE('GET /api/notes/{id}/ --> Notes/read'); ROUTE('+POST /api/notes/ --> Notes/insert'); ROUTE('+DELETE /api/notes/{id}/ --> Notes/remove'); ROUTE('GET /api/stats/', stats); ROUTE('SOCKET /live/', live); }; function stats($) { $.json({ ticks: MAIN.ticks }); } function live($) { MAIN.live = $; } ``` `controllers/default.js` ```js exports.install = function() { ROUTE('GET /', index); }; function index($) { NOSQL('notes').find().sort('dtcreated', true).fields('title').callback(function(err, notes) { $.view('index', notes); }); } ``` `views/index.html` ```html @{title('Latest notes')}

@{config.name}

``` `views/mail/note.html` ```html @{layout('')}

New note: @{model.title}

``` --- title: Routing project: Total.js V5 version: 0.0.20 section: guides language: en license: MIT url: https://totaljs.es/docs/total-js-v5/0-0-20/guides/routing/ updated: 2026-11-16T15:48:48.957Z --- # Routing > Declare routes with ROUTE(): methods, dynamic paths, authorization, actions, API endpoints, flags, file routes, CORS and proxies. Routes 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. ```js exports.install = function() { ROUTE('GET /', index); ROUTE('GET /products/{id}/', detail); ROUTE('POST /contact/', contact); }; function index($) { $.plain('Hello world'); } function detail($) { $.json({ id: $.params.id }); } function contact($) { // $.body contains the parsed JSON or form data $.success(); } ``` The action receives the controller `$`. Its properties and methods (`$.params`, `$.body`, `$.query`, `$.json()`, `$.view()`...) are described in [Controller](../../guides/controller/). ## Methods and paths The 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. The action can be: - a function, called with the controller; - a string, the name of a view that is rendered; - missing, then a view named after the first segment of the path is rendered (`index` for `/`). ```js exports.install = function() { ROUTE('GET /', 'index'); // views/index.html ROUTE('GET /about/'); // views/about.html ROUTE('GET /pricing/', 'cms/pricing'); }; ``` ## Dynamic parameters and wildcards A 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. ```js exports.install = function() { ROUTE('GET /users/{id}/orders/{order}/', function($) { $.json({ user: $.params.id, order: $.params.order }); }); ROUTE('GET /docs/*', function($) { // /docs/, /docs/a/, /docs/a/b/c/ ... $.plain($.url); }); }; ``` A `*` 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. ## Authorization: `+` and `-` Prefix 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. ```js exports.install = function() { ROUTE('+GET /account/', 'account'); ROUTE('-GET /account/', 'login'); ROUTE('+POST /account/password/', password); }; ``` You can declare the same URL twice, once with `+` and once with `-`, as above. ## Actions with `-->` Instead 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()`). ```js exports.install = function() { ROUTE('GET /api/products/ --> Products/list'); ROUTE('+POST /api/products/ --> Products/insert'); ROUTE('+PUT /api/products/{id}/ --> Products/update'); ROUTE('+POST /api/orders/ --> Orders/insert Orders/read (response)'); }; ``` With several actions, `(response)` marks the action whose result is the response. ## API routes with `?` `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. ```js exports.install = function() { ROUTE('API ? products_list --> Products/list'); ROUTE('API ? products_read/{id} --> Products/read'); ROUTE('+API ? products_save --> Products/save'); ROUTE('+API ? products_remove/{id} --> Products/remove'); }; ``` ```js // client AJAX('POST /api/', { schema: 'products_read/123', data: null }, console.log); ``` `+API` and `-API` set the authorization of each endpoint separately. A missing parameter is answered with an error for `params.`, and an unknown endpoint or a body without `schema` with `400`. ## Flags Flags follow the path. `@flag` limits when the route matches, `#name` runs a middleware, ` Promo/read'); // later route.remove(); endpoint.remove(); ``` ## CORS Requests with an `Origin` header from another host are checked against `CONF.$cors`. Set it with `CORS()` or in `/config`. ```js CORS(); // any origin CORS('https://app.example.com,https://admin.example.com'); CORS('+https://partner.example.com'); // add one more CORS('*example.com'); // any origin that contains example.com ``` An 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)`. ## Proxies `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. ```js PROXY('/cdn/', 'https://cdn.example.com').copy('extend').timeout(10000); PROXY('/legacy/', '/var/run/legacy.sock'); ``` The forwarded request gets `X-Forwarded-For`, `X-Forwarded-URL` and `X-Forwarded-Host`. When the target fails, the client gets `503`. --- title: Controller project: Total.js V5 version: 0.0.20 section: guides language: en license: MIT url: https://totaljs.es/docs/total-js-v5/0-0-20/guides/controller/ updated: 2026-11-19T16:16:52.152Z --- # Controller > The `$` object of a route action: request data, uploaded files, responses, errors, headers and cookies. In 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. ```js exports.install = function() { ROUTE('GET /products/{id}/', detail); }; function detail($) { $.json({ id: $.params.id, ip: $.ip }); } ``` The routes themselves are described in [Routing](../routing/). The full list of properties and methods is in the reference of [Controller](../../reference/controller/). ## Request data | Property | What it contains | | --- | --- | | `$.method` | The HTTP method in upper case (`GET`, `POST`...) | | `$.url` | The path of the URL, with a trailing slash and without the query string | | `$.split` | The segments of the path as an array (`/a/b/` gives `['a', 'b']`) | | `$.params` | The dynamic parts of the URL (`{id}`) as strings | | `$.query` | The query string as an object (`?page=2` gives `{ page: '2' }`) | | `$.body` | The parsed body: JSON, a URL-encoded form or the fields of a multipart form | | `$.files` | Uploaded files of a `multipart/form-data` request | | `$.payload` | The raw body as a `Buffer` (not for multipart requests) | | `$.headers` | The request headers, with lower-case names | | `$.ip` | The IP address of the client (the first `X-Forwarded-For` address behind a proxy) | | `$.ua` | A short name of the system and the browser, parsed from `User-Agent` | | `$.mobile`, `$.robot` | `true` for mobile devices, or for crawlers | | `$.xhr` | `true` when the request has `X-Requested-With: XMLHttpRequest` | | `$.user` | The user returned by your authorization delegate, or `undefined` | | `$.language` | The language returned by your localization delegate, or an empty string | | `$.protocol`, `$.host`, `$.address` | `http` or `https`, the `Host` header and the full URL | | `$.req`, `$.res` | The Node.js request and response objects | ```js exports.install = function() { ROUTE('POST /api/contact/', contact); }; function contact($) { var model = $.body; var page = $.query.page; var agent = $.headers['user-agent']; $.success(); } ``` Values 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`. ## Uploaded files The 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. ```js exports.install = function() { ROUTE('POST /upload/ <5MB', upload); }; function upload($) { var file = $.files[0]; if (!file || !file.isImage) { $.invalid('@(Upload an image)'); return; } file.move(PATH.public('photos/' + UID() + '.' + file.extension), function(err) { if (err) $.invalid(err); else $.success(); }); } ``` The flag `<5MB` raises the size limit of the body for this route (the default is the configuration key `$httpmaxsize`, 256 kB). See [Routing](../routing/). ## Sending a response Each method below ends the request. Call only one of them per request. | Method | Response | | --- | --- | | `$.json(value)` | JSON | | `$.success([value])` | `{ success: true, value: value }` as JSON | | `$.invalid(error)` | An error as JSON, with status 400 or the status of the error | | `$.jsonstring(text)` | A string that is already JSON | | `$.html(text)`, `$.plain(text)`, `$.xml(text)` | Text with the right content type | | `$.view(name, [model])` | A rendered view | | `$.file(path, [download])` | A file from the disk | | `$.stream(type, stream, [download])` | A readable stream | | `$.binary(buffer, type, [download])` | A `Buffer` | | `$.content(value, [type])` | A string or a `Buffer` with your content type | | `$.redirect(url, [permanent])` | A redirect with 302, or 301 | | `$.empty()` | Status 204 without a body | | `$.fallback(code, [error])` | An error page (or JSON for XHR requests) | ```js exports.install = function() { ROUTE('GET /api/products/', list); ROUTE('GET /download/', download); ROUTE('GET /old/', function($) { $.redirect('/new/', true); }); }; function list($) { NOSQL('products').find().callback(function(err, response) { if (err) $.invalid(err); else $.json(response); }); } function download($) { $.file(PATH.root('reports/2025.pdf'), 'report.pdf'); } ``` `$.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()`. ```js ROUTE('GET /api/debug/', function($) { $.json({ id: 1, password: 'secret' }, true, function(key, value) { return key === 'password' ? undefined : value; }); }); ``` `$.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: ... }`. ## Errors `$.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. ```js function update($) { if (!$.body.name) { $.invalid('Name is required'); return; } if (!$.user) { $.invalid(401); return; } $.success($.body.name); } ``` `$.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. ```js function report($) { F.Fs.readFile(PATH.root('reports/2025.csv'), function(err, buffer) { if (err) $.invalidsafe('The report is not available', err); else $.content(buffer, 'text/csv'); }); } ``` `$.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. ## Status and headers The response that will be sent is in `$.response`. Change `$.response.status` and `$.response.headers` before you call a response method: ```js function create($) { $.response.status = 201; $.response.headers['x-version'] = '1'; $.json({ id: UID() }); } ``` For 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. ## Cookies `$.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`. ```js function login($) { $.cookie('session', 'abc123', '7 days', { httponly: true }); $.success(); } function profile($) { var session = $.cookie('session'); $.json({ session: session }); } ``` To remove a cookie, set it with an empty value and a date in the past. ## Views `$.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/). ```js function homepage($) { $.layout('layout'); $.view('index', { title: 'Home' }); } ``` ## Other helpers - `$.action(name, model)` runs an action with this controller (see [Actions](../actions/)). - `$.authorize([callback])` runs your authorization delegate manually and fills `$.user`. - `$.proxy(url)` forwards the request to another server and sends its answer. - `$.hostname([path])` returns `protocol://host` with an optional path. - `$.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. - `$.touch([url])` clears the cached state of a static file after you change it (see [Static files](../static-files/)). - `$.csrf()` creates a CSRF token. - `$.custom()` tells the framework that you write to `$.res` yourself. --- title: Actions project: Total.js V5 version: 0.0.20 section: guides language: en license: MIT url: https://totaljs.es/docs/total-js-v5/0-0-20/guides/actions/ updated: 2026-11-19T16:16:52.152Z --- # Actions > Declare business logic with NEWACTION(), validate its input, expose it as a route and run it from code with ACTION(). An **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. ```js // actions/products.js NEWACTION('products_create', { name: 'Create a product', input: '*name:String, price:Number, description:String', route: '+POST /api/products/', action: function($, model) { model.id = UID(); model.dtcreated = NOW; DATA.insert('products', model).callback($.done(model.id)); } }); ``` Put 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. ## Declaring an action `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. | Option | What it does | | --- | --- | | `action` | `function($, model)`, the logic | | `input` | Schema of the payload (the body); the validated result is `$.model` | | `output` | Schema of the response; the value of `$.callback()` is cleaned by it | | `params` | Schema of the dynamic URL parameters (`$.params`) | | `query` | Schema of the query string (`$.query`) | | `user` | `true` requires a signed-in user, `false` requires an anonymous request | | `sa` / `su` | Requires a user with the `sa` or `su` flag | | `permissions` | Required permissions, `'products_create,admin'` or an array | | `route` | A route that runs the action, e.g. `'+POST /api/products/'` | | `middleware` | Names of middleware to run before the action, `'auth, ratelimit'` | | `partial` | Validates the input partially (only the fields that are sent) | | `extend` | Puts the response into the payload under this key and returns the payload | | `audit` | `true` or a template; writes an audit record after success | | `config` | Any object; available as `$.config` | | `timeout` | Milliseconds; the action fails with `Timeout.` when it does not respond in time | | `cache` | `true` or `{ query, params, input, user, language, key, expire }`; keeps the response in the cache | | `oninput` | `function($)`, called right before `action` | | `onoutput` | `function(err, response, $)`, called after the action responds | | `summary` | A description of the action; the MCP server uses it as the description of the tool | | `mcp` | `true` makes the action a tool of the [MCP server](../../guides/mcp-server/) | A 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.`. ## The `$` object The first argument of `action` is an options object, usually named `$`. It carries the data of the call and the methods that finish it. ```js NEWACTION('orders_read', { params: '*id:UID', query: 'fields:String', user: true, action: function($) { var id = $.params.id; var user = $.user; DATA.read('orders').id(id).where('userid', user.id).error(404).callback($); } }); ``` | Property | What it contains | | --- | --- | | `$.model` | The validated payload (aliases `$.payload` and `$.value`) | | `$.input` | Another alias of `$.model` | | `$.params` | The validated URL parameters | | `$.query` | The validated query string | | `$.user` | The user of the request, or the user passed to `ACTION().user()` | | `$.config` | The `config` option of the action | | `$.id` | The name of the running action | | `$.controller` | The controller of the HTTP request, or `undefined` | | `$.error` | The `ErrorBuilder` of the call | | `$.xhr` | `true` for an XHR request, `null` without a controller | | `$.meta` | The definition object of the action | | `$.env` | The value passed to `ACTION().env()`, or `undefined` | | `$.ip`, `$.headers`, `$.url`, `$.files`, `$.language`, `$.ua` | Shortcuts to the controller, empty without one | An action ends with exactly one of these calls: - `$.success([value])` responds with `{ success: true, value: value }`. - `$.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($)`. - `$.done([value])` returns a `function(err, response)` callback: an error becomes `$.invalid()`, otherwise it calls `$.success(value)`, or `$.success(response)` when `value` is `true`. - `$.invalid(error, [path], [index])` fails the call. A number above 399 is an HTTP status (`$.invalid(404)`); a string is an error message. `$.redirect(url)` redirects the HTTP request instead of responding. `$.output('html')` changes how a route responds (the default is JSON). `$.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. ```js NEWACTION('orders_invoice', { action: async function($) { try { var template = await F.FsPromises.readFile(PATH.root('templates/invoice.html'), 'utf8'); $.success(template.length); } catch (e) { $.invalidsafe('The invoice can\'t be created', e); } } }); ``` `$.touch([url])` clears the cached state of a static file after you change it (see [Static files](../../guides/static-files/)), the same as `TOUCH()`. ## Routes The `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. ```js NEWACTION('products_list', { query: 'search:String, page:Number', route: 'GET /api/products/', action: function($) { var builder = DATA.list('products'); $.query.search && builder.search('name', $.query.search); builder.paginate($.query.page, 20); builder.callback($); } }); ``` A 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. ```js exports.install = function() { ROUTE('+POST /api/orders/ --> orders_create orders_notify (response) orders_stats'); ROUTE('+API ? +orders_create --> orders_create'); }; ``` A `+` 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/). `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. ```js NEWACTION('account_read', { user: true, route: true, action: function($) { $.success($.user.name); } }); ``` ## Running actions from code `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. ```js ACTION('products_create', { name: 'Keyboard', price: 49 }).user(user).callback(function(err, response) { if (err) console.log(err.toString()); else console.log(response); }); ``` | Method | What it does | | --- | --- | | `.callback(fn)` | `function(err, response)`, or an existing `$` that receives the result | | `.promise([$])` | Returns a Promise; with `$`, an error goes to `$.invalid()` | | `.user(user)` | Sets `$.user` (it also accepts a `$` and takes its user) | | `.query(obj)` / `.params(obj)` | Sets the query string and the URL parameters | | `.ctrl(controller)` | Runs the action with a controller | | `.autorespond()` | Sends the response (or the error) to the controller | | `.status(fn)` | Receives the values the action sends with `$.status()` | | `.progress(fn)` | Receives the values the action sends with `$.progress()` | | `.config(obj)` | Adds keys to `$.config` for this call only | | `.env(value)` | Sets `$.env`, a value that tells the action where it is called from | Inside 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. ```js NEWACTION('orders_checkout', { input: '*productid:UID, *count:Number', user: true, action: async function($, model) { var order = await $.action('orders_create', model).promise($); var payment = await $.action('payments_create', { orderid: order.value }).promise($); $.success(payment); } }); ``` After every successful action, the framework emits the event `@` with `($, response)`: ```js ON('@products_create', function($, response) { console.log($.user.name, 'created', response.value); }); ``` The 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: ```js NEWACTION('notes_save', { input: '*body:String', oninput: function($) { $.input.body = $.input.body.trim(); }, onoutput: function(err, response, $) { console.log($.id, 'done', response); }, action: function($, model) { $.success(model.body.length); } }); ``` ## Caching the response The `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). ```js NEWACTION('Products|list', { query: 'page:Number', cache: { query: true, key: 'products', expire: '10 minutes' }, action: function($) { DATA.list('products').page($.query.page, 20).callback($); } }); NEWACTION('Products|save', { input: '*id:UID,*name:String', action: function($, model) { DATA.update('products', model).id(model.id).callback(function() { CACHE.reset('action|products|'); // the next list is read again $.success(); }); } }); ``` Errors are not cached. Without `user`, every user gets the same cached response, so do not cache answers that depend on the user without it. ## Schemas `NEWSCHEMA(name, callback)` groups actions under a common prefix. The callback receives an object whose `action(name, options)` creates the action `/`. ```js NEWSCHEMA('Products', function(schema) { schema.action('list', { route: 'GET /api/products/', action: function($) { DATA.find('products').callback($); } }); }); // The action name is 'Products/list' ``` ## Transformations A 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()`. ```js NEWTRANSFORM('product', function($, value) { value.name = value.name.trim(); $.next(); }, 'name'); NEWTRANSFORM('product', function($, value) { $.value = { id: value.id, name: value.name, price: value.price }; $.next(); }); TRANSFORM('product', { id: 1, name: ' Mouse ', price: 9, stock: 3 }, function(err, response) { console.log(response); // { id: 1, name: 'Mouse', price: 9 } }); ``` A 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: ```js NEWACTION('products_read', { params: '*id:UID', action: async function($) { var item = await DATA.read('products').id($.params.id).promise($); $.callback(await TRANSFORM('product', item, $)); } }); ``` Without 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. --- title: Schemas and validation project: Total.js V5 version: 0.0.20 section: guides language: en license: MIT url: https://totaljs.es/docs/total-js-v5/0-0-20/guides/json-schemas/ updated: 2026-11-19T16:16:57.153Z --- # Schemas and validation > Inline schemas, JSON schemas and ErrorBuilder: how Total.js 5 validates and converts data. Total.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. You can write a schema in two ways: - an **inline schema**, a short string such as `'*name:String,email:Email,age:Number'`; - a **JSON schema**, a plain object with `type`, `properties`, `required` and other keywords. An inline schema is turned into a JSON schema object, so both ways end in the same format and the same validator. ## Inline schemas An 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. ```js var schema = '*name:String,*email:Email,age:Number,newsletter:Boolean'.toJSONSchema(); var result = schema.transform({ name: ' Peter ', email: 'PETER@EXAMPLE.COM', age: '33' }); // result.error === null // result.response === { name: 'Peter', email: 'peter@example.com', age: 33, newsletter: false } ``` `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. ### Modifiers | Syntax | Meaning | | --- | --- | | `*name:String` | The field is required (`!name:String` is the same) | | `name:String(50)` | The text can have at most 50 characters | | `tags:[String]` | An array of values of the type | | `type:{draft\|published}` | The value must be one of the listed values | | `address:{street:String,city:String}` | A nested object with its own fields | | `address:@Address` | A nested object validated by the registered schema `Address` | | `name:String // Enter your name` | A custom error message for the field | A 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. ### Types | Type | What it does with the value | | --- | --- | | `String`, `Text` | Converted to a string and trimmed | | `String2` | Like `String`, but an empty value becomes `null` | | `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 | | `SmallInt` | A number from -32767 to 32767 | | `TinyInt` | A number from 0 to 255 | | `Boolean`, `Bool` | `true` or `false`; strings like `'true'`, `'1'` or `'on'` are parsed | | `Date` | A `Date` object, or `null` | | `Email` | Spaces removed, lower case, must be a valid email | | `Email2` | Like `Email`, and the tag is removed: `name+tag@domain.com` gives `name@domain.com` | | `Phone` | Spaces removed, must be a valid phone number | | `URL` | Must be a valid URL | | `Zip` | Must be a valid ZIP code | | `UID`, `GUID` | Must be a valid Total.js UID or a GUID; empty becomes `null` | | `Name` | Formatted as a person name (`'peter sirka'` gives `'Peter Sirka'`) | | `Lower`, `Lowercase`, `Upper`, `Uppercase` | Converted to lower or upper case | | `Capitalize`, `Capitalize2` | First letter of every word, or only of the first word, in upper case | | `Color` | A hex color: `#RGB`, `#RRGGBB` or `#RRGGBBAA` | | `Icon` | An icon class such as `ti ti-home` or `fa fa-check` | | `Base64` | Must be a Base64 string; empty becomes `null` | | `JSON` | A string that looks like JSON (see `String.isJSON()`); it is kept as text and empty becomes `null` | | `IP` | An IPv4 or IPv6 address; trimmed, empty becomes `null` | | `DataURI` | Must be a Base64 data URI; parsed into `{ type, buffer }` | | `DataURI2` | Must be a Base64 data URI; kept as the original text | | `SafeString` | Rejected when it contains XSS or SQL injection patterns | | `Search` | Converted to a search string with `String.toSearch()` | Strings, 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. ```js var schema = 'color:Color,icon:Icon,photo:DataURI,avatar:DataURI2'.toJSONSchema(); var result = schema.transform({ color: '#FF0000', icon: 'ti ti-user', photo: 'data:image/png;base64,iVBORw0KGgo=', avatar: 'data:image/png;base64,iVBORw0KGgo=' }); // result.response.photo === { type: 'image/png', buffer: } // result.response.avatar === 'data:image/png;base64,iVBORw0KGgo=' ``` ### Enums, arrays and nested objects ```js var schema = `*title:String(100) status:{draft|published|archived} tags:[String] ratings:[Number] author:{name:String,email:Email} items:[{name:String,price:Number}]`.toJSONSchema(); ``` An 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: ```js var schema = 'order:{number:String,lines:[{sku:String,qty:Number}],shipping:{address:{street:String,city:String}}}'.toJSONSchema(); ``` The errors of a nested field have a path such as `author.email`, `items[1].price` or `order.shipping.address.city`. ### Registered schemas `NEWSCHEMA(name, schema)` registers an inline schema under a name. Other schemas and actions use it with `@name`. ```js NEWSCHEMA('@Address', '*street:String,*city:String,zip:Zip'); NEWSCHEMA('@Customer', `*name:String(50) *email:Email address:@Address branches:[@Address]`); ``` All registered schemas are in the `F.jsonschemas` object. `'...'.toJSONSchema(name)` registers the schema under `name` too. ## Schemas in actions The `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/). ```js NEWACTION('Customers/create', { input: '@Customer', action: function($, model) { // model is the validated object $.success(); } }); NEWACTION('Customers/list', { query: 'page:Number,limit:Number,search:Search', action: function($) { // $.query.page is a number $.callback([]); } }); ``` Errors 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. ## JSON schemas A JSON schema is an object. Register it with `F.newjsonschema()`, or put it in the `jsonschemas/` folder. ```js F.newjsonschema({ $id: 'Product', type: 'object', properties: { name: { type: 'string', maxLength: 100 }, sku: { type: 'string', subtype: 'uid' }, price: { type: 'number', minimum: 1 }, stock: { type: 'number', subtype: 'smallint' }, tags: { type: 'array', items: { type: 'string' }, uniqueItems: true }, supplier: { type: 'object', $ref: '#/definitions/Supplier' } }, required: ['name', 'price'], definitions: { Supplier: { type: 'object', properties: { name: { type: 'string' }, email: { type: 'string', subtype: 'email' } }, required: ['name'] } } }); var result = F.jsonschemas.Product.transform({ name: 'Mug', price: '9.90' }); ``` Supported 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`). ### The jsonschemas folder When 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. ## Errors and ErrorBuilder `ErrorBuilder` collects errors. Validation fills it, and you can use it on your own. ```js var err = new ErrorBuilder(); err.push('The order is closed'); err.push2('email'); // a field error err.output(); // [{ error: 'The order is closed' }, { name: 'email', error: 'The field "email" is invalid' }] ``` The 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. ## AI tools Two 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/). `schema.toAITool(name)` returns a tool definition in the common function format: ```js var schema = '*city:String // The name of the city,days:Number // Number of days'.toJSONSchema(); var tool = schema.toAITool('weather'); // { type: 'function', function: { name: 'weather', parameters: { type: 'object', properties: {...}, required: ['city'] } } } ``` `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']`: ```js var schema = '*city:String // The name of the city,days:Number // Number of days'.toJSONSchema(); var obj = schema.toAIObject('forecast', 'The weather forecast for a city'); // { name: 'forecast', description: 'The weather forecast for a city', type: 'object', additionalProperties: false, // properties: { city: { type: 'string', description: 'The name of the city' }, days: {...} }, required: ['city'] } ``` --- title: Views project: Total.js V5 version: 0.0.20 section: guides language: en license: MIT url: https://totaljs.es/docs/total-js-v5/0-0-20/guides/views/ updated: 2026-11-19T16:16:57.153Z --- # Views > HTML views with @{} commands: rendering, layouts, conditions, loops, sections, meta tags, imports, helpers and templates. A 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. ```html @{title('Products')}

@{model.name}

    @{foreach item in model.items}
  • @{item.name} - @{item.price}
  • @{end}
``` ## Rendering a view In 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)). ```js exports.install = function() { ROUTE('GET /', index); ROUTE('GET /contact/'); // renders /views/contact.html ROUTE('GET /products/', 'products'); // renders /views/products.html }; function index($) { $.view('index', { name: 'Shop', items: [{ name: 'Pen', price: 5 }] }); } ``` A 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. `$.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. ```js var html = F.view('mail/order', { id: 'A100' }, function(view) { view.language = 'sk'; }); ``` ## Layouts Every 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. ```html @{import('meta', 'default.css', 'default.js')} @{body} ``` Change 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`. ## Output and escaping `@{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. ```html

@{model.name}

@{!model.html}
@{model.items.length} @{repository.count = 5} ``` These variables are available in every view: | Variable | What it contains | | --- | --- | | `model` | The model passed to the view | | `repository` | An object shared by the view, its partial views and the layout | | `config` | The configuration (`CONF`) | | `controller` | The controller of the request (`undefined` in `F.view()`) | | `query`, `body`, `files` | The query string, the parsed body and the uploaded files of the request | | `user`, `session` | The user and the session of the request | | `language` | The language of the view: of the request, or `view.language` set for `F.view()` (an empty string by default) | | `url` | The path of the request, without the query string (`undefined` in `F.view()`) | | `helpers` | The custom helpers (`DEF.helpers`) | Global 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. `@{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: ```html Products ``` ## Conditions and loops ```html @{if model.stock > 10} In stock @{else if model.stock > 0} Last pieces @{else} Sold out @{fi} @{foreach item in model.items} @{if item.hidden}@{continue}@{fi}
  • @{index + 1}. @{item.name}
  • @{end} ``` `@{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`. ## Partial views and sections `@{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: ```html @{section scripts} @{end} @{section('scripts')} ``` ## Title, meta tags and imports `@{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 `` 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`. `@{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. ```html @{import('meta', 'favicon.ico', 'default.css', '@app.js')} @{import('reset.css + layout.css + forms.css')} @{import('/vendor/editor.js')} ``` ## Helpers A 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. ```js // /definitions/helpers.js DEF.helpers.price = function(value) { return value.format(2) + ' EUR'; }; ``` ```html <span>@{price(model.price)}</span> ``` ## Localization Text 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. ```html <h1>@(Welcome to our shop)</h1> ``` ## Compression When 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>`. ## Templates `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. ```js var html = await TEMPLATE('invoice', { number: 'F001', items: items }); ``` ```html <!-- /templates/invoice.html --> <h1>Invoice {{ value.number }}</h1> {{ foreach item in value.items }} <p>{{ item.name }}: {{ item.price | format(2) }}</p> {{ end }} ``` --- title: Running in production project: Total.js V5 version: 0.0.20 section: guides language: en license: MIT url: https://totaljs.es/docs/total-js-v5/0-0-20/guides/production/ updated: 2026-11-18T19:21:30.967Z --- # Running in production > Run a Total.js application on a server: no watcher, the right address, automatic restarts, nginx, clean stops and logs. This 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/). ## Start without the watcher In the start script, uncomment this line: ```js options.watcher = false; ``` Then start the application from its directory: ```bash $ node index.js ``` The 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. The working directory is the application root, so a start from another directory does not find the routes of the application. The `--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. ## Choose the address and the port By default the application listens on all network interfaces. Set the address and the port in the start script: ```js options.ip = '127.0.0.1'; options.port = 8000; ``` Or set them in the `config` file: ```text $ip : 127.0.0.1 $port : 8000 ``` The port comes from the first of these that is set: | Order | Source | Example | | --- | --- | --- | | 1 | The start option | `options.port = 8000;` | | 2 | The configuration key | `$port : 8000` | | 3 | A number in the command line | `node index.js 8001` | | 4 | The default | `8000` | The 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`. With 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. ## Keep the application running An 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`: ```js ON('error', function(obj) { console.log('Application error:', obj.error); }); ``` When 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`: ```dockerfile FROM node:24-alpine WORKDIR /app COPY package.json package-lock.json ./ RUN npm ci --omit=dev COPY . . RUN chown -R node:node /app USER node CMD ["node", "index.js"] ``` Create `.dockerignore`: ```text node_modules tmp logs ``` Create `compose.yaml`. The `nginx` service and its `nginx.conf` file are described in the next section: ```yaml services: app: build: . restart: unless-stopped nginx: image: nginx:1.29-alpine restart: unless-stopped ports: - "80:80" volumes: - ./nginx.conf:/etc/nginx/conf.d/default.conf:ro depends_on: - app ``` Build and start both services: ```bash $ docker compose up -d --build ``` With `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: ```bash $ docker inspect -f '{{.RestartCount}}' $(docker compose ps -a -q app) ``` During 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. ## Put nginx in front Create `nginx.conf` next to `compose.yaml`: ```nginx map $http_upgrade $connection_upgrade { default upgrade; '' close; } server { listen 80; location / { proxy_pass http://app:8000; proxy_http_version 1.1; proxy_set_header Host $host; proxy_set_header X-Forwarded-For $remote_addr; proxy_set_header X-Forwarded-Proto $scheme; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection $connection_upgrade; } } ``` `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. The `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. While the application is down, nginx answers `502`. When the application is back, nginx reaches it again without a restart of nginx. ## What the application sees behind the proxy The `proxy_set_header` lines decide what the application reads from a request: | Value | Source | Result | | --- | --- | --- | | `$.ip` | First address in `X-Forwarded-For` | The address of the client | | `client.ip` (WebSocket) | First address in `X-Forwarded-For` | The address of the client | | `$.protocol` | `X-Forwarded-Proto` | `https` when the header is `https`, otherwise `http` | | `$.host` | `Host` | The host name the client asked for | | `$.hostname('/x')` | `X-Forwarded-Proto` and `Host` | `https://www.example.com/x` | | `$.address` | `X-Forwarded-Proto`, `Host` and the URL | `https://www.example.com/info/` | The framework trusts `X-Forwarded-For` on every request and reads its first address. Two rules follow from this: - 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. - Do not let clients connect to the application directly, because they can then send the header themselves. ## Stop the application cleanly The signals `SIGTERM` and `SIGINT` stop the application. `docker stop` and `docker compose stop` send `SIGTERM`, and the container ends in less than three seconds. After the signal: 1. The `exit` event runs. 2. The application refuses new connections. 3. About 300 ms later the process exits with code `1`. The exit code is `1` after a clean stop too, so do not read it as a crash. The 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. Use the `exit` event for short work, for example in `definitions/exit.js`: ```js const Fs = require('node:fs'); ON('exit', function() { Fs.appendFileSync(PATH.root('stopped.log'), new Date().toISOString() + '\n'); }); ``` Keep 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. ## Logs The application writes no log file by default. All output goes to the standard streams of the process: | Output | Stream | | --- | --- | | `console.log()` | stdout | | The start information | stdout | | Errors logged by the framework (`ERROR ======= ...`) | stdout | | `console.warn()` and `console.error()` | stderr | Docker collects both streams: ```bash $ docker compose logs app ``` To write to a file instead, add this key to the `config` file: ```text $logger : true ``` `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`. --- title: Configuration project: Total.js V5 version: 0.0.20 section: guides language: en license: MIT url: https://totaljs.es/docs/total-js-v5/0-0-20/guides/configuration/ updated: 2026-11-16T15:32:37.496Z --- # Configuration > The config file and its types, .env, CONF, LOADCONFIG() and DEBUG. The 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. ``` name : My application $api : /api/ $httpmaxsize : 1024 $cors : https://app.example.com mail_from : info@example.com smtp (json) : {"server":"smtp.example.com","port":465,"user":"info@example.com","password":"secret"} ``` ```js // anywhere in the code console.log(CONF.name); // My application console.log(F.config.$api); // /api/ ``` Keys 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. ## The format of the file Each 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). - Empty lines and lines that start with `#` or `//` are ignored. - `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. - A value that starts with `base64 ` or `hex ` is decoded to a string first. A type in parentheses after the key converts the value: | Type | Result | | --- | --- | | `(number)`, `(float)`, `(double)`, `(currency)` | A number | | `(boolean)`, `(bool)` | `true` when the value contains `true`, `on`, `1` or `enabled` | | `(array)` | An array of strings, split by commas and trimmed | | `(json)`, `(object)` | The parsed JSON | | `(eval)` | The result of a JavaScript expression | | `(date)`, `(time)`, `(datetime)` | A `Date` | | `(env)`, `(environment)` | The value of the environment variable with that name | | `(config)` | The value of another key that is already in `CONF` | | `(random)` | A new random identifier of the given length (default 10) on every start | | `(generate)`, `(hash)` | A random string of the given length (default 10), created once and kept | ``` $httptimeout (number) : 10 allowed (array) : admin, editor limits (json) : {"files":10,"size":5} started (date) : 2025-01-01 db (env) : DATABASE_URL appname (config) : name token (generate) : 32 logo : base64 aGVsbG8= ``` `(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. `(config)` reads `CONF` before the file is applied: it sees the defaults and the values loaded earlier, not the keys of the same file. Use `(number)` for every numeric value of your own keys. ## Environment variables and `.env` Before 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. ``` # .env DATABASE_URL=postgresql://user:pass@localhost:5432/app API_KEY="abc123" ``` The `config` file reads them with the `(env)` type: ``` database (env) : DATABASE_URL apikey (env) : API_KEY ``` The framework itself reads a few variables: `PORT` (see the port below), and it sets `TZ` from `$timezone` and `NODE_TLS_REJECT_UNAUTHORIZED` from `$insecure`. ## Loading order When the application starts, the framework loads, in this order: 1. The `config` object from the options of `F.http()` (for example `F.http({ config: { name: 'Shop' } })`). 2. The file `.env`. 3. The file `config`. Its values win over the options. 4. The file `version`: its first line, as a number, becomes `CONF.version`. 5. The `config` file of each plugin, before the other files of the plugins. Only 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. In debug mode the watcher restarts the application when the `config` file of the application or of a plugin changes. ## Plugin configuration A 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. ``` # plugins/invoices/config invoices_currency : EUR invoices_due (number) : 14 ``` ```js // plugins/invoices/index.js exports.install = function() { var days = CONF.invoices_due; }; ``` See [Plugins and components](../plugins-and-components/) for the rest of the plugin structure. ## Common keys | Key | Default | Meaning | | --- | --- | --- | | `name` | `Total.js` | The name of the application: page titles, e-mails, the start screen | | `version` | `1.0.0` | The version; also read from the `version` file | | `author` | `''` | Printed on the start screen | | `secret` | | The key for `ENCRYPT()`/`DECRYPT()` and signed values; set your own | | `secret_csrf` | `''` | Enables CSRF tokens; see [Authorization](../authorization/) | | `secret_encryption` | `''` | The key for encrypted WebSocket messages | | `mail_from`, `mail_from_name`, `mail_reply`, `mail_cc`, `mail_bcc` | | Defaults for `MAIL()`; see [Mail](../mail/) | | `smtp` (or `mail`) | | The SMTP options as JSON; `mail_smtp` and `mail_smtp_options` set the server and the options separately | | `$root` | `''` | A prefix for all routes and static files, e.g. `/app/` | | `$api` | `/api/` | The URL that replaces `?` in API routes | | `$port`, `$ip` | `auto`, `0.0.0.0` | Where the HTTP server listens | | `$timezone` | `utc` | The time zone of the process (`TZ`) | | `$httpmaxsize` | `256` | The maximum size of a request body in kB | | `$httptimeout` | `5` | The request timeout in seconds | | `$cors` | `''` | Allowed origins for cross-origin requests | `$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. ## Changing the configuration at runtime `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. ```js // from a database, for example LOADCONFIG({ name: 'Shop', $cors: 'https://shop.example.com' }); LOADCONFIG('$httptimeout (number) : 15\n$minifyhtml : false'); ON('$reconfigure', function() { console.log('New name:', CONF.name); }); ``` You 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()`. ## `DEBUG` The 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: ```js if (DEBUG) console.log('Running in debug mode'); ``` `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. --- title: Authorization project: Total.js V5 version: 0.0.20 section: guides language: en license: MIT url: https://totaljs.es/docs/total-js-v5/0-0-20/guides/authorization/ updated: 2026-11-18T15:27:34.798Z --- # Authorization > Decide who the user of a request is with AUTH(), protect routes and actions, and use built-in sessions. Total.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. ```js // definitions/auth.js AUTH(function($) { var token = $.headers['x-token']; if (token === 'secret-token') $.success({ id: '1', name: 'Peter', sa: true }); else $.invalid(); }); ``` ## The delegate The 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: | Call | Result | | --- | --- | | `$.success(user)` | The request is authorized and `user` becomes `$.user` | | `$.invalid()` | The request is not authorized and the user is `undefined` | The 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. Without an `AUTH()` delegate no user is ever assigned and the `+` and `-` flags of routes are not checked. ## Route flags `+` and `-` Put the flag in front of the HTTP method: ```js exports.install = function() { ROUTE('+GET /admin/', dashboard); ROUTE('-GET /login/', 'login'); ROUTE('-POST /api/login/ --> Account/login'); ROUTE('+GET /api/logout/ --> Account/logout'); ROUTE('GET /', 'index'); }; ``` | Flag | Who may call the route | | --- | --- | | `+` | Only an authorized request (the delegate called `$.success()`) | | `-` | Only an unauthorized request (the delegate called `$.invalid()`) | | none | Everybody | The 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`. For API routes the flag belongs to the whole `API` line and is checked for every endpoint: `ROUTE('+API /api/ products_save --> Products/save')`. ## The user in controllers and actions ```js function dashboard($) { $.json({ id: $.user.id, name: $.user.name }); } NEWACTION({ id: 'Account/profile', action: function($) { $.success({ id: $.user.id, name: $.user.name }); } }); ``` When 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. ## Roles and permissions Total.js reads two conventions of the user object: - `user.sa` or `user.su` (super admin) passes every check. - `user.permissions` or `user.roles` hold what the user may do, as an array (`['products', 'orders']`) or as an object (`{ products: true }`). `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`: ```js NEWACTION({ id: 'Products/remove', params: '*id:UID', action: function($) { if (UNAUTHORIZED($, 'products', 'admin')) return; $.success(); } }); ``` Actions 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). ## Built-in sessions Pass 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: ```js // definitions/auth.js var opt = {}; opt.secret = 'a-long-random-string'; opt.cookie = '__user'; opt.expire = '10 minutes'; opt.ddos = 10; opt.options = { httponly: true, security: 'lax' }; opt.onread = function(meta, next) { // meta: { sessionid, userid, ip, ua } DATA.read('tbl_user').fields('id,name,sa,permissions').id(meta.userid).where('isdisabled', false).callback(next); }; AUTH(opt); MAIN.session = opt; ``` The 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`). Sign in and sign out from actions: ```js NEWACTION({ id: 'Account/login', input: '*email:Email,*password:String', action: function($, model) { if (BLOCKED($, 10)) { $.invalid(401); return; } DATA.read('tbl_user').where('email', model.email).where('password', model.password.sha256(CONF.secret)).callback(function(err, user) { if (user) { BLOCKED($, null); MAIN.session.authcookie($, UID(), user.id, '1 month'); $.success(); } else $.invalid(401); }); } }); NEWACTION({ id: 'Account/logout', action: function($) { MAIN.session.logout($); $.success(); } }); ``` `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. ## Brute-force protection `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. --- title: Encryption project: Total.js V5 version: 0.0.20 section: guides language: en license: MIT url: https://totaljs.es/docs/total-js-v5/0-0-20/guides/encryption/ updated: 2026-11-16T15:32:32.495Z --- # Encryption > Encrypt values with ENCRYPT() and DECRYPT(), bind them to the client of a request with ENCRYPTREQ() and DECRYPTREQ(), and choose the cipher. `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. ```js var token = ENCRYPT({ id: user.id, expire: NOW.add('1 day') }, 'reset'); var data = DECRYPT(token, 'reset'); ``` `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: ```js var token = ENCRYPTREQ($, { id: user.id }, 'download'); // later, in another request of the same browser var data = DECRYPTREQ($, token, 'download'); ``` To 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. --- title: Audit logs project: Total.js V5 version: 0.0.20 section: guides language: en license: MIT url: https://totaljs.es/docs/total-js-v5/0-0-20/guides/audit-logs/ updated: 2026-11-16T15:32:32.495Z --- # Audit logs > Record who did what with AUDIT() and $.audit(), audit actions after they succeed, and store the records where you need them. `AUDIT()` writes who did what. It reads the user, IP address, user agent, URL and action from `$`: ```js NEWACTION({ id: 'Orders/remove', params: '*id:UID', action: function($) { $.audit('Removed order {params.id} by {user.name}'); $.success(); } }); ``` A 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`. Each 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. --- title: Middleware project: Total.js V5 version: 0.0.20 section: guides language: en license: MIT url: https://totaljs.es/docs/total-js-v5/0-0-20/guides/middleware/ updated: 2026-11-16T15:32:42.496Z --- # Middleware > Run named functions before routes, WebSockets and actions with NEWMIDDLEWARE(). ## Creating a middleware Register 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. ```js // middleware/apikey.js exports.install = function() { NEWMIDDLEWARE('apikey', function($, next) { if ($.headers['x-api-key'] === CONF.apikey) next(); else $.invalid(401); }); }; ``` Files 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. The 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. ## Using a middleware in a route Add 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()`. ```js exports.install = function() { ROUTE('GET /api/orders/ #apikey', orders); ROUTE('POST /api/orders/ #apikey #ratelimit', create); ROUTE('SOCKET /live/ #apikey', live); }; function orders($) { $.json([]); } ``` For 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. A middleware can also prepare data for the action: ```js NEWMIDDLEWARE('company', function($, next) { $.company = $.headers['x-company'] || 'default'; next(); }); ``` ## Assigning a middleware to existing routes The 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. ```js ON('ready', function() { NEWMIDDLEWARE('audit', function($, next) { console.log($.method, $.url); next(); }, 'routes'); }); ``` `NEWMIDDLEWARE(name)` without a function removes the middleware: it is deleted from the registry and from every route that uses it. ## Middleware in actions An 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. ```js NEWMIDDLEWARE('tenant', function($, next) { if ($.user && $.user.tenantid) next(); else $.invalid(401); }); NEWACTION({ name: 'Orders/list', middleware: 'tenant', action: function($) { $.callback([]); } }); ``` See [Actions](../../guides/actions/) for the other options. --- title: Static files project: Total.js V5 version: 0.0.20 section: guides language: en license: MIT url: https://totaljs.es/docs/total-js-v5/0-0-20/guides/static-files/ updated: 2026-11-16T15:32:42.496Z --- # Static files > Serve the public folder with minification, caching, compression and ranges, and merge files into one. ## The public folder Every 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. Only 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: ``` $httpfiles : avif, glb ``` A `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. ## Minification and caching JavaScript, 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/)). In 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. Static responses carry these headers: | Header | Value | | --- | --- | | `Expires` | One year ahead (`CONF.$httpexpire`, refreshed every hour) | | `Cache-Control` | `public, must-revalidate, max-age=` + `CONF.$httpmaxage` (60 seconds) | | `Last-Modified` | The date of the file | | `ETag` | `858` + `CONF.$httpetag` (the app version without dots by default) | `CONF.$httpcacheoffset` (for example `'1 minute'`) moves the `Last-Modified` date of static files forward by that time; see [Configuration](../../guides/configuration/). `.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. When you change a file in `public/` while the app runs in release mode, clear its cached state with `TOUCH()`: ```js TOUCH('/css/default.css'); // one file, by its URL TOUCH(); // every static file ``` ## Compression and ranges With `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. A 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. ## Merging files `MERGE(url, files...)` creates a virtual file made of several files. It returns the URL, which you put in a view or a page. ```js exports.install = function() { MERGE('/css/all.css', 'bootstrap.min.css + default.css'); MERGE('/js/all.js', '/js/jquery.min.js', '/js/app.js', 'https://cdn.componentator.com/spa.min@20.js'); }; ``` A 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. --- title: WebSockets project: Total.js V5 version: 0.0.20 section: guides language: en license: MIT url: https://totaljs.es/docs/total-js-v5/0-0-20/guides/websockets/ updated: 2026-11-19T16:16:57.153Z --- # WebSockets > Real-time connections with SOCKET routes, the WebSocket object and its clients, compression, ping and the WebSocket client. A 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. ## A WebSocket route Declare 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**. ```js exports.install = function() { ROUTE('SOCKET /chat/', chat); }; function chat() { var self = this; self.on('open', function(client) { client.send({ type: 'welcome', id: client.id }); }); self.on('message', function(client, message) { // message is already parsed from JSON self.send({ type: 'message', from: client.id, body: message.body }); }); self.on('close', function(client, code, reason) { self.send({ type: 'left', id: client.id }); }); } ``` In the browser: ```js var ws = new WebSocket('ws://localhost:8000/chat/'); ws.onmessage = function(e) { var msg = JSON.parse(e.data); }; ws.onopen = function() { ws.send(JSON.stringify({ body: 'Hello' })); }; ``` The 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: ```js ROUTE('SOCKET /upload/ <5MB', upload); ROUTE('SOCKET /feed/', feed, 1024 * 1024); ``` ## One WebSocket object per URL The 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: ```js exports.install = function() { ROUTE('SOCKET /room/{name}/', room); }; function room() { var self = this; // self.params.name === 'sport' self.on('message', function(client, message) { self.send({ room: self.params.name, body: message.body }); }); } ``` `self.url`, `self.params`, `self.online` (the number of connected clients) and `self.connections` (an object `{ id: client }`) describe the group. ## Message formats A 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: | Flag | `message` event receives | `send()` writes | | --- | --- | --- | | (none) | a parsed object | JSON | | `@text` | a string | JSON, or the string as it is with `client.send(text, true)` | ```js ROUTE('SOCKET /terminal/ @text', function() { this.on('message', function(client, text) { client.send(text.toUpperCase(), true); }); }); ``` The `message` event also gets the size of the message in bytes as its third argument. ## Sending messages `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: ```js self.send({ type: 'notify' }, function(client) { return client.user && client.user.isadmin; }); ``` `websocket.find(fn)` returns the first client for which `fn(client)` returns `true`: ```js var target = self.find(function(client) { return client.user && client.user.id === message.to; }); target && target.send({ type: 'private', body: message.body }); ``` ## Notifying clients from outside the route An 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. Create `controllers/live.js`: ```js exports.install = function() { ROUTE('SOCKET /live/', live); ROUTE('POST /api/products/ --> products_create'); ROUTE('POST /api/maintenance/', maintenance); }; function live() { MAIN.live = this; } function maintenance($) { MAIN.live && MAIN.live.send({ type: 'maintenance', message: $.body.message }); $.success(); } ``` Create `actions/products.js` (see [Actions](../actions/)): ```js var products = []; NEWACTION('products_create', { input: '*name:String', action: function($, model) { var product = { id: UID(), name: model.name }; products.push(product); MAIN.live && MAIN.live.send({ type: 'product_created', product: product }); $.callback(product); } }); ``` Connect from the browser: ```js var ws = new WebSocket('ws://localhost:8000/live/'); ws.onmessage = function(e) { var msg = JSON.parse(e.data); if (msg.type === 'product_created') console.log('New product:', msg.product.name); }; ``` A 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. The 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. When 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: ```js function live() { var self = this; MAIN.live = self; self.autodestroy(function() { MAIN.live = null; }); } ``` A route with a dynamic URL has one WebSocket object per URL, so keep one reference per URL: ```js MAIN.rooms = {}; exports.install = function() { ROUTE('SOCKET /rooms/{name}/', room); ROUTE('POST /api/rooms/{name}/', notify); }; function room() { MAIN.rooms[this.params.name] = this; } function notify($) { var room = MAIN.rooms[$.params.name]; room && room.send({ type: 'notice', message: $.body.message }); $.success(); } ``` ## The client Each 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: ```js self.on('open', function(client) { client.nick = client.query.nick || 'guest'; }); ``` ## Authorization, CSRF and middleware Before 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: ```js ROUTE('+SOCKET /notifications/', notifications); ``` The `@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. ## Closing and cleaning up `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`. `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: ```js function room() { var self = this; var timer = setInterval(function() { self.send({ type: 'tick' }); }, 1000); self.autodestroy(function() { clearInterval(timer); }); } ``` The global event `websocket_end` is emitted when any client disconnects: `ON('websocket_end', function(websocket, client) {})`. ## Compression and encoding When 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: - `CONF.$wsencodedecode = true` sends messages through `encodeURIComponent()` and decodes incoming messages with `decodeURIComponent()`. - `websocket.encrypt()` encrypts outgoing and decrypts incoming messages of the group with `CONF.secret_encryption`. Both sides must use the same key. ## Ping and latency 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. `client.ping()` pings one client yourself. ## Removing a route `ROUTE()` returns the route. `route.remove()` removes it and destroys all its WebSocket objects, so every client is disconnected: ```js var route = ROUTE('SOCKET /live/', live); // later route.remove(); ``` ## WebSocket client `WEBSOCKETCLIENT([callback])` connects your application to another WebSocket server. Set the options and the events, then call `connect()`: ```js var client = WEBSOCKETCLIENT(); client.options.reconnect = 5000; client.headers['x-token'] = CONF.token; client.on('open', function() { client.send({ type: 'hello' }); }); client.on('message', function(message) { console.log(message); }); client.on('close', function(code, reason) { console.log('closed', code, reason); }); client.connect('wss://example.com/live/'); ``` Options of `client.options`: | Option | Default | Description | | --- | --- | --- | | `type` | `'json'` | `'json'`, `'text'` or `'binary'` | | `compress` | `true` | Offer `permessage-deflate` to the server | | `reconnect` | `3000` | Delay in ms before a reconnection after the connection closes; `0` disables it | | `reconnectserver` | | `true` also reconnects when the connection cannot be opened | | `masking` | `false` | Mask outgoing frames (required by servers that follow the RFC strictly) | | `encodedecode` | `false` | Encode/decode messages with `encodeURIComponent()` | | `encrypt` | | A key: messages are encrypted and decrypted with it | | `size` | `0` | Max. size in bytes of a decompressed message (`0` no limit) | | `rejectunauthorized` | `false` | Reject invalid TLS certificates | | `timeout` | `30000` | TCP keep-alive delay in ms for the socket (`0` disables it) | `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. ## Configuration | Key | Default | Description | | --- | --- | --- | | `$wsmaxsize` | `256` | Max. size of a message in kB | | `$wscompress` | `true` | Allow `permessage-deflate` compression | | `$wsencodedecode` | `false` | Encode/decode all messages with URI encoding | | `$wsmaxlatency` | `2000` | Max. latency in ms before a client is closed by the ping check | --- title: NoSQL database project: Total.js V5 version: 0.0.20 section: guides language: en license: MIT url: https://totaljs.es/docs/total-js-v5/0-0-20/guides/nosql/ updated: 2026-11-19T20:13:56.297Z --- # NoSQL database > The embedded NoSQL database: NOSQL(name), files in databases/, inserting, finding, updating and removing documents with the query builder. Total.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. ```js NOSQL('users').insert({ id: UID(), name: 'Peter', age: 33, dtcreated: NOW }).callback(function(err, response) { // response === 1 }); NOSQL('users').find().where('age', '>', 18).sort('name').take(10).callback(function(err, response) { // response is an array of documents }); ``` `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/). ## Files in databases/ `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. A name that contains a slash is used as a file path as it is, without the `.nosql` extension: ```js NOSQL('/data/shared/orders.nosql').find().callback(console.log); ``` The 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. All 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. ## Inserting `insert(doc)` appends the document. NoSQL does not generate any identifier, so add your own `id` (for example with `UID()`). The response is `1`. ```js NOSQL('products').insert({ id: UID(), name: 'Keyboard', price: 49.9, tags: ['usb', 'black'], dtcreated: NOW }).callback(function(err, response) { console.log('inserted', response); }); ``` Dates are stored as ISO strings and every read converts them back to `Date` objects, so you can compare them and sort by them. ## Finding documents `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. Without `sort()`, documents come from the end of the file: the most recently written first. Add `sort()` when the order matters. ```js NOSQL('products').find().where('price', '<', 100).in('tags', ['usb']).fields('id,name,price').sort('price', true).take(20).callback(function(err, items) { console.log(items); }); NOSQL('products').read().id('1abc8d001').callback(function(err, product) { console.log(product ? product.name : 'not found'); }); ``` ### Filters Every filter is joined with AND. Field names can be nested with a dot (`address.city`). | Method | Matches when | | --- | --- | | `where(name, [comparer], value)` | the field compares with the value; comparers `=` (default), `<>`, `!=`, `>`, `>=`, `<`, `<=` | | `id(value)`, `userid(value)` | the `id` or `userid` field equals the value (an array means "one of") | | `equal(obj)` | every key of the object equals its value | | `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 | | `between(name, a, b)` | the field is `>= a` and `<= b` | | `search(name, text, [where])` | the field contains the text (case-insensitive); `where` is `'beg'` or `'end'` | | `contains(name)`, `empty(name)` | the field has a value (a non-empty array), or it does not | | `year()`, `month()`, `day()` | a part of a `Date` field compares with a number | | `query(code)` | a JavaScript expression with `doc` is true | `or(fn)` groups the filters added inside the function with OR: ```js NOSQL('users').find().where('active', true).or(function(builder) { builder.search('name', 'peter'); builder.search('email', 'peter'); }).callback(console.log); ``` `query()` (and `where()` with only one argument) takes a raw JavaScript condition. The document is `doc`. Do not put user input into it. ```js NOSQL('orders').find().query('doc.items.length > 2 && doc.price > 100').callback(console.log); ``` ### Fields, sorting and paging - `fields('id,name,price')` returns only these fields; `fields('-password,-token')` returns everything except these fields. - `sort(name, [desc])` sorts by a field; call it again for a second key. `desc` is `true` or `'desc'`. - `take(count)` (alias `limit()`), `skip(count)` and `first()` limit the result. `first()` returns one object instead of an array. - `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. ```js function list($) { NOSQL('articles').find().where('published', true).sort('dtcreated', true).paginate($.query.page, $.query.limit, 50).callback($); } ``` ## Updating `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. ```js NOSQL('products').update({ price: 39.9, dtupdated: NOW }).id('1abc8d001').callback(function(err, count) { console.log('updated', count); }); ``` A prefix in a key changes how the value is applied: | Key | Effect | | --- | --- | | `'+stock': 5` | adds the number to the field (a missing field counts as `0`) | | `'-stock': 1`, `'*price': 1.1`, `'/price': 2` | subtracts, multiplies or divides the field by the number | | `'>maxorder': 3` | writes the value only when it is greater than the field (a missing field takes it) | | `'<minprice': 9` | writes the value only when it is smaller than the field | | `'!active': 1` | toggles a boolean field (the value is ignored) | | `'=total': 'doc.price * doc.count'` | evaluates a JavaScript expression with `doc` | ```js NOSQL('products').update({ '+stock': -1, '+sold': 1 }).id(id).callback(console.log); ``` In `insert()` the prefixes are removed: `'+stock': 5` stores `stock: 5` and `'!active'` stores `true`. ## Removing and maintenance `remove()` removes the documents that match the filter and responds with their count. Without a filter it removes all documents. ```js NOSQL('logs').remove().where('dtcreated', '<', NOW.add('-30 days')).callback(function(err, count) { console.log('removed', count); }); ``` - `clear()` deletes the whole file with all documents. - `clean()` rewrites the file without the lines of removed and replaced documents. ```js ON('service', function(counter) { // once a day if (counter % 1440 === 0) NOSQL('logs').clean(); }); ``` ## Getting the result All builders end in the same way: - `callback(fn)` (alias `pipe()`) calls `fn(err, response)`. In an action you can pass `$`, and the response goes straight to the client. - `promise([$])` returns a Promise; with `$` an error goes to `$.invalid()`. - `done($, fn)` calls `fn(response)` and sends an error to `$.invalid()`. - `data(fn)` and `fail(fn)` are called only with the response or only with the error. - `error(message)` turns an empty result (`undefined`, an empty array, `0` updated or removed) into an error. ```js NEWACTION('Products/detail', { params: '*id:UID', action: async function($) { var item = await NOSQL('products').read().id($.params.id).error('Not found').promise($); $.callback(item); } }); ``` `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. ## NoSQL through DATA NoSQL 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: ```js DATA.count('nosql/users').where('active', true).callback(function(err, response) { // response.count }); DATA.check('nosql/users').where('email', email).callback(function(err, exists) { // exists is true or false }); DATA.scalar('nosql/orders', 'sum', 'price').callback(function(err, response) { // response.value }); DATA.list('nosql/orders').page(2, 20).callback(function(err, response) { // response.items, response.count (all matching documents), response.page, response.pages }); ``` `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. For `DATA` with SQL databases see [QueryBuilder](../../guides/querybuilder/). --- title: QueryBuilder project: Total.js V5 version: 0.0.20 section: guides language: en license: MIT url: https://totaljs.es/docs/total-js-v5/0-0-20/guides/querybuilder/ updated: 2026-11-19T20:13:51.296Z --- # QueryBuilder > Query any database with one QueryBuilder: DATA, DB(), adapters, filters, paging and autoquery. Total.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. ```js DATA.find('users').where('isremoved', false).sort('name').take(20).callback(function(err, response) { console.log(err, response); }); ``` The full list of methods is in the reference of [QueryBuilder](../../reference/querybuilder/). ## The parts | Name | What it is | | --- | --- | | `DATA` | A global, shared database object. Every call on it starts one query at once. | | `DB()` | Creates a new database object that runs several queries one after another and collects their results. | | `NEWDB(name, fn)` | Registers an adapter: the function that executes the queries for the connection `name`. | | QueryBuilder | The object that `find()`, `insert()` and the other operations return. You chain filters on it. | ## Registering an adapter The 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: ```js NEWDB('default', function(filter, callback) { // filter.exec the operation: find, list, read, check, count, scalar, // insert, update, remove, query, drop, truncate, command // filter.table the table name // filter.filter the conditions: [{ type: 'where', name, comparer, value }, ...] // filter.fields, filter.sort, filter.take, filter.skip, filter.payload ... callback(null, []); }); ``` The 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. The 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/). ## Reading data ```js // all rows that match DATA.find('products').where('price', '>', 100).sort('price', true).callback(console.log); // one row (or null) DATA.read('products').id('p123').callback(console.log); // a page with metadata DATA.list('products').search('name', 'phone').page(2, 25).callback(function(err, response) { // response.items, response.count (from the adapter) // response.page, response.limit, response.pages (added by the QueryBuilder) }); // true or false DATA.check('users').where('email', 'peter@example.com').callback(console.log); // number of rows DATA.count('orders').where('status', 'paid').callback(console.log); ``` `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`. `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. ## Writing data ```js DATA.insert('users', { id: UID(), name: 'Peter', dtcreated: NOW }).callback(console.log); DATA.update('users', { name: 'Lucia', dtupdated: NOW }).id('u1').callback(console.log); DATA.remove('users').where('id', 'u1').callback(console.log); ``` Pass `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: ```js DATA.update('pages', { name: 'Home', dtupdated: NOW }, true).id('home').insert(function(doc) { doc.id = 'home'; doc.dtcreated = NOW; }).callback(console.log); ``` `returning('id,name')` asks the adapter to return those columns of the changed rows. ## Filters All filters are joined with AND. Put a group in `or()` to join it with OR. ```js DATA.find('users') .where('age', '>=', 18) // =, <>, >, <, >=, <= (== and != work too) .in('role', ['admin', 'editor']) .notin('id', ['u1', 'u2']) .between('dtcreated', NOW.add('-7 days'), NOW) .search('name', 'pet') // contains the text .or(function(builder) { builder.where('isblocked', false); builder.empty('dtblocked'); }) .fields('id,name,email') .callback(console.log); ``` | Method | Condition | | --- | --- | | `where(name, [comparer], value)` | Compare a column. With one argument it is a raw condition (`query()`). | | `id(value)`, `userid(value)` | `where('id', …)`, or `in('id', …)` for an array | | `equal(obj)` | One `where()` per key of the object | | `in()`, `notin()` | The value is (not) in a list | | `between(name, a, b)` | Between two values | | `search(name, value, [where])` | Text search; `where` can be `'beg'` or `'end'` | | `contains(name)`, `empty(name)` | The column has a value, or is empty | | `array(name, [comparer], value)` | A condition on an array column (`&&` by default) | | `year()`, `month()`, `day()`, `hour()`, `minute()` | Compare a part of a date | | `query(sql)` | A raw condition passed to the adapter as it is | The adapter translates these items into its own syntax, so which comparers and raw conditions work depends on the engine. ## Sorting and paging ```js DATA.find('products') .sort('price', 'desc') // or true .sort('name') // ascending .page(3, 20) // skip 40, take 20 .callback(console.log); ``` `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. ## Filters from a query string `autoquery()` builds the whole query from the query string of a request. You list the allowed fields and their types; everything else is ignored. ```js NEWACTION('Products/list', { name: 'List of products', action: function($) { DATA.list('products').autoquery($.query, 'id,name:string,price:number,dtcreated:date,ispublished:boolean', 'dtcreated_desc', 100).callback($); } }); ``` With `?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. `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/). `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: ```js DATA.find('products').gridfields($.query.fields, 'id,name,price').callback($); ``` `gridfilter(name, query, type, [column])` does the same for one field. The value of the query string decides the condition: | Value | Condition | | --- | --- | | `phone` | `search` for text, `=` for other types | | `=phone` | Exact match | | `a,b,c` | Text: any of the words (OR of `search`); other types: `in` | | `=a,b` | Text: `in` with the exact values | | `10 - 20` | `between` | | `>10`, `<10` | Greater or less than (numbers and dates) | | `today`, `yesterday`, `2024-05-01` | The whole day (dates) | | `2024`, `5` | The year (a number above 1000) or the month (dates) | ## Inside actions `callback($)` passes the result straight to the action. `promise($)` gives a promise; with `$` an error goes to `$.invalid()`. ```js NEWACTION('Users/read', { name: 'Read user', params: '*id:UID', action: async function($) { var user = await DATA.read('users').id($.params.id).error('@(User not found)').promise($); $.callback(user); } }); ``` `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/). ## Several queries with DB() `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. ```js var db = DB(); db.read('users').id('u1').set('user').error('@(User not found)'); db.find('orders').where('userid', 'u1').set('orders'); db.callback(function(err, response) { // response.user, response.orders }); ``` The 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. --- title: PostgreSQL project: Total.js V5 version: 0.0.20 section: guides language: en license: MIT url: https://totaljs.es/docs/total-js-v5/0-0-20/guides/postgresql/ updated: 2026-11-19T20:13:51.296Z --- # PostgreSQL > Connect to PostgreSQL with DATA.init() and run the QueryBuilder, raw SQL and transactions on it. Total.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. ```js DATA.init('default', CONF.database + '?pooling=10'); DATA.find('tbl_product').where('price', '>', 100).sort('name').take(20).callback(console.log); // SELECT * FROM tbl_product WHERE "price">100 ORDER BY "name" ASC LIMIT 20 ``` The full list of options and functions is in the reference of [PostgreSQL](../../reference/postgresql/). ## Connecting Keep the connection string in the `config` file: ``` database : postgresql://user:password@localhost:5432/eshop ``` Register the connection when the application starts, for example in `definitions/db.js`: ```js DATA.init('default', CONF.database + '?pooling=10'); ``` The 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: ```js DATA.init('logs', CONF.database_logs); DATA.insert('logs/tbl_request', { url: '/', dtcreated: NOW }).callback(console.log); ``` Calling `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`. ## The connection string The 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()`. Options go in the query string, joined with `&`: | Option | What it does | | --- | --- | | `pooling=10` | Keeps a pool of up to 10 connections. Without it every query opens a new connection and closes it at the end. | | `schema=eshop` | The schema of the tables: `DATA.find('tbl_product')` reads `eshop.tbl_product`. | | `sslmode=require` | Encrypts the connection (see below). `ssl=true` is the same. | | `connect_timeout=5` | Seconds to wait for the connection. Then the query fails with `Connection timeout`. | | `application_name=eshop` | The name of the connections in `pg_stat_activity`. | | `host`, `port`, `user`, `password`, `dbname` | Replace the parts of the URL. A `host` that starts with `/` is the directory of a Unix socket. | ```js DATA.init('default', CONF.database + '?schema=eshop&pooling=10&sslmode=require&connect_timeout=5'); ``` The values of `sslmode`: | Value | Connection | | --- | --- | | `disable` (default) | Not encrypted. | | `prefer`, `allow` | Encrypted when the server supports SSL, otherwise not encrypted. | | `require`, `no-verify` | Encrypted, the certificate is not checked. A server without SSL gives the error `The server does not support SSL connections`. | | `verify-ca`, `verify-full` | Encrypted, the certificate of the server must be valid. | The client signs in with a password in plain text, MD5 or SCRAM-SHA-256, as the server asks. In 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. ## Schemas `schema` in the connection string sets the schema for every table of the connection. `schema(name)` on the QueryBuilder changes it for one query: ```js DATA.find('tbl_product').schema('archive').callback(console.log); // SELECT * FROM archive.tbl_product ``` Raw queries (`DATA.query()`) do not use the schema; write it in the SQL. ## The SQL of the QueryBuilder Column 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: ```js DATA.find('tbl_product') .where('isremoved', false) .in('id', ['p1', 'p2']) .search('name', 'pho') .array('tags', ['sale']) .fields('id, name, UPPER(name) AS code') .callback(console.log); // SELECT "id","name",UPPER(name) AS code FROM tbl_product // WHERE "isremoved"=false AND "id" IN ('p1','p2') AND "name"::text ILIKE '%pho%' AND "tags" && ARRAY['sale'] ``` The values of conditions are escaped and written into the SQL. The payload of `insert()` and `update()` goes to the server as parameters (`$1`, `$2`…). | Method | SQL | | --- | --- | | `where('age', '>', 20)` | `"age">20` | | `where('dtremoved', null)` | `"dtremoved" IS NULL` (`IS NOT NULL` with the comparer `<>`) | | `in('id', ['a', 'b'])`, `notin()` | `"id" IN ('a','b')`, `"id" NOT IN (…)` | | `between('age', 20, 30)` | `("age" BETWEEN 20 AND 30)` | | `search('name', 'pet')` | `"name"::text ILIKE '%pet%'` | | `search('name', 'pet', 'beg')` | `"name"::text ILIKE 'pet%'` (the text is at the beginning) | | `search('name', 'pet', 'end')` | `"name"::text ILIKE '%pet'` (the text is at the end) | | `array('tags', ['a'])` | `"tags" && ARRAY['a']`; another comparer, for example `array('tags', '@>', ['a'])`, replaces `&&` | | `year('dtcreated', 2024)` | `EXTRACT(year from "dtcreated")=2024`; `month()`, `day()`, `hour()` and `minute()` work in the same way | | `contains('tags')` | `LENGTH("tags"::text)>0` | | `empty('tags')` | `("tags" IS NULL OR LENGTH("tags"::text)=0)` | | `query('age % 2 = 0')` | `(age % 2 = 0)` | | `or(fn)` | `(… OR …)` | | `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 | | `sort('name', true)` | `ORDER BY "name" DESC` | | `take(20)`, `skip(40)` | `LIMIT 20 OFFSET 40` | `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"`. ## Results | Operation | Result | | --- | --- | | `find()` | An array of rows. | | `read()` | One row or `null`. | | `list()` | `{ items, count, page, limit, pages }`. The adapter runs two queries: the page and `SELECT COUNT(1)`. | | `check()` | `true` or `false`. | | `count()` | A number. | | `scalar(table, 'sum', 'price')` | A number; also `avg`, `min`, `max` and `count`. | | `scalar(table, 'group', 'kind', 'price')` | Rows `{ kind, value }`: the sum of `price` for each `kind` (without the fourth argument the number of rows). | | `insert()` | The number of inserted rows. With `primarykey('id')` the value of that column, with `returning('id,dtcreated')` the inserted row. | | `update()` | The number of changed rows. With `returning()` an array of the changed rows, with `returning()` and `first()` one row. | | `remove()` | The number of removed rows. With `returning()` an array of the removed rows. | | `query()` | An array of rows. | | `truncate()` | Runs `TRUNCATE TABLE … RESTART IDENTITY`. | | `drop()` | Runs `DROP TABLE …`. | ```js DATA.insert('tbl_product', { id: 'p3', name: 'Watch', price: 80 }).returning('id,dtcreated').callback(console.log); // null { id: 'p3', dtcreated: 2026-11-16T16:22:26.950Z } DATA.update('tbl_product', { '*price': 0.9 }).where('price', '>', 100).returning('id,price').callback(console.log); // null [ { id: 'p2', price: 270 }, { id: 'p1', price: 108 } ] ``` ## Operators in the payload The first character of a key in the payload of `update()` can change the value in the database instead of replacing it: | Key | SQL | | --- | --- | | `'+stock': 5` | `"stock"=COALESCE("stock",0)+$1`; also `-`, `*` and `/` | | `'>price': 10` | `"price"=GREATEST("price",$1)` | | `'<price': 10` | `"price"=LEAST("price",$1)` | | `'!isread': 1` | `"isread"=NOT "isread"` | | `'=dtupdated': 'NOW()'` | `"dtupdated"=NOW()`, the value is raw SQL | | `'#dtupdated': 'NOW()'` | The same as `=`, but `insert()` leaves the key out | ```js DATA.update('tbl_product', { '+stock': 5, '-reserved': 5, '=dtupdated': 'NOW()' }).id('p1').callback(console.log); // UPDATE tbl_product SET "stock"=COALESCE("stock",0)+$1,"reserved"=COALESCE("reserved",0)-$2,"dtupdated"=NOW() WHERE "id"='p1' ``` In `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: ```js var id = NOW.format('yyyy-MM-dd'); DATA.update('tbl_visitor', { '+count': 1, '=dtupdated': 'NOW()' }, true).id(id).insert(doc => doc.id = id).callback(console.log); // the first call: INSERT INTO tbl_visitor ("count","dtupdated","id") VALUES($1,NOW(),$2) // the next calls: UPDATE tbl_visitor SET "count"=COALESCE("count",0)+$1,"dtupdated"=NOW() WHERE "id"='2026-11-16' ``` ## Properties of a JSON column `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: ```js NEWACTION('Products/list', { name: 'List of products', action: function($) { DATA.list('tbl_product') .autoquery($.query, 'id,name,price:number', 'name_asc', 100) .autoqueryjson($, 'data', 'color,weight:number,waterproof:boolean,released:date') .callback($); } }); ``` With `?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: ```js { items: [{ id: 'p3', name: "Kid's watch", color: 'red', weight: 40 }], count: 1, page: 1, limit: 100, pages: 1 } ``` A value of a wrong type never makes the query fail: | Type | Result | | --- | --- | | `string` (default) | The text. | | `number` | A number; `0` when the value is not a number. | | `boolean` | `true` for `true`, `1`, `on` and `yes`, otherwise `false`. | | `date` | A `Date`; `null` when the value is not a valid date (`2024-02-30`). | | `[string]` | An array of strings; `[]` when the value is not an array. | A missing property is `null`. The filters, the sort and the types of the values are the same as in `autoquery()`. ## Raw queries `DATA.query()` sends the SQL as it is. Parameters are `$1`, `$2`… and their values go in an array: ```js DATA.query('SELECT id, name FROM eshop.tbl_product WHERE price>$1 ORDER BY id', [100]).callback(console.log); ``` Conditions added with the QueryBuilder replace the text `{where}`, or are added at the end of the SQL when it has no `{where}`: ```js DATA.query('SELECT id, name FROM eshop.tbl_product {where} ORDER BY id').where('isremoved', false).search('name', 'a').callback(console.log); // SELECT id, name FROM eshop.tbl_product WHERE "isremoved"=false AND "name"::text ILIKE '%a%' ORDER BY id ``` ## Transactions Each 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`): ```js DATA.query(`BEGIN; UPDATE eshop.tbl_product SET stock=stock-1 WHERE id='p1'; INSERT INTO eshop.tbl_order (id, productid, count) VALUES('o1', 'p1', 1); COMMIT`).callback(console.log); ``` When the transaction needs parameters or JavaScript between the statements, use the client directly (see below). ## Errors and debugging An 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. ```js DATA.insert('tbl_order', { id: 'o1', productid: 'p2', count: 1 }).callback(function(err, response) { if (err) console.log(err.code, err.constraint, err.detail); // 23505 tbl_order_pkey Key (id)=(o1) already exists. }); ``` Every 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: ```js DATA.init('default', CONF.database + '?pooling=10', function(message) { console.log('SQL error:', message); // SQL error: Error: column "unknown" does not exist - SELECT * FROM tbl_product WHERE "unknown"=1 }); ``` `debug()` on a query (or on a `DB()` chain) prints the SQL and the parameters to the console: ``` -- PostgreSQL --> SELECT "id","name" FROM eshop.tbl_product ORDER BY "price" DESC LIMIT 2 undefined ``` ## Types of values | PostgreSQL | JavaScript | | --- | --- | | `boolean` | `Boolean` | | `smallint`, `integer`, `real`, `double precision`, `numeric` | `Number` | | `bigint` | `String` (it does not always fit into a JavaScript number) | | `json`, `jsonb` | The parsed value; texts in the ISO date format become `Date` objects | | `date`, `timestamp`, `timestamptz` | `Date` | | `bytea` | `Buffer` | | arrays | `Array` of the same types | | other types | `String` | `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: ```js const PG = require('total5/client-postgresql'); PG.types[20] = value => +value; // bigint as a number ``` In 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. ## The client without the QueryBuilder The 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: ```js const PG = require('total5/client-postgresql'); const pool = PG.pool(CONF.database, 5); pool.connect(async function(err, client, release) { if (err) { console.log(err); return; } try { await client.query('BEGIN'); await client.query('UPDATE eshop.tbl_product SET stock=stock-$1 WHERE id=$2', [2, 'p1']); await client.query('INSERT INTO eshop.tbl_order (id, productid, count) VALUES($1, $2, $3)', ['o2', 'p1', 2]); await client.query('COMMIT'); } catch (e) { await client.query('ROLLBACK'); } finally { release(); } }); ``` `client.query()` and `pool.query()` return `{ command, rowCount, rows, fields }`, through a callback or a promise. --- title: Localization project: Total.js V5 version: 0.0.20 section: guides language: en license: MIT url: https://totaljs.es/docs/total-js-v5/0-0-20/guides/localization/ updated: 2026-11-16T15:32:47.498Z --- # Localization > Translate views, files and messages with resource files, choose the language of each request and create dictionaries with total5 translate. Total.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. ```html <!-- /views/index.html --> <h1>@(Welcome)</h1> <button>@(Add to cart)</button> ``` ``` # /resources/sk.resource T1bx8wg2 : Vitajte T1oapati : Pridať do košíka ``` The 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. ## Resource files A 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. Each line is a key, a separator and a value: ``` # a comment // also a comment T1bx8wg2 : Vitajte name : Meno title = Obchod ``` - 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. - The key and the value are trimmed, so you can align the values with spaces. A value can contain more `:` characters. - Empty lines and lines that start with `#` or `//` are ignored. Each 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. ### The default dictionary `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. ## Creating the dictionary Run the `translate` command of the `total5` tool in the root of your project: ```bash total5 translate total5 translate resources/sk.resource ``` It 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: ``` T1bx8wg2 : Welcome T1oapati : Add to cart ``` Copy the file into `/resources/` under the name of a language and translate the values. ## Choosing the language The 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: ```js // /definitions/localize.js LOCALIZE(function($) { var language = $.query.language || ($.headers['accept-language'] || '').substring(0, 2).toLowerCase(); return language === 'sk' || language === 'de' ? language : 'en'; }); ``` The 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: ```js LOCALIZE(function($) { return $.user ? $.user.language : 'en'; }); ``` The 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: ```js function index($) { $.language = 'sk'; $.view('index'); } ``` Inside an action, `$.language` returns the language of the request that called the action. It is read-only there. ## Views and static HTML files A 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. ```js var html = F.view('mail/order', { id: 'A100' }, function(view) { view.language = 'de'; }); ``` Static `.html` files from `/public/` are translated the same way and cached per language, except files whose name contains `.min`, `-min` or `@min`. ## Translating in code `TRANSLATE(language, text)` replaces every `@(...)` in a string and returns the result. Use it for text you build in code, JSON responses or files. ```js var title = TRANSLATE($.language, '@(Order) #' + order.number); ``` `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. ```js // /resources/de.resource contains: currency : EUR var currency = F.resource('de', 'currency') || 'USD'; ``` ## Error messages Errors are translated into the language of the request when they are sent. A message in `@(...)` is translated like any other text: ```js NEWACTION('Orders/create', { name: 'Create an order', input: '*name:String', action: function($, model) { if (!model.name.trim()) { $.invalid('@(The name is required)'); return; } $.success(); } }); ``` A 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. ## E-mails and templates `MAIL()` takes the language after the model. The subject and the view are translated into that language: ```js MAIL(user.email, '@(Your order)', 'mail/order', order, user.language, function(err) { err && console.error(err); }); ``` `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. ## Names of months and days `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: ``` # /resources/sk.resource January : január Monday : pondelok ``` ```js new Date(2024, 0, 1).format('dddd d. MMMM', 'sk'); // pondelok 1. január ``` ## Loading resources from code `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. ```js LOADRESOURCE('sk', 'T1bx8wg2 : Vitajte'); LOADRESOURCE('https://example.com/translations.json'); ``` --- title: HTTP requests project: Total.js V5 version: 0.0.20 section: guides language: en license: MIT url: https://totaljs.es/docs/total-js-v5/0-0-20/guides/http-requests/ updated: 2026-11-19T16:16:52.152Z --- # HTTP requests > Call other HTTP services with RESTBuilder, REQUEST(), AJAX() and DOWNLOAD(). Total.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()`. ## RESTBuilder `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: ```js RESTBuilder.GET('https://api.example.com/products/', { page: 1 }).callback(function(err, response, output) { // response: the parsed JSON body // output.status, output.headers console.log(err, response); }); RESTBuilder.POST('https://api.example.com/orders/', { productid: 'p100', count: 2 }).callback(console.log); ``` `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: ```js RESTBuilder.make(function(builder) { builder.url('https://api.example.com/users/'); builder.auth('Bearer ' + CONF.apitoken); builder.header('X-Client', 'shop'); builder.timeout(5000); builder.json({ name: 'Peter', email: 'peter@example.com' }); builder.callback(function(err, response) { console.log(err, response); }); }); ``` The 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. ### The response The 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)`. `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. `error(value)` replaces any error with your own value, and `logerror()` prints errors to the console through the framework error handler: ```js RESTBuilder.GET('https://api.example.com/stock/') .logerror() .error('The stock service is not available') .callback(function(err, response) { // err === 'The stock service is not available' on any error }); ``` ### Promises `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()`: ```js NEWACTION('Orders/create', { name: 'Create an order', input: '*productid:String, *count:Number', action: async function($, model) { var order = await RESTBuilder.POST(CONF.shopapi + '/orders/', model).promise($); $.callback(order); } }); ``` ### Bodies, files and headers `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`: ```js RESTBuilder.POST('https://files.example.com/upload/') .file('file', 'invoice.pdf', PATH.databases('invoice.pdf')) .callback(console.log); ``` `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. ### Connection options `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. ### Streams and progress `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`: ```js RESTBuilder.GET('https://cdn.example.com/backup.zip').stream(function(err, response) { if (err) return; response.stream.pipe(Total.Fs.createWriteStream(PATH.tmp('backup.zip'))); }); ``` ### Total.js APIs `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: ```js RESTBuilder.API('https://app.example.com/api/', 'products_list', { category: 'shoes' }).callback(console.log); ``` The 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: ```js RESTBuilder.API('https://app.example.com/api/', 'products_list', { category: 'shoes', color: null }).get({ page: 2 }).compress().callback(console.log); // body: { data: { category: 'shoes' }, query: { page: 2 }, schema: 'products_list' } ``` ## REQUEST() `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. ```js REQUEST({ url: 'https://api.example.com/status/', method: 'POST', type: 'json', body: JSON.stringify({ ping: 1 }), headers: { 'X-Token': CONF.apitoken }, timeout: 5000, keepalive: true }, function(err, response) { // response.status, response.headers, response.body (a string) console.log(err, response.status, response.body); }); ``` `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. All 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`. ## AJAX() `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`. ```js AJAX('POST https://api.example.com/login/', { email: 'peter@example.com' }, function(err, response) { console.log(err, response); }); var products = await AJAX('GET https://api.example.com/products/'); ``` ## DOWNLOAD() `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: ```js DOWNLOAD('https://cdn.example.com/logo.png', PATH.public('img/logo.png'), function(err, response) { if (!err && response.status === 200) console.log('Saved', response.size, 'bytes to', response.filename); }); ``` --- title: OpenClient project: Total.js V5 version: 0.0.20 section: guides language: en license: MIT url: https://totaljs.es/docs/total-js-v5/0-0-20/guides/openclient/ updated: 2026-11-16T15:58:11.814Z --- # OpenClient > Open a WebSocket connection to another service with OPENCLIENT() and send messages that wait for an answer. `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. ```js var client = OPENCLIENT('https://service.example.com/$client/'); client.online(function(meta) { console.log(meta ? 'online' : 'offline'); }); client.message(function(msg) { console.log('Message', msg); }); var result = await client.rpc({ type: 'users' }, 5000); ``` `rpc()` adds a `callbackid` to the message; the service answers with `{ callbackid, error, response }`. For WebSocket routes in your own application read [WebSockets](../websockets/). --- title: Sending email project: Total.js V5 version: 0.0.20 section: guides language: en license: MIT url: https://totaljs.es/docs/total-js-v5/0-0-20/guides/mail/ updated: 2026-11-19T16:16:57.153Z --- # Sending email > Send e-mail with MAIL(), HTMLMAIL() and LOGMAIL(), configure SMTP, add attachments and build messages with the Mail module. Total.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. ```js MAIL('user@example.com', 'Welcome', 'mail/welcome', { name: 'Peter' }); HTMLMAIL('user@example.com', 'Your order', '<p>Thank you for your order.</p>'); LOGMAIL('admin@example.com', 'Import finished', { count: 120 }); ``` The full list of functions, methods and keys is in the reference of [Sending email](../../reference/mail/). ## Configuration The 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`. ``` smtp (json) : {"server":"smtp.example.com","port":465,"secure":true ,"user":"info@example.com","password":"secret"} mail_from : info@example.com mail_from_name : My application ``` | Option | Meaning | | --- | --- | | `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 | | `port` | The port. With `secure: true` it defaults to `465`; otherwise set it (usually `25` or `587`) | | `secure` | `true` opens a TLS connection from the start (implicit TLS) | | `user`, `password` | The login. The client uses `AUTH LOGIN`, or `AUTH PLAIN` when the server also offers `XOAUTH` and no `token` is set | | `token` | An OAuth2 access token, used with `user` when the server offers `XOAUTH2` | | `tls` | Extra Node.js TLS options used for the `STARTTLS` upgrade | | `timeout` | The connection timeout in milliseconds (default `60000`) | | `from`, `name` | The sender address and name used when `mail_from` and `mail_from_name` are not set | On 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`. Instead of one object you can also set the server and the options separately: ``` mail_smtp : smtp.example.com mail_smtp_options : {"port":587,"user":"info@example.com","password":"secret"} ``` The 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. ## MAIL() with a view `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. ```js MAIL('user@example.com', 'Welcome', 'mail/welcome', { name: 'Peter' }, function(err) { if (err) console.log('Not sent:', err); }); ``` ```html <!-- views/mail/welcome.html --> @{layout('')} <h1>Hello @{model.name}</h1> <p>Your account is ready.</p> ``` With `language`, the view is rendered in that language and a subject that contains `@(...)` is translated as well. See [Localization](../localization/). ```js MAIL(user.email, '@(Welcome)', 'mail/welcome', user, user.language); ``` The `email` argument is one address, a comma-separated string of addresses, or an array. Each address becomes a `To:` recipient. ## HTMLMAIL() and LOGMAIL() `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. ```js HTMLMAIL('user@example.com', 'Password reset', '<p>Your code is <b>' + code + '</b>.</p>'); ``` `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. ```js LOGMAIL('admin@example.com', 'Nightly import', { imported: 120, failed: 2 }); LOGMAIL('admin@example.com', 'The backup has finished.'); ``` ## Changing the message before it is sent All 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: ```js var msg = HTMLMAIL('user@example.com', 'Invoice', '<p>Your invoice is attached.</p>'); msg.cc('accounting@example.com'); msg.attachment(PATH.databases('invoices/2025-001.pdf'), 'invoice.pdf'); msg.unsubscribe('https://example.com/unsubscribe/?id=123'); ``` `message.manually()` stops the automatic sending. You send the message yourself later with `message.send2()`: ```js var msg = MAIL('user@example.com', 'Report', 'mail/report', data); msg.manually(); // ... later msg.send2(function(err) { console.log(err ? 'Failed' : 'Sent'); }); ``` ## Attachments `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>`: ```js var msg = HTMLMAIL('user@example.com', 'Newsletter', '<img src="cid:logo" /><p>News of the month</p>'); msg.attachment(PATH.public('img/logo.png'), 'logo.png', 'logo'); ``` The 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: ```js var id = UID(); await FILESTORAGE('documents').save(id, 'contract.pdf', Buffer.from('%PDF-1.4 ...')); var msg = HTMLMAIL('user@example.com', 'Your documents', '<p>The files are attached.</p>'); msg.attachment(Buffer.from('id;name\n1;Peter\n'), 'users.csv'); msg.attachmentfs('documents', id); ``` ## Building a message yourself `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)`). ```js var msg = Mail.create('Hello', '<p>Hello from Total.js</p>'); msg.from('info@example.com', 'My application'); msg.to('user@example.com'); msg.reply('support@example.com'); msg.callback(function(err) { err && console.log(err); }); msg.send2(); ``` The body is HTML by default. Set `msg.type = 'plain'` for a plain-text body. `msg.headers` is an object of extra headers. `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: ```js HTMLMAIL('boss@example.com', 'Server is down', '<p>The server does not answer.</p>').high().confidential(); ``` `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: ```js Mail.try(CONF.smtp).then(function() { console.log('SMTP works'); }).catch(function(err) { console.log('SMTP error:', err); }); ``` ## Errors and events The 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: - the server refuses the message (for example an unknown recipient): the reply line of the server, - `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`, - the server is not a valid host name: `Invalid SMTP server hostname.`, - the connection fails or times out. A refused login also gives the reply line of the server. Reply lines are in upper case. An error that reaches a callback is not written to the error log; without a callback, it is logged with `F.error()`. `Mail` is an event emitter, and the framework emits a global event for every message: ```js ON('$mail', function(message) { console.log('Sending', message.subject, 'to', message.email_to); }); Mail.on('error', function(err) { console.log('SMTP error', err); }); ``` `Mail.debug = true` prints the whole SMTP conversation to the console. ## Sending through the Total.js API With `$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: ``` $tapimail : true secret_totalapi : your-totalapi-token ``` `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). ## Customizing `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: ```js var onmail = DEF.onMail; DEF.onMail = function(email, subject, body, callback, reply) { var msg = onmail(email, subject, body, callback, reply); msg.headers = { 'X-Application': CONF.name }; return msg; }; ``` New methods for all messages can be added with `F.extend('mail', name, fn)`; see [Prototypes](../prototypes/). --- title: Scheduling and events project: Total.js V5 version: 0.0.20 section: guides language: en license: MIT url: https://totaljs.es/docs/total-js-v5/0-0-20/guides/scheduling-and-events/ updated: 2026-11-16T16:36:26.082Z --- # Scheduling and events > Crons, global events, the events of the framework, debounced timers, pausing the server and the service timer. A 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()`. ```js // /modules/tasks.js exports.install = function() { ON('ready', function() { console.log('The application is loaded'); }); CRON('0 3 * * *', function(date) { // every day at 03:00 NOSQL('logs').remove().where('date', '<', date.add('-30 days')); }); }; ``` ## Crons `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: | Field | Values | | --- | --- | | minute | `0`–`59` | | hour | `0`–`23` | | day of the month | `1`–`31` | | month | `1`–`12` | | day of the week | `0`–`6` (`0` is Sunday) or a name: `su`, `mo`, `tu`, `we`, `th`, `fr`, `sa` | Each field accepts: - `*`: any value, - a number: `30`, - a list: `0,15,30,45`, - a range: `8-17` (both ends included), - 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`. Names of days can be written in full (`monday`): only the first two letters are read. ```js CRON('30 8 * * mo-fr', function(date) { // at 08:30 from Monday to Friday }); CRON('0,30 * * * *', function() { // every half hour }); CRON('0 0 1 * *', function() { // at midnight on the first day of every month }); CRON('5/20 8-17 * * mo-fr', function() { // at minutes 5, 25 and 45 from 08:00 to 17:59 on working days }); ``` The 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`). `CRON()` returns an object; call its `remove()` method to stop the cron. All registered crons are in the array `F.crons`. ```js var cron = CRON('* * * * *', function() { console.log('Every minute'); }); // later cron.remove(); ``` ## Events `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`. ```js ON('order.created', function(order) { MAIL(order.email, 'Thank you', 'mail/order', order); }); // anywhere EMIT('order.created', { id: 123, email: 'buyer@example.com' }); ``` One listener can catch several events: join their names with `+`. ```js ON('ready + service', function() { // once at the start, then once a minute }); ``` A 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). `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. ## Built-in events | Event | Arguments | When | | --- | --- | --- | | `ready` | | The application is loaded (all modules, actions, controllers…) | | `load` | | Right after `ready` | | `service` | `counter` | Once a minute; `counter` is the number of minutes since the start | | `exit` | `signal` | The process is stopping | | `error` | `obj` | The framework logged an error | | `request` | `ctrl` | An HTTP request arrived, before routing | | `controller` | `ctrl` | A route was found, before its action runs | | `componentator` | `meta` | `COMPONENTATOR()` is about to download components | | `flowstream_error` | `meta` | A component of a FlowStream failed | | `flowstream` | `instance` | A FlowStream instance was created | | `$mail` | `message` | An e-mail is being sent | | `$stats` | `stats` | The usage statistics of the process were updated | | `$message` | `msg`, `handle` | The process received a message from its parent | | `$update` | | Another process of the cluster sent `total:update` | Other 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. The `request` and `controller` events can stop the request: call `ctrl.cancel()` and answer it yourself. ```js ON('request', function(ctrl) { if (ctrl.url === '/health/') { ctrl.cancel(); ctrl.text('OK'); } }); ``` ## Debounced timers `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. ```js function save(doc) { // many changes in a short time make one write setTimeout2('save' + doc.id, function() { NOSQL('docs').modify(doc).where('id', doc.id); }, 2000); } ``` The fourth argument `limit` stops endless postponing: after `limit` postponements, the next call runs its callback at once and the counting starts again. ```js setTimeout2('search', function() { search(text); }, 300, 10); ``` ## Waiting for a stream `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. ```js var writer = F.Fs.createWriteStream(PATH.temp('export.csv')); writer.write('id;name\n'); writer.end(); CLEANUP(writer, function() { console.log('Written'); }); ``` ## Pausing the server `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. ```js PAUSESERVER('Database migration', true); migrate(function() { PAUSESERVER('Database migration', false); }); ``` Without `enable` the call toggles the name and returns `true` when it is now paused. The paused names are in the array `F.paused`. ## The service timer Every 5 seconds the timer updates `NOW` and cancels HTTP requests that ran out of time. Once a minute it: - removes expired items of the cache and the bans that expired, - every 5 minutes clears `TEMP`, - every `$clearcache` minutes (default `10`) clears the internal caches of actions, views, paths, images and templates, - every `$tmsclearblocked` minutes (default `60`) clears the list of blocked TMS clients, - updates the usage statistics and emits `$stats`, - runs the crons and emits `service`. `$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: ```js ON('service', function(counter) { if (counter % 5 === 0) { // every 5 minutes refresh(); } }); ``` --- title: File storage project: Total.js V5 version: 0.0.20 section: guides language: en license: MIT url: https://totaljs.es/docs/total-js-v5/0-0-20/guides/file-storage/ updated: 2026-11-19T16:16:52.152Z --- # File storage > Store, read, serve and manage binary files with FILESTORAGE(), including uploaded files. A **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. ```js var fs = FILESTORAGE('photos'); fs.save('avatar-100', 'me.jpg', PATH.root('me.jpg'), function(err, meta) { // meta.name === 'me.jpg', meta.type === 'image/jpeg', meta.width, meta.height }); ``` `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/). ## Where files are stored A 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. Each `.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)`: ```js FILESTORAGE('backups').storage('/mnt/disk2/backups/'); ``` ## Saving files `fs.save(id, name, source, [custom], [callback], [expire], [headers])` (alias `insert()`) accepts four kinds of source: - the path of a file on the disk, - a `Buffer`, - a readable stream, - an `https://` URL, which is downloaded (optional `headers` are sent with the request; a response with status 400 or higher ends with an error). The 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`. ```js var fs = FILESTORAGE('documents'); // From a Buffer, with custom data fs.save(UID(), 'note.txt', Buffer.from('Hello', 'utf8'), { userid: 'u1' }, function(err, meta) { console.log(meta.id, meta.size, meta.custom.userid); }); // From a URL, as a Promise, expires in 7 days var meta = await fs.save('logo', 'logo.png', 'https://www.example.com/logo.png', null, null, '7 days'); ``` The callback receives the metadata of the saved file: | Property | Content | | --- | --- | | `id` | The id of the file | | `name` | The file name (without a path, at most 250 characters) | | `ext` | The extension, lower case without the dot | | `type` | The content type, for example `image/png` | | `size` | The size of the content in bytes | | `width`, `height` | The dimensions of JPEG, PNG, GIF and SVG images | | `custom` | Your custom data, or `null` | | `date` | When the file was saved | | `expire` | When the file expires, if you set it | Saving again with an existing id replaces the file. `fs.savejson(id, value, [callback])` is a shortcut that stores a value as `{id}.json`. ## Uploaded files Files 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. ```js exports.install = function() { ROUTE('POST /api/upload/ @upload <10MB', upload); }; function upload($) { var file = $.files[0]; if (!file) { $.invalid('@(Select a file)'); return; } file.fs('files', UID(), function(err, meta) { if (err) $.invalid(err); else $.success(meta.id); }); } ``` Several files are saved one after another with `wait()`: ```js function upload($) { var output = []; $.files.wait(function(file, next) { file.fs('files', UID(), function(err, meta) { meta && output.push({ id: meta.id, name: meta.name, size: meta.size }); next(); }); }, () => $.json(output)); } ``` The properties of `HttpFile` and its other methods are described in [Controller](../controller/). ## Reading files | Method | The callback receives | | --- | --- | | `fs.read(id, callback)` | `(err, meta)` with a readable stream in `meta.stream` | | `fs.readmeta(id, callback)` | `(err, meta)`: only the header, the content is not read | | `fs.readbuffer(id, callback)` | `(err, buffer, meta)`: the whole content | | `fs.readbase64(id, callback)` | `(err, base64, meta)`: the content as a base64 string | | `fs.readjson(id, callback)` | `(err, value, meta)`: the parsed JSON | | `fs.image(id, callback)` | `(err, image, meta)`: an image object of [Images](../images/) | A 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. ```js var fs = FILESTORAGE('documents'); fs.read('invoice-2025-001', function(err, meta) { if (err) return; var writer = F.Fs.createWriteStream(PATH.tmp(meta.name)); meta.stream.pipe(writer); }); var buffer = await fs.readbuffer('invoice-2025-001'); ``` Always 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. ## Serving files over HTTP `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. ```js exports.install = function() { ROUTE('GET /files/{id}/', file); ROUTE('GET /download/{id}/', download); }; function file($) { FILESTORAGE('files').http($, { id: $.params.id }); } function download($) { FILESTORAGE('files').http($, { id: $.params.id, download: true, check: meta => meta.custom && meta.custom.public }); } ``` The options are: - `id`: the id of the file, - `download`: `true` sends the file as an attachment with its stored name, a string sets another name, a function `(name, type)` returns the name, - `check`: a function `(meta)`; when it returns `false` the answer is `404`, - `image`: a function `(image)` called with `this` as the controller, to transform JPEG, PNG and other images before they are sent, - `cache`: a key; with `image`, the transformed image is saved to the temporary directory under this key and reused for the next requests. ```js function thumbnail($) { var id = $.params.id; FILESTORAGE('photos').http($, { id: id, cache: 'thumb-' + id, image: function(image) { image.resize(200, 200); image.quality(80); } }); } ``` An 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. ## Managing files ```js var fs = FILESTORAGE('documents'); fs.rename('note-1', 'renamed.txt'); // changes the stored name fs.copy('note-1', PATH.tmp()); // writes the content to a directory or a file path fs.clone('note-1', 'note-2'); // a new id with the same content fs.remove('note-2', function(err) {}); // deletes the file and its line in the index ``` `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. `fs.clear()` (alias `drop()`) removes all files of the storage and the index; the callback receives the number of removed files. ## Listing files `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/): ```js FILESTORAGE('documents').browse().where('ext', 'pdf').sort('date', true).take(20).callback(function(err, files) { console.log(files); }); ``` `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()`. ```js FILESTORAGE('documents').stream(function(meta, next) { console.log(meta.id, meta.name, meta.size); next(); }, function() { console.log('done'); }); ``` ## Backup and restore `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. ```js var fs = FILESTORAGE('documents'); await fs.backup(PATH.root('documents.backup')); fs.restore(PATH.root('documents.backup'), function(err) { fs.rebuild(); }); ``` While a storage is cleared, restored or its index is rebuilt, its `save()`, `read()`, `readbuffer()`, `copy()` and `clone()` calls wait until the operation ends. --- title: Plugins and components project: Total.js V5 version: 0.0.20 section: guides language: en license: MIT url: https://totaljs.es/docs/total-js-v5/0-0-20/guides/plugins-and-components/ updated: 2026-11-16T16:36:21.082Z --- # Plugins and components > Plugins in the plugins/ folder, PLUGINS, UI bundles from COMPONENTATOR(), server components with NEWCOMPONENT(), and NPMINSTALL(), REQUIRE() and IMPORT(). A **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. This 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/). ## Structure of a plugin ```text plugins/ shop/ index.js <- required: the plugin definition controllers/ <- routes of the plugin actions/ schemas/ models/ definitions/ extensions/ middleware/ public/ <- static files, served as /_shop/... views/ <- views, rendered as #shop/views/... ``` The 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`. ## index.js `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. ```js // plugins/shop/index.js exports.icon = 'ti ti-shopping-cart'; exports.name = 'Shop'; exports.position = 3; exports.permissions = [{ id: 'shop', name: 'Shop' }, { id: 'shop_orders', name: 'Orders' }]; exports.visible = user => user.sa || user.permissions.includes('shop'); exports.install = function() { ROUTE('+API ? shop_orders --> Shop/orders'); ON('ready', function() { // the whole application is loaded }); }; ``` The framework itself reads only these properties: | Property | What Total.js does with it | | --- | --- | | `exports.install` | Called once, when the plugin is loaded | | `exports.id` | Set to the folder name when you do not define it | | `exports.name` | Written with the id and the permissions to the source map of the application (debug mode) | | `exports.permissions` | An array of strings or objects with `id`; the ids are written to the source map | Any 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. ## Files inside a plugin These 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. | Folder | Content | | --- | --- | | `controllers/` | Routes, see [Routing](../routing/) | | `actions/` | `NEWACTION()` definitions, see [Actions](../actions/) | | `schemas/` | Schemas and actions, see [JSON schemas](../json-schemas/) | | `models/`, `definitions/`, `extensions/` | Shared code, delegates, prototypes | | `middleware/` | `NEWMIDDLEWARE()` definitions, see [Middleware](../middleware/) | All 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. ```js // plugins/shop/controllers/api.js exports.install = function() { ROUTE('+API ? shop_products --> Shop/products'); ROUTE('+GET /admin/shop/', function($) { $.view('#shop/views/index'); }); }; ``` ## Public files, views and templates - **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/)). - **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/)). - **Templates**: `TEMPLATE('#shop/templates/order.html', model)` reads `plugins/shop/templates/order.html`. `.html` is added when the name does not contain it. - **Paths**: `PATH.plugins('shop/data.json')` returns the absolute path of a file in the plugins folder. In debug mode the `plugins/` folder is watched like `controllers/`: a change of a script restarts the application. ## Configuration of a plugin A 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. ```text // plugins/shop/config shop_currency : EUR shop_pagesize : 20 ``` ```js // plugins/shop/actions/products.js NEWACTION('Shop/products', { action: function($) { var take = CONF.shop_pagesize; // ... $.success(); } }); ``` ## FlowStream in a plugin When 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/). ```js // plugins/iot/index.js exports.name = 'IoT'; exports.install = function() { ON('ready', function() { setTimeout(function() { var flow = PLUGINS.iot.flowstream; flow && console.log('IoT FlowStream is running'); }, 1000); }); }; ``` ## PLUGINS `PLUGINS` is an object with all loaded plugins, by id. Each value is the `module.exports` object of the plugin `index.js`. ```js // a menu for an admin panel ROUTE('+GET /admin/plugins/', function($) { var user = $.user; var arr = []; for (var id in PLUGINS) { var plugin = PLUGINS[id]; if (plugin.visible && !plugin.visible(user)) continue; arr.push({ id: id, name: plugin.name, icon: plugin.icon, position: plugin.position }); } arr.quicksort('position'); $.json(arr); }); ``` ## UI components (COMPONENTATOR) `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. ```js // definitions/ui.js COMPONENTATOR('ui', 'exec,locale,aselected,page,viewbox,input,box,validate,loading,notify,message,errorhandler,empty,menu,colorpicker,icons,directory,miniform,preview,datagrid', true); ``` The 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: ```html <script src="@{REPO.ui}"></script> ``` ## Server components (NEWCOMPONENT) A 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. ```html <!-- components/uppercase.html --> <script total> exports.name = 'Uppercase'; exports.config = { prefix: '' }; exports.inputs = [{ id: 'input', name: 'Text' }]; exports.outputs = [{ id: 'output', name: 'Result' }]; exports.make = function(instance, config) { instance.message = function(msg) { msg.send('output', config.prefix + String(msg.data).toUpperCase()); }; }; </script> <readme> Converts the text to upper case. </readme> ``` ```js var com = await NEWCOMPONENT('uppercase'); // reads components/uppercase.html com.debugger = false; // do not print outputs to the console var instance = com.create({ prefix: '> ' }); instance.input('input', 'hello', function(msg) { console.log(msg.output, msg.data); // output > HELLO }); ``` `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`. ## NPM packages and remote modules - `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`). - `REQUIRE(name)` loads a module: Node.js built-in modules directly, other packages with `require()` and, when that fails, from `CONF.$nodemodules`. - `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. ```js // plugins/pdf/index.js exports.install = async function() { await NPMINSTALL('pdfkit@0.15.0'); var PDFDocument = REQUIRE('pdfkit'); // ... }; ``` ```js IMPORT('https://cdn.example.com/helpers.js', function(err, module) { if (!err) module.hello(); }); ``` --- title: FlowStream project: Total.js V5 version: 0.0.20 section: guides language: en license: MIT url: https://totaljs.es/docs/total-js-v5/0-0-20/guides/flowstream/ updated: 2026-11-19T16:16:52.152Z --- # FlowStream > Visual data flows: loading FlowStreams, components, instances, messages and the Total.js Flow editor. FlowStream 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. The engine is available as the global `Flow` (and its alias `FlowStream`). Every loaded flow is kept in `Flow.instances[id]`. ## Loading a FlowStream `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. ```js Flow.load({ id: 'orders', name: 'Orders', components: {}, design: {}, variables: { token: '123' } }, function(err, flowstream) { // flowstream === Flow.instances.orders }); ``` | Key | What it does | | --- | --- | | `id` | Identifier of the FlowStream (a random id when empty) | | `name` | Name shown in the editor (`id` when empty) | | `components` | Object: component id → source code of the component | | `design` | Object: instance id → `{ component, config, connections, x, y }` | | `variables` | Values available as `{name}` in the components | | `worker` | `'worker'` runs the flow in a worker thread, any other truthy value in a child process | | `memory` | With `worker`: the heap limit of the worker in MB (`--max-old-space-size` for a child process, `resourceLimits` for a worker thread) | | `proxypath` | URL path under which the HTTP server of a worker is reachable through the main app | | `cloning` | `false` disables cloning of message data between connections | | `paused` | `true` loads the flow paused | | `readonly` | `true` disables saving | | `import` | Comma-separated paths (from the app root) of modules whose `install(flow)` / `init(flow)` run on load | | `initscript` | JavaScript code executed with the FlowStream as `instance` | | `env` | A value available as `instance.env` in the components | When 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. Loading a schema with an `id` that is already running reloads the running FlowStream with the new schema. Each time a FlowStream starts (also after the automatic restart of a worker), the framework emits the global event `flowstream`: ```js ON('flowstream', function(flowstream) { console.log('FlowStream started:', flowstream.id); }); ``` A 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/). ## Editing with Total.js Flow The editor talks to the FlowStream over a WebSocket. Create a route and pass the connection to `Flow.socket()`: ```js exports.install = function() { ROUTE('+SOCKET /flowstreams/{id}/ <8MB', socket); }; function socket($) { $.autodestroy(); Flow.socket($.params.id, $); } ``` Open `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. The FlowStream does not write files. About 5 seconds after a change it emits `save` with the whole schema, and you store it yourself: ```js Flow.on('save', function(schema) { F.Fs.writeFile(PATH.root('flowstreams/' + schema.id + '.flow'), JSON.stringify(schema, null, '\t'), NOOP); }); ``` For 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. ## Components A 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. ```html <script total> exports.name = 'Uppercase'; exports.icon = 'ti ti-text'; exports.group = 'Common'; exports.config = { field: 'name' }; exports.inputs = [{ id: 'input', name: 'Input' }]; exports.outputs = [{ id: 'output', name: 'Output' }]; exports.make = function(instance, config) { instance.message = function($) { var data = $.data; data[config.field] = (data[config.field] || '').toUpperCase(); $.send('output'); }; instance.configure = function() { config = instance.config; }; }; </script> <readme> Converts a field to upper case. </readme> ``` `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. `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. ## Messages The `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()`. ```js instance.message = function($) { if ($.data.price > 100) $.send('expensive'); else $.send('cheap', { price: $.data.price }); }; ``` The fourth argument of `$.send()` filters the targets: `$.send('output', null, null, function(from, to, output, input) { return to.component !== 'debug'; })`. Without 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: ```js exports.make = function(instance) { instance.cache.count = 0; var onreset = function() { instance.cache.count = 0; instance.status({ count: 0 }); }; instance.main.on('reset', onreset); instance.close = function() { instance.main.off('reset', onreset); }; }; ``` The next example starts messages from a timer and shows the time of the last one as the status: ```js exports.make = function(instance, config) { var timer = setInterval(function() { instance.send('output', { ts: NOW }); instance.status({ last: NOW }); }, 5000); instance.close = function() { clearInterval(timer); }; }; ``` ## Instance data `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). `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. ## Activities A 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. ```js instance.message = function($) { instance.activity('import', 'Importing products', 0); importproducts($.data, function(percentage) { instance.activity('import', 'Importing products', percentage); }, function() { instance.activity('import', 'Importing products', 100); $.send('output'); }); }; ``` ## Variables The 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. ```js var url = instance.replace('https://api.example.com/orders/?token={token}'); ``` `flowstream.variables(obj)` replaces the variables of a running flow; the instances are notified by their `variables` delegate. ## Controlling a FlowStream from code `Flow.instances[id]` is the running FlowStream. It works the same for flows in the main process and in workers. ```js var flowstream = Flow.instances.orders; // Executes the "trigger" delegate of an instance flowstream.trigger('instanceid', { manual: true }); // Sends data to an instance and waits for the end of the message flowstream.send('instanceid', { id: 1 }, function(err, response) { console.log(response.data, response.duration); }); flowstream.pause(true); flowstream.reconfigure('instanceid', { field: 'title' }); flowstream.export(function(err, schema) {}); ``` Instance ids can be replaced by `@component` (instances of a component id) or `#name` (instances of a component name). `Flow.remove(id)` stops a FlowStream and removes it. ## Workers With `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. With `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. `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. ## Notifications `Flow.notify($, id)` passes an HTTP request to the `notify` delegate of an instance. The `id` is `flowid-instanceid`. Register the routes yourself: ```js exports.install = function() { ROUTE('GET /notify/{id}/', notify); ROUTE('POST /notify/{id}/ <1MB', notify); }; function notify($) { Flow.notify($, $.params.id); } ``` ## TMS sources In 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/). ## Testing a component `Flow.test(name, source, [config], init)` loads a single component in a test flow and gives you a `Test` object: ```js Flow.test('uppercase', source, { field: 'name' }, function(test) { test.message = function($, data) { test.assert(data.name === 'PETER', 'uppercase'); }; test.send('input', { name: 'Peter' }); }); ``` ## The flow5 command The `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: ```bash flow5 orders.json 8001 ``` Changes made in the editor are written back to the JSON files. See [Command line](../command-line/). --- title: Message Service (TMS) project: Total.js V5 version: 0.0.20 section: guides language: en license: MIT url: https://totaljs.es/docs/total-js-v5/0-0-20/guides/message-service-and-apis/ updated: 2026-11-16T15:32:52.498Z --- # Message Service (TMS) > Publish events, receive messages and answer calls over TMS. Total.js 5 has two small layers for talking to other services: - **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. - **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. ## Enabling TMS TMS is off by default. Turn it on in the configuration and set a token: ```js // /config $tms : true secret_tms : a-long-random-token ``` The 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. After 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' }`. ## Publishing events `NEWPUBLISH()` declares an event and its schema. `PUBLISH()` sends data to every connected client that subscribed to that event: ```js // definitions/tms.js NEWPUBLISH('orders_created', 'id:UID, email:Email, total:Number'); // anywhere in the app PUBLISH('orders_created', { id: order.id, email: order.email, total: order.total }); ``` `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. ## Receiving messages `NEWSUBSCRIBE()` declares a message that clients may send to your app, with its schema. `SUBSCRIBE()` adds a handler for it: ```js NEWSUBSCRIBE('users_updated', 'id:UID, *name:String, email:Email'); SUBSCRIBE('users_updated', function(msg, client) { // msg.response is the validated data var user = msg.response; console.log('From', client.ip, user.id, user.name); }); ``` A 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. ## Remote calls `NEWCALL()` declares a procedure that clients can call and wait for its answer: ```js NEWCALL('products_detail', 'id:UID', function(data, next, client) { if (data.id === '404') next('Product not found'); else next(null, { id: data.id, name: 'Keyboard', price: 49 }); }); ``` `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. ## Connecting to TMS `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: ```js TMSCLIENT('https://orders.example.com/$tms/', CONF.orders_token, function(err, client, meta) { console.log('Connected to', meta.name); // Events published by the server with PUBLISH() client.subscribe('orders_created', function(order) { console.log('New order', order.id); }); // Messages for the server's NEWSUBSCRIBE() client.publish('users_updated', { id: user.id, name: user.name }); // Procedures declared with NEWCALL() client.call('products_detail', { id: '123' }, function(err, product) { console.log(err, product); }); }); ``` The 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. --- title: APIs project: Total.js V5 version: 0.0.20 section: guides language: en license: MIT url: https://totaljs.es/docs/total-js-v5/0-0-20/guides/apis/ updated: 2026-11-16T15:32:52.498Z --- # APIs > Register named APIs with NEWAPI(), call remote services through them with API(), and use the Total.js API service. ## Registering an API `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: ```js NEWAPI('Weather', function(opt, next) { // opt.schema is the operation, opt.data the payload var req = {}; req.url = 'https://api.weather.example/' + opt.schema + '/?q=' + encodeURIComponent(opt.data.city); req.method = 'GET'; req.type = 'json'; req.callback = function(err, response) { if (err && opt.retries < 3) opt.retry(); else next(err, response && response.body.parseJSON()); }; REQUEST(req); }); ``` A 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`. An 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()`: ```js NEWAPI('Weather', { region: 'eu', units: 'metric' }, function(opt, next) { // opt.config.region, opt.config.units next(null, { region: opt.config.region }); }); API('Weather', 'current', { city: 'Oslo' }).configure({ units: 'imperial' }).callback(console.log); ``` ## Calling an API `API(name, schema, data, [$])` runs the handler on the next tick and returns an object whose methods configure the call: ```js NEWACTION('weather_read', { input: '*city:String', action: function($, model) { API('Weather', 'current', model).error('City not found').callback($); } }); // with a promise var forecast = await API('Weather', 'forecast', { city: 'Bratislava' }).promise(); ``` | Method | What it does | | --- | --- | | `.callback(fn)`, `.pipe(fn)` | Sets `function(err, response)`, or passes the result to `$.callback()` | | `.promise([$])` | Returns a promise; with `$` an error goes to `$.invalid()` | | `.data(fn)` / `.fail(fn)` | Runs `fn(response)` on success or `fn(err)` on error | | `.error(message, [reverse])` | Turns an empty response (or, with `reverse`, any truthy one, an empty array too) into an error | | `.output(type)` | Sets `opt.output`, the format the handler should return | | `.file(filename, path, [name])` | Adds a file to `opt.files` | | `.configure(obj)` | Copies keys into `opt.config` | | `.controller($)` | Sets `opt.controller` | | `.audit($, message, [type])` | Writes an audit log with `$.audit()` after a successful call | | `.debug()` | Prints the error and the response to the console | A name without a handler (and no `*` handler) fails with `API is not initialized`. ## Total.js API `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: ```js // /config totalapi : your-totalapi-token // code TotalAPI('check', {}, function(err, response) { console.log(err, response); }); // "operation" is the name of a Total API operation that returns a file API('TAPI', operation, data).output('#files').callback(console.log); ``` The 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. For the WebSocket server itself see [WebSockets](../../guides/websockets/), and for outgoing HTTP calls see [HTTP requests](../../guides/http-requests/). --- title: Workers, threads and cluster project: Total.js V5 version: 0.0.20 section: guides language: en license: MIT url: https://totaljs.es/docs/total-js-v5/0-0-20/guides/workers-and-threads/ updated: 2026-11-19T16:16:57.153Z --- # Workers, threads and cluster > Worker threads, thread pools, cluster mode, shell commands, Python scripts and Python pipelines. Total.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`. ## The `workers/` folder A 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')`. ```text myapp/ ├── index.js ├── controllers/ └── workers/ └── calc.js ``` ## A worker thread The 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: ```js // workers/calc.js require('total5'); var worker = NEWTHREAD(); worker.message = function(msg) { var sum = msg.a + msg.b; worker.send({ sum: sum, user: worker.data.user }); }; ``` In the main application `NEWTHREAD(name, [data])` starts the thread and returns the Node.js `Worker`. `data` is copied into the thread as `worker.data`: ```js // controllers/default.js exports.install = function() { ROUTE('GET /sum/', sum); }; function sum($) { var thread = NEWTHREAD('calc', { user: 'Peter' }); thread.on('message', function(msg) { $.json(msg); thread.kill(); }); thread.postMessage({ a: 1, b: 2 }); } ``` Messages 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. `F.worker` has these members: | Member | Description | | --- | --- | | `worker.data` | The `data` passed to `NEWTHREAD(name, data)`, or `{}` | | `worker.is` | `true` when the script runs as a worker (the argument `--worker`) | | `worker.isfork` | `true` in a process from `NEWFORK()`, `false` in a thread | | `worker.message` | Assign a function: it receives every message from the parent | | `worker.send(msg)` | Sends a message to the parent (alias `worker.postMessage()`) | | `worker.exit([code])` | Ends the process of the worker with the code (default `0`); aliases `kill()` and `close()` | | `worker.setTimeout(ms)` | Ends the worker with code `1` after `ms` milliseconds; call it again to restart the countdown | `setTimeout()` is a watchdog: call it when a job starts, and the worker ends itself if the job takes too long. ```js worker.message = function(msg) { worker.setTimeout(10000); heavyjob(msg, function(err, response) { worker.send({ error: err ? err + '' : null, response: response }); }); }; ``` On 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()`. ## A forked process `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: ```js // workers/report.js require('total5'); var worker = NEWFORK(); worker.message = function(msg) { worker.send({ id: msg.id, done: true }); }; ``` ```js var fork = NEWFORK('report'); fork.on('message', function(msg) { if (typeof(msg) === 'string') return; // internal messages of the framework, e.g. 'total:init' console.log(msg); fork.terminate(); }); fork.postMessage({ id: 100 }); ``` The 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. ## A pool of threads `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. ```js var pool = NEWTHREADPOOL('calc', 4); pool.exec(function(worker, release) { worker.on('message', function(msg) { console.log(msg.sum); release(); }); worker.postMessage({ a: 5, b: 5 }); }); ``` `pool.exec()` without a function returns a promise that resolves with the worker; call `worker.release()` when the job is done: ```js var worker = await pool.exec(); worker.on('message', function(msg) { console.log(msg.sum); worker.release(); }); worker.postMessage({ a: 1, b: 1 }); ``` Before 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. ## Cluster mode A 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'`: ```js // index.js require('total5'); const options = {}; options.port = 8000; options.release = true; options.cluster = 4; // options.cluster = 'auto'; // options.limit = 10; Total.run(options); ``` The 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. | Option | Description | | --- | --- | | `cluster` | The number of processes, or `'auto'` | | `limit` | With `'auto'`: the maximum number of processes | | `tz` | The time zone of the processes (`process.env.TZ`), default `'utc'` | | `logs` | `'isolated'` prints the cluster header even when the master runs under another process | | `callback` | `function(forks)` called in the master after all processes have started | All 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. With `'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. A 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. Inside a process of the cluster: ```js F.isCluster; // true F.isWorker; // true F.id; // '1', '2', ... the identifier of the process F.clusterid; // the same identifier ``` The framework adds `F.clusterid` to the names of its temporary files, so the processes do not overwrite each other's files in `tmp/`. ## Messages between cluster processes Every 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: ```js // definitions/sync.js ON('$message', function(msg) { if (msg && msg.type === 'clearcache') MAIN.products = null; }); // anywhere in a request function update($) { if (F.isCluster) process.send({ type: 'clearcache', from: F.id }); else MAIN.products = null; $.success(); } ``` Do 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. ## Shell commands `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`). ```js SHELL('git rev-parse HEAD', function(err, stdout) { console.log(stdout.trim()); }); var files = await SHELL('ls -1', PATH.public()); ``` ## Python scripts `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: ```js await F.pipinstall('requests'); var output = await F.python(PATH.root('scripts/report.py')); console.log(output); ``` For a script that keeps running and exchanges messages with the application, use a pipeline. ## Python pipelines `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`. The 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): ```python # pypelines/upper.py import sys, socket, struct, json s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) s.connect(sys.argv[1]) def read(n): data = b'' while len(data) < n: chunk = s.recv(n - len(data)) if not chunk: sys.exit(0) data += chunk return data while True: size = struct.unpack('>I', read(4))[0] msg = json.loads(read(size)) out = json.dumps({ 'text': msg['text'].upper() }).encode() s.sendall(struct.pack('>I', len(out)) + out) ``` ```js var py = PYPELINE('upper'); py.on('data', function(msg) { console.log(msg.text); // HELLO }); py.send({ text: 'hello' }); ``` Messages 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. The 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/). --- title: MCP server project: Total.js V5 version: 0.0.20 section: guides language: en license: MIT url: https://totaljs.es/docs/total-js-v5/0-0-20/guides/mcp-server/ updated: 2026-11-19T16:16:57.153Z --- # MCP server > 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. The **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. ``` # config name : Tasks version : 1.0 $mcp : true ``` ```js // actions/tasks.js NEWACTION('Tasks|create', { summary: 'Creates a task and returns its ID', mcp: true, input: '*name:String // The name of the task, due:Date // When the task must be done', output: 'id:UID', action: function($, model) { model.id = UID(); NOSQL('tasks').insert(model).callback(() => $.callback({ id: model.id })); } }); NEWACTION('Tasks|remove', { summary: 'Removes a task', mcp: true, params: '*id:UID // The ID of the task', action: function($) { NOSQL('tasks').remove().id($.params.id).callback(function(err, count) { if (count) $.success(); else $.invalid(404); }); } }); ``` The AI client connects to `http://localhost:8000/$mcp/` and sees the tools `Tasks_create` and `Tasks_remove`. ## The endpoint With `$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`. The 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. | Method | Answer | | --- | --- | | `initialize` | The protocol version, `capabilities: { tools: {} }` and `serverInfo` with `CONF.name` and `CONF.version` | | `ping` | An empty result | | `tools/list` | The list of the tools | | `tools/call` | Runs a tool (an action) and returns its response | | `server/discover` | The supported version `2026-07-28`, the capabilities and the server info | | a notification (a message without `id`) | Status `202` without a body | Another 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`). ```js // the answer to { "jsonrpc": "2.0", "id": 1, "method": "initialize", "params": { "protocolVersion": "2025-06-18" } } { "jsonrpc": "2.0", "id": 1, "result": { "protocolVersion": "2025-06-18", "capabilities": { "tools": {} }, "serverInfo": { "name": "Tasks", "version": "1.0" } } } ``` `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. ## Actions as tools Every 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. - **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`. - **description**: the `summary` option of the action, or its `name` option. - **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. - **outputSchema**: made from the `output` schema, when the action has one. The 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. ```js // tools/list, the tool Tasks_remove { "name": "Tasks_remove", "description": "Removes a task", "inputSchema": { "type": "object", "properties": { "params": { "type": "object", "description": "URL params passed to this action.", "properties": { "id": { "type": "string", "description": "The ID of the task" } }, "additionalProperties": false, "required": ["id"] } }, "required": ["params"] } } ``` `F.actions[name].toAITool()` returns the same definition for one action, and `Total.mcp.tools` holds the whole list. ## Calling a tool The AI client sends `tools/call` with the name of the tool and its arguments: `input` (the payload; `data` is accepted too), `query` and `params`. ```js { "jsonrpc": "2.0", "id": 3, "method": "tools/call", "params": { "name": "Tasks_create", "arguments": { "input": { "name": "Call Peter", "due": "2026-11-20" } } } } ``` The 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`. The 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`: ```js { "jsonrpc": "2.0", "id": 3, "result": { "resultType": "complete", "content": [{ "type": "text", "text": "{\"id\":\"JafvB11cV61f\"}" }], "structuredContent": { "id": "JafvB11cV61f" } } } ``` Errors 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: ```js { "jsonrpc": "2.0", "id": 6, "result": { "resultType": "complete", "content": [{ "type": "text", "text": "[{\"error\":\"404: Not Found\"}]" }], "isError": true } } ``` An 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. ## Authorization By 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. ```js // definitions/mcp.js Total.mcp.auth = function($) { if ($.token && $.token === CONF.mcptoken) $.success({ id: 'mcp' }); else $.invalid(); }; ``` A 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 `{}`. `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`): ```js // definitions/mcp.js Total.mcp.auth = function($) { if ($.token === CONF.mcp_admin) $.success({ id: 'admin', name: 'Admin', sa: true }); else if ($.token === CONF.mcp_reader) $.success({ id: 'reader', name: 'Reader' }); else $.invalid(); }; Total.mcp.filter = function(tool, $) { return !tool.name.startsWith('Admin_') || $.user.sa; }; ``` ## Code mode Every 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. `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: ``` curl -H 'Authorization: Bearer TOKEN' https://app.example.com/$mcp/client.js > client.js ``` ```js // /** // * Creates a task and returns its ID // * @param {Object} args // * @param {Object} args.input Payload (request body) passed to this action. // * @param {String} args.input.name The name of the task // * @param {String} [args.input.due] When the task must be done (ISO date) // * @returns {Promise<{ id: ?String }>} // */ // api.Tasks_create = args => call("Tasks_create", args); const api = require('./client.js')('TOKEN'); for (const name of ['Call Peter', 'Send the offer']) await api.Tasks_create({ input: { name } }); console.log('2 tasks created'); ``` `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`. Nothing 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. --- title: Utilities project: Total.js V5 version: 0.0.20 section: guides language: en license: MIT url: https://totaljs.es/docs/total-js-v5/0-0-20/guides/utilities/ updated: 2026-11-19T16:16:57.153Z --- # Utilities > The global helpers of Total.js 5: the U/Utils module, identifiers, copies, the in-memory cache, shared objects, PATH, MEMORIZE(), BACKUP() and RESTORE(). Total.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()`). ```js var id = UID(); // 'JacVuE1cn61f' var copy = CLONE(model); // deep copy var url = QUERIFY('/api/products/', { page: 2, q: 'shoe' }); var file = PATH.databases('settings.json'); CACHE.set('stats', data, '10 minutes'); ``` The 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/). ## Identifiers and hashes `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. ```js var model = {}; model.id = UID(); model.token = GUID(30); model.checksum = HASH(model.id + model.token, 'sha256'); ``` For 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). ## Copying and comparing objects `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. ```js var user = { id: 'abc', name: 'Peter', email: 'peter@example.com', admin: true }; var form = { name: 'Lucia', email: 'lucia@example.com', admin: false }; var allowed = { name: '', email: '' }; COPY(form, allowed, false); // { name: 'Lucia', email: 'lucia@example.com' } U.extend(user, allowed); // user.admin stays true ``` `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: ```js var db = [{ id: 1, name: 'A' }, { id: 2, name: 'B' }]; var form = [{ id: 2, name: 'B2' }, { id: 3, name: 'C' }]; var diff = DIFFARR('id', db, form); // diff.add === [{ id: 3, name: 'C' }] // diff.upd === [{ db: { id: 2, name: 'B' }, form: { id: 2, name: 'B2' } }] // diff.rem === [1] ``` `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()`. ## Converting values `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: ```js var page = U.parseInt(this.query.page, 1); var price = U.parseFloat('12,50'); // 12.5 var active = U.parseBoolean('on'); // true ``` `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: ```js QUERIFY({ q: 'red shoes', tags: ['a', 'b'] }); // '?q=red%20shoes&tags=a%2Cb' QUERIFY('GET /api/products/', { page: 2 }); // 'GET /api/products/?page=2' ``` ## Hostnames A 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: ```js U.validhost('example.com'); // true U.validhost('127.1'); // false U.tohost('münchen.de'); // 'xn--mnchen-3ya.de' U.tohost('127.1'); // '127.0.0.1' U.tohost('a\0b.com'); // '' ``` The 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. ## Shared objects | Global | What it is for | | --- | --- | | `MAIN` | An empty object for the shared state of your application | | `REPO` | An empty object for shared data; also available in views | | `FUNC` | An empty object for your own shared functions | | `TEMP` | An object for short-lived data; the framework replaces it with an empty object every 5 minutes | | `MODS` | The loaded modules from `/modules/`, by their `id` | | `NOW` | A `Date` that the framework refreshes every 5 seconds | | `NOOP` | An empty function, for callbacks you do not need | | `EMPTYOBJECT`, `EMPTYARRAY` | A frozen `{}` and `[]`, for default values that must not change | `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. ```js // definitions/init.js FUNC.slug = function(name) { return name.slug(); }; MAIN.settings = { title: 'My shop' }; // anywhere else var slug = FUNC.slug('Red shoes'); ``` ## In-memory cache `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. ```js async function products($) { var items = CACHE.get('products'); if (!items) { items = await DATA.find('nosql/products').promise($); CACHE.set('products', items, '2 minutes'); } $.callback(items); } ``` The 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). ## Caching generated data in a file `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`. ```js FILECACHE('sitemap', '1 hour', function(err, response) { console.log(response.length); }, function(next) { DATA.find('nosql/pages').fields('id,url').callback(function(err, response) { next(err, response); }); }); ``` ## Persistent state with MEMORIZE() `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. ```js var stats = MEMORIZE('stats'); if (!stats.visits) stats.visits = 0; function visit() { stats.visits++; stats.save(); } ``` ## Paths `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. ```js var filename = PATH.databases('exports/' + UID() + '.csv'); var exists = await PATH.exists(filename); ``` `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`: ```js var text = await Total.FsPromises.readFile(PATH.root('README.md'), 'utf8'); ``` ## Archives with BACKUP() and RESTORE() `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. ```js await BACKUP(PATH.temp('site.backup'), PATH.public()); await RESTORE(PATH.temp('site.backup'), PATH.root('public-copy')); ``` ## Large data `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()`. ```js var Fs = require('fs'); var chunker = U.chunker('export', 500); var stream = Fs.createReadStream(PATH.databases('products.xml')); stream.on('data', U.streamer('<product>', '</product>', function(value) { chunker.write(value.parseXML()); })); stream.on('end', function() { chunker.end(); chunker.each(function(items, next) { // 500 products at a time next(); }); }); ``` For 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: ```js var parser = U.aistreamer(function(line) { print(line); }); response.stream.on('data', parser); ``` ## Promises Most 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: ```js var Fs = require('fs'); var buffer = await PROMISIFY(Fs.readFile, PATH.root('README.md')); ``` --- title: Prototypes project: Total.js V5 version: 0.0.20 section: guides language: en license: MIT url: https://totaljs.es/docs/total-js-v5/0-0-20/guides/prototypes/ updated: 2026-11-16T15:32:42.496Z --- # Prototypes > Methods that Total.js adds to String, Number, Date and Array: formatting, parsing, validation, hashing, dates and array helpers. Total.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. ```js var title = 'Hello World!'; title.slug(); // hello-world '{0} items'.format(5); // 5 items (1234.5).format(2); // 1 234.50 new Date().add('1 day').format('yyyy-MM-dd'); users.findItem('id', 5); ``` The full list with every argument is in the reference [Prototypes](../../reference/prototypes/). This guide shows the groups and the methods you use most. ## Strings: templates and text `format()` fills numbered placeholders and `args()` fills named ones. `args()` can encode the values for HTML, JSON or URLs: ```js 'Hello {0}, you have {1} messages.'.format('Peter', 5); var tpl = '<a href="/users/{id}/">{name}</a>'; tpl.args({ id: 10, name: '<Peter>' }, 'html'); // <a href="/users/10/"><Peter></a> ``` For text from users and for URLs: ```js 'Čaute, svet!'.slug(); // caute-svet '<b>Hi</b>'.encode(); // <b>Hi</b> '<b>'.decode(); // <b> '<p>Hi</p>'.removeTags(); // Hi 'A long description'.max(10); // A long ... 'hello world'.capitalize(); // Hello World 'Čučoriedka'.toASCII(); // Cucoriedka ``` `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). ## Strings: parsing The `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. ```js '10'.parseInt(); // 10 'abc'.parseInt(1); // 1 (the default) '1,5'.parseFloat(); // 1.5 'on'.parseBoolean(); // true '{"a":1}'.parseJSON(); // { a: 1 }, or undefined for bad JSON '2024-05-01 12:30'.parseDate(); // a Date in UTC '01/05/2024'.parseDate('dd/MM/yyyy'); '5 minutes'.parseDateExpiration(); // now + 5 minutes ``` Structured text formats have their own parsers: ```js 'q=total&page=2'.parseEncoded(); // { q: 'total', page: '2' } 'PORT=8000\nNAME="App"'.parseEnv(); // { PORT: '8000', NAME: 'App' } 'count (number) : 10'.parseConfig(); // { count: 10 } 'a,b\n1,2'.parseCSV(); // [{ a: 'a', b: 'b' }, { a: '1', b: '2' }] req.headers['user-agent'].parseUA(); // Windows Chrome ``` `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`: ```js var text = PATH.root('prompts.txt'); var blocks = Total.Fs.readFileSync(text, 'utf8').parseContext(); // [{ name: 'welcome', type: 'prompt', body: '...' }, ...] ``` `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: ```js var rows = text.parseCSV(';'); var header = rows.shift(); var users = rows.map(row => ({ name: row.a, email: row.b })); ``` ## Strings: validation The `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: ```js 'info@example.com'.isEmail(); // true '+421903123456'.isPhone(); // true 'https://totaljs.com'.isURL(); // true UID().isUID(); // true (the checksum is checked too) '123'.isNumber(); // true '<script>'.isXSS(); // true // /definitions/validators.js DEF.validators.phone = /^\+?[0-9\s]{6,20}$/; ``` ## Strings: hashing and encryption ```js 'text'.hash(); // a fast 32-bit number, for cache keys 'text'.hash('sha256'); // the same as 'text'.sha256() 'text'.md5(); 'password'.sha512(CONF.secret); var link = '123'.sign('key'); // 123-nzo165 link.sign('key', true); // 123, or null when the text was changed var secret = 'user@example.com'.encrypt('key'); secret.decrypt('key'); // user@example.com var token = '123'.encrypt_uid(); // a short token for public URLs token.decrypt_uid(); // 123 ``` `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. ## Numbers ```js (1234567.891).format(2); // 1 234 567.89 (1234.5).format(2, ',', '.'); // 1,234.50 (1.005).round(2); // 1.01 (100).VAT(20); // 120 (100).discount(15); // 85 (5).padLeft(3); // 005 (1536000).filesize(); // 1.46 MB (3).pluralize('no files', '# file', '# files', '# files'); // 3 files (5).between({ '0-3': 'low', '4-6': 'medium', '7-': 'high' }); // medium ``` `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`. ## Dates The application runs in UTC unless the `$timezone` configuration key says otherwise, so dates are formatted in UTC by default. ```js var now = new Date(); now.add('1 day'); // a new Date, now is not changed now.add('-30 minutes'); now.format('yyyy-MM-dd HH:mm'); // 2024-05-01 12:30 now.format('dddd, d. MMMM yyyy'); // Wednesday, 1. May 2024 now.format(); // ISO string in UTC now.extend('08:00'); // the same day at 08:00 now.diff(created, 'days'); // days between created and now now.setTimeZone('America/New_York').format('HH:mm'); // the time in New York ``` ## Arrays The find methods accept a function, a property name with a value, or a single value: ```js var users = [{ id: 1, name: 'Peter', role: 'admin' }, { id: 2, name: 'Anna', role: 'user' }]; users.findItem('id', 2); // { id: 2, ... } or null users.findAll('role', 'admin'); // an array users.findIndex(u => u.name === 'Anna'); // 1 users.findValue('id', 1, 'name'); // Peter users = users.remove('id', 1); // a new array without the item users.quicksort('name'); // in place, by name users.quicksort('role,name_desc'); // several columns users.group('role'); // [{ name: 'admin', items: [...] }, ...] all.skip(20).take(10); // paging ``` `remove()`, `findAll()`, `take()` and `skip()` return new arrays; `quicksort()` and `random()` change the array itself. For 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: ```js files.wait(function(file, next) { FUNC.process(file, next); }, function() { console.log('All files are processed'); }, 3); ``` `async()` runs an array of functions in sequence and `limit()` processes an array in chunks, which is handy for inserting many rows in batches. --- title: Images project: Total.js V5 version: 0.0.20 section: guides language: en license: MIT url: https://totaljs.es/docs/total-js-v5/0-0-20/guides/images/ updated: 2026-11-19T16:16:57.153Z --- # Images > Resize, crop, convert, watermark and measure images with GraphicsMagick or ImageMagick. Total.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()`. Install 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/). ## Load an image The `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: ```js var img = Image.load(PATH.public('photos/beach.jpg')); img.resize(800, 600); img.quality(85); img.save(PATH.public('photos/beach-800.jpg'), function(err) { if (err) console.error(err); }); ``` ```js // From a Buffer or a stream var img = Image.load(buffer); var img2 = Image.load(F.Fs.createReadStream('/tmp/upload.png')); ``` The 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')`. The methods return the image object, so you can chain them: ```js Image.load(filename).resize(200, 200).grayscale().quality(80).save(target, callback); ``` Other 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. ## Choose the program The 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/). ``` $imageconverter : im ``` The second argument of `Image.load()` changes it for one image: ```js var img = Image.load(filename, 'magick'); ``` ## Resize and crop | Method | What it does | | --- | --- | | `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%'` | | `thumbnail(w, h, [options])` | Like `resize()`, but also removes the profiles, for small previews | | `scale(w, h, [options])` | A fast resize without filtering | | `crop(w, h, [x], [y])` | Cuts a `w`x`h` area at the offset `x`, `y` | | `extent(w, h, [x], [y])` | Sets the canvas to `w`x`h`; new area is filled with the background color | | `resizecenter(w, h, [color])` | Fills the `w`x`h` box completely and crops the centre | | `resizealign(w, h, [align], [color])` | Like `resizecenter()` but crops at the given side | | `miniature(w, h, [color])` | Fits the image into `w`x`h` and fills the rest with the color (white) | ```js // A square avatar, the face is usually at the top Image.load(filename).resizealign(200, 200, 'top').quality(90).save(target); // The whole photo inside 300x300, with a white border Image.load(filename).miniature(300, 300).save(target); ``` `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'`. ## Adjust and transform ```js var img = Image.load(filename); img.rotate(90); // degrees img.flip(); // vertical mirror img.flop(); // horizontal mirror img.blur(3); img.grayscale(); img.sepia(); img.normalize(); img.colors(16); // reduce the palette img.bitdepth(8); img.quality(75); // compression level, 80 when empty img.save(target); ``` `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'`. ## Watermarks `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: ```js Image.load(filename) .resize(1200) .watermark(PATH.public('img/logo.png'), 20, 20, 120, 40) .save(target); ``` ## Any other option `command(key, [value], [priority], [escape])` adds any option of the program. Pass `true` as the third argument to put the value in quotes: ```js img.command('-sharpen', '0x1'); img.command('-strip'); img.command('-label', 'Holiday 2024', true); ``` The 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: ```js var img = Image.load('photo.jpg').resize(200, 100); console.log(img.cmd('photo.jpg', 'small.jpg')); // gm convert 'photo.jpg' -resize '200x100' 'small.jpg' ``` `img.clear()` removes all operations, and `img.make(fn)` calls `fn(img)` so you can keep a set of operations in a function. ## Save, pipe and stream `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)`: ```js Image.load(buffer).resize(400).save(PATH.public('upload/photo.jpg'), function(err, success) { // success === true }); ``` `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()`: ```js function preview($) { var img = Image.load(PATH.public('photos/' + $.params.id + '.jpg')); img.resize(300, 300); $.res.writeHead(200, { 'content-type': 'image/webp' }); img.pipe($.res, 'webp'); } ``` `writer([type])` starts the conversion and returns the readable output stream: ```js var stream = Image.load(buffer).resize(100, 100).writer('png'); stream.pipe(F.Fs.createWriteStream('/tmp/thumb.png')); ``` When an image has no operations, `save()`, `pipe()` and `writer()` add `minify()`, which removes the profiles and metadata. For HTTP responses with a cache, `$.image()` of the controller is shorter (see [Controller](../../guides/controller/)). ## Measure an image The module reads the size from the header of the file, without the external program: ```js var size = Image.measure('png', buffer); // { width: 800, height: 600 } Image.load(PATH.public('photos/beach.jpg')).measure(function(err, size) { console.log(size.width, size.height); }); ``` `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/). ## Post-processing middleware `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: ```js Image.middleware('png', function() { return new MyPngOptimizer(); // a Transform stream }); ``` The type is `img.type`: the extension of the source, or the value of `output()`. For `pipe()` and `writer()` it is the output format. --- title: AI models project: Total.js V5 version: 0.0.20 section: guides language: en license: MIT url: https://totaljs.es/docs/total-js-v5/0-0-20/guides/ai-models/ updated: 2026-11-19T16:16:52.152Z --- # AI models > Register AI model handlers with NEWAIMODEL() and build chat requests with AIMODEL(): messages, config, callbacks, promises, streaming and tool calls. Total.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. ```js // definitions/ai.js NEWAIMODEL('assistant', function(ai, callback) { // ai.payload.model, ai.payload.messages, ai.config, ai.options.stream callback(null, 'Hello from the model'); }); // anywhere in the application AIMODEL('assistant').user('Say hello').callback(function(err, response) { console.log(err, response); }); ``` The full list of functions, methods and properties is in the reference of [AI models](../../reference/ai-models/). ## Registering a model `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. ```js NEWAIMODEL('gpt-4o-mini, gpt-4o', { url: 'https://api.openai.com/v1/chat/completions', token: 'sk-...', temperature: 0.2 }, function(ai, callback) { // the same handler serves both models }); ``` The handler is called as `handler(ai, callback)`: - `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). - `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. The `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. ## Building a request `AIMODEL(name)` returns a new request for the model `name`. Its methods return the request, so you chain them: | Method | What it does | | --- | --- | | `system(content, [merge])` | Adds a message with the role `system` | | `user(content, [merge])` | Adds a message with the role `user` | | `assistant(content, [merge])` | Adds a message with the role `assistant` | | `message(role, content, [merge])` | Adds a message with any role | | `prompt(content)` | Sets `payload.prompt`, for single-prompt endpoints | | `think()` | Sets `payload.think = true` | | `configure(obj)` | Copies the keys of `obj` into `ai.config` | | `tool(content)` | Adds a tool definition to `payload.tools` | The 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`: ```js AIMODEL('assistant') .system('You are a helpful assistant. Answer briefly.') .user('What is Total.js?') .assistant('A Node.js framework.') .user({ content: 'Describe this picture', images: [base64] }) .configure({ temperature: 0 }) .callback(console.log); ``` ### Merging messages The `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: ```js var ai = AIMODEL('assistant'); ai.system('You are a support agent.'); ai.system('Answer in English.', '\n'); ai.system('Never share internal links.', '\n'); // one system message with three lines ``` ## Running the request A 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. ```js AIMODEL('assistant').user('Hello').callback(function(err, response) { if (err) console.log('AI error:', err); else console.log(response); }); ``` `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: ```js NEWACTION('Assistant/ask', { name: 'Ask the assistant', input: '*question:String', action: async function($, model) { var response = await AIMODEL('assistant').user(model.question).promise($); $.callback({ answer: response }); } }); ``` When no model with the name is registered, the callback receives the error `'AI model not found.'`. ## Streaming `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. ```js AIMODEL('assistant') .user('Write a short poem about Node.js') .stream(function(text) { process.stdout.write(text); }) .callback(function(err) { console.log('\nDone', err || ''); }); ``` ## Tools `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)). ```js var weather = { type: 'function', function: { name: 'weather', description: 'Returns the weather forecast for a city', parameters: { type: 'object', properties: { city: { type: 'string' } }, required: ['city'] } } }; AIMODEL('assistant') .user('What is the weather in Bratislava?') .tool(weather) .callback(console.log); ``` In the handler, add the tools to the body when there are some: ```js if (ai.payload.tools.length) body.tools = ai.payload.tools; ``` When 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 })`. ## Parsing streams with AIPARSER() `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. | Provider | Format | | --- | --- | | `ollama` | Ollama `/api/chat` and `/api/generate` (and its OpenAI-compatible endpoint) | | `openai`, `openai_chat` | OpenAI Chat Completions | | `openai_responses` | OpenAI Responses API | | `claude`, `anthropic` | Anthropic Messages | | `gemini`, `google` | Google Gemini | | anything else | A generic parser that reads `content`, `text`, `thinking`, `reasoning`, `message.*` and `tool_calls` | `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: ```js { content: 'The text of the answer', thinking: 'The reasoning, if the model sends it', tools: [], // the tool calls: { id, name, arguments } reasoning: 'content' // or 'thinking' or 'tool' } ``` The 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: ```js var parser = AIPARSER('openai'); parser.on('content', function(e) { ai.options.stream(e.delta); }); for await (var chunk of res.body) parser.write(Buffer.from(chunk)); var output = parser.end(); callback(null, output); ``` The parser does not depend on `AIMODEL()`, so you can also use it to read a stream that you requested yourself. ## Tool calls in a stream The 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: ```js var parser = AIPARSER('openai'); // recorded server-sent events of an OpenAI Chat Completions stream var chunks = [ 'data: {"choices":[{"index":0,"delta":{"role":"assistant","tool_calls":[{"index":0,"id":"call_A","type":"function","function":{"name":"weather","arguments":""}}]}}]}\n\n', 'data: {"choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"{\\"city\\":"}}]}}]}\n\n', 'data: {"choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"\\"Bratislava\\"}"}}]}}]}\n\n', 'data: {"choices":[{"index":0,"delta":{},"finish_reason":"tool_calls"}]}\n\n', 'data: [DONE]\n\n' ]; parser.on('tool_start', function(e) { console.log('calling', e.tool.name); }); for (var chunk of chunks) parser.write(chunk); var output = parser.end(); console.log(output.reasoning); // 'tool' console.log(output.tools); // [{ id: 'call_A', name: 'weather', arguments: { city: 'Bratislava' } }] ``` Each 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`. Three 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: | Event | When | | --- | --- | | `tool_start` | A new call appears | | `tool_update` | More data of a known call arrives (before each further piece of its arguments) | | `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) | With `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. To 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. ## A complete handler This 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()`. ```js NEWAIMODEL('gpt-4o-mini', { url: 'https://api.openai.com/v1/chat/completions', token: 'sk-...' }, function(ai, callback) { var body = {}; body.model = ai.payload.model; body.messages = ai.payload.messages; if (ai.config.temperature != null) body.temperature = ai.config.temperature; if (ai.payload.tools.length) body.tools = ai.payload.tools; if (ai.options.stream) body.stream = true; var opt = {}; opt.method = 'POST'; opt.headers = { 'Content-Type': 'application/json', Authorization: 'Bearer ' + ai.config.token }; opt.body = JSON.stringify(body); fetch(ai.config.url, opt).then(async function(res) { if (!res.ok) { callback('HTTP ' + res.status + ': ' + (await res.text())); return; } if (!ai.options.stream) { var json = await res.json(); callback(null, json.choices[0].message.content); return; } var parser = AIPARSER('openai'); parser.on('content', function(e) { ai.options.stream(e.delta); }); for await (var chunk of res.body) parser.write(Buffer.from(chunk)); callback(null, parser.end().content); }).catch(callback); }); ``` The 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. ## Tips - Keep tokens in the [configuration](../../guides/configuration/) and pass them to `NEWAIMODEL()` as config, not in every request. - 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. - `ai.payload` is a plain object. A handler can send it almost as it is to providers whose API takes `model` and `messages`. --- title: Proxy project: Total.js V5 version: 0.0.20 section: guides language: en license: MIT url: https://totaljs.es/docs/total-js-v5/0-0-20/guides/proxy/ updated: 2026-11-16T16:36:31.083Z --- # Proxy > Forward requests with PROXY(), and publish an app of a private network through a public Total.js app with PROXYSERVER() and PROXYCLIENT(). `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). ### Publishing a local app through a public server `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. ```js // The public app PROXYSERVER('/', '/$proxy/'); ``` ```js // The private machine (any Total.js app, or a small script) PROXYCLIENT('https://public.example.com/$proxy/', '127.0.0.1:8000'); ``` `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. --- title: LDAP project: Total.js V5 version: 0.0.20 section: guides language: en license: MIT url: https://totaljs.es/docs/total-js-v5/0-0-20/guides/ldap/ updated: 2026-11-16T16:36:21.082Z --- # LDAP > Read users and groups from an LDAP server such as Active Directory with LDAP(). `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. ```js var users = await LDAP({ ldap: { host: 'ad.example.com', port: 389 }, user: 'CN=reader,CN=Users,DC=example,DC=com', password: CONF.ldap_password, dn: 'CN=Users,DC=example,DC=com', type: 'person' }); // [{ cn: 'Peter', mail: 'peter@example.com', memberOf: ['CN=Admins,...', ...], ... }] ``` Each 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`...). To 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: ```js var profile = await LDAP({ ldap: { host: 'ad.example.com' }, user: 'peter@example.com', password: password }); ``` `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. Attributes are text by default. The `attributes` option tells how to read the others, for example a photo: ```js var profile = await LDAP({ ldap: { host: 'ad.example.com' }, user: 'peter@example.com', password: password, attributes: { thumbnailPhoto: 'buffer', employeeNumber: 'number', whenCreated: 'date' } }); ``` The types are `string`, `number`, `date`, `buffer` (or `binary`) and the encodings `hex`, `base64`, `ascii` and `utf8`. A 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: ```js try { var profile = await LDAP({ ldap: { host: 'ad.example.com' }, user: 'peter@example.com', password: password }); } catch (err) { // 'LDAP bind error 49' or the text of the server } ``` --- title: Markdown project: Total.js V5 version: 0.0.20 section: guides language: en license: MIT url: https://totaljs.es/docs/total-js-v5/0-0-20/guides/markdown/ updated: 2026-11-16T15:32:27.494Z --- # Markdown > Convert Markdown to HTML with String.prototype.markdown(), and the Markdown syntax it supports. `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. ```js var html = '# Hello\n\nSome **bold** text with a [link](https://www.totaljs.com).'.markdown(); ``` Besides 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: | Syntax | Output | | --- | --- | | `:check:` or `:ti ti-user:` | An icon `<i class="ti ti-check">` | | `{keyword}(type)` | `<span class="markdown-keyword" data-type="type">` | | `[1](#1)` and a line `#1: text` | A footnote and its text | | `< text` | A `<section>` | | `::: Title` … `:::` | A block that can be expanded | | `![+alt](url)`, `![-alt](url)` | An image without `img-responsive`, a gallery image | Headings 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. --- title: HTML and XML parser project: Total.js V5 version: 0.0.20 section: guides language: en license: MIT url: https://totaljs.es/docs/total-js-v5/0-0-20/guides/html-parser/ updated: 2026-11-19T16:16:52.152Z --- # HTML and XML parser > Parse HTML and XML on the server into a tree of elements that you can search and change. `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`). ```js var dom = '<div class="list"><p id="a">Hello <b>world</b></p><p data-id="2">Bye</p></div>'.parseHTML(); dom.find('p').length; // 2 dom.find('div > p[data-id="2"]').text(); // 'Bye' var p = dom.find('#a')[0]; p.aclass('big').css('color', 'red').attr('title', 'Greeting'); p.find('b')[0].remove(); dom.html(); // '<div class="list"><p id="a" class="big" style="color:red" title="Greeting">Hello </p>...' ``` `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`. --- title: Macros project: Total.js V5 version: 0.0.20 section: guides language: en license: MIT url: https://totaljs.es/docs/total-js-v5/0-0-20/guides/macros/ updated: 2026-11-16T15:32:27.494Z --- # Macros > Compile a small rule language into a function with NEWMACRO(), for rules that users write. `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. ```js var rule = NEWMACRO([ '#total = price * count', 'IF #total > 1000 AND country == "SK"', ' RETURN discount(#total)', 'FI', 'RETURN #total' ].join('\n')); rule({ price: 600, count: 2, country: 'SK' }, { discount: function(value) { return value * 0.8; } }); // 960 ``` A 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. --- title: Tangular project: Total.js V5 version: 0.0.20 section: guides language: en license: MIT url: https://totaljs.es/docs/total-js-v5/0-0-20/guides/tangular/ updated: 2026-11-16T15:32:27.494Z --- # Tangular > The Tangular template engine: compile and render templates and register helpers. Tangular 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). ```js var template = Tangular.compile('<h1>{{ name }}</h1>{{ foreach item in items }}<p>{{ item.price | format(2) }}</p>{{ end }}'); var html = template({ name: 'Order', items: [{ price: 10 }] }); ``` The 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. --- title: Minification project: Total.js V5 version: 0.0.20 section: guides language: en license: MIT url: https://totaljs.es/docs/total-js-v5/0-0-20/guides/minification/ updated: 2026-11-16T15:48:48.957Z --- # Minification > Minify JavaScript, CSS and HTML from your code with the minificators of U. The framework minifies static `.js`, `.css` and `.html` files and merged files (see [Static files](../static-files/)). The same minificators are in `U`: ```js U.minify_css('.box {\n\t.title { margin: 0 0 0 0; color: #FFFFFF; }\n}'); // '.box .title{margin:0;color:#FFF}' U.minify_js('function sum(a, b) {\n\t// adds\n\treturn a + b;\n}'); // 'function sum(a,b){return a+b}' U.minify_html(html); ``` The 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/). The 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. --- title: CMS compiler project: Total.js V5 version: 0.0.20 section: guides language: en license: MIT url: https://totaljs.es/docs/total-js-v5/0-0-20/guides/cms/ updated: 2026-11-16T15:32:37.496Z --- # CMS compiler > Compile pages made with the Total.js CMS editor and render them with their widgets. `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. ```js var widgets = [{ id: 'hello', css: '.hello { color: red; }', render: function(opt, next) { next('<b>Hello ' + opt.config.name + '</b>'); } }]; var page = F.TCMS.compile(html, widgets); page.importcss(); var output = await page.render({ url: '/about/', navigation: function(id) { return [{ url: '/', name: 'Home' }]; } }); ``` A `<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`. --- title: Application structure and modes project: Total.js V5 version: 0.0.20 section: guides language: en license: MIT url: https://totaljs.es/docs/total-js-v5/0-0-20/guides/application-structure/ updated: 2026-11-19T16:16:52.152Z --- # Application structure and modes > The start script, the folders and their loading order, debug and release mode, bundles, remote editing, modules and statistics. A 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/). ## The start script The start script (usually `index.js`) is the file that you run with `node`. It loads `total5` and calls `F.run()` with the start options: ```js require('total5'); var options = {}; // options.ip = '127.0.0.1'; // options.port = parseInt(process.argv[2]); // options.config = { name: 'Total.js' }; // options.cluster = 'auto'; F.run(options); ``` `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/). The 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. ## Folders and the loading order `LOAD()` (called by `F.http()` and `F.run()`) reads the application in this order: 1. `.env`: environment variables 2. `config`: the configuration (see [Configuration](../../guides/configuration/)) 3. `version`: the first line becomes `CONF.version` as a number 4. `resources/*.resource`: dictionaries (see [Localization](../../guides/localization/)) 5. `jsonschemas/*.json` and `jsonschemas/*.txt`: JSON schemas, named after the file 6. the JavaScript files of `extensions`, `modules`, `actions`, `schemas`, `models`, `definitions`, `controllers` and `middleware`, in this order 7. `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`) 8. `flowstreams/*.flow`: the FlowStream engine loads the flows (see [FlowStream](../../guides/flowstream/)) 9. the framework statistics and the service timer The 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: ```js // controllers/api.js exports.install = function() { ROUTE('GET /api/time/', function($) { $.json({ now: new Date() }); }); }; ``` When 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/)). Other 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. ### Loading only some parts `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: ```js require('total5'); LOAD('config,modules,actions', function() { // the application is ready, without the web server }); ``` ## Debug mode and the watcher In 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: ``` --- UPD --- [ 2025-03-01 10:15:22 ] --------> /controllers/api.js ``` `ADD`, `UPD` and `REM` mark added, updated and removed files, and `RES` a restart asked by the application itself with `F.restart()`. The 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. The 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. The 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>`. ### Live reload With `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. ## Release mode ```js require('total5'); F.run({ watcher: false, port: 8000 }); ``` In 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. ### Service mode `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. ### Cluster `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/). ## Bundles A 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. When `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`): 1. Every `bundles/<name>.url` file contains a URL; the bundle is downloaded into `bundles/<name>.bundle`. 2. The files of the previous build (listed in `.src/bundle.json`) are removed. 3. 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. 4. 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. 5. The list of files is written to `.src/bundle.json`. The `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. A `.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`). ``` /docs/ /readme.md /public/*.map ``` With 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' } })`. A 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`. With 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. ## Remote editing The 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: ```js require('total5'); F.run({ edit: 'wss://code.example.com/?id=myproject' }); ``` The 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`. The 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. In 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. ### Remote editing by an AI agent `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: ```js require('total5'); F.run({ editmcp: 'wss://proxy.example.com/$mcp/?id=myproject' }); ``` The proxy is a Total.js application with `$mcp : true` and one WebSocket route: ```js const editmcp = require('total5/edit-mcp'); ROUTE('SOCKET /$mcp/', $ => editmcp.proxy($)); ``` The 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. `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. ## Modules and MODS A 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()`: ```js // modules/counter.js exports.id = 'counter'; var count = 0; exports.install = function() { ROUTE('GET /counter/', function($) { $.json({ count: exports.increment() }); }); }; exports.increment = function() { return ++count; }; // anywhere after the start MODS.counter.increment(); ``` Plugins are registered in `PLUGINS` in the same way (see [Plugins and components](../../guides/plugins-and-components/)). ## IMPORT() and REQUIRE() `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: ```js var Fs = REQUIRE('fs'); var helpers = await IMPORT('https://cdn.example.com/helpers.js'); ``` ## Framework statistics `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`. Once 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: ```js ON('$stats', function(stats) { if (stats.memory > 500) console.log('High memory usage:', stats.memory, 'MB'); }); ``` The 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. --- title: Unit tests project: Total.js V5 version: 0.0.20 section: guides language: en license: MIT url: https://totaljs.es/docs/total-js-v5/0-0-20/guides/unit-tests/ updated: 2026-11-18T15:27:34.798Z --- # Unit tests > Write unit tests with the Test runner of total5/test: test groups, results, fake actions and how to run them with total5 test. `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()`: ```js // tests/run.js require('total5/test'); Test.push('Strings', function(next) { Test.print('slug()', 'Hello World'.slug() === 'hello-world' ? null : 'Unexpected slug'); Test.print('capitalize()', 'total'.capitalize() === 'Total' ? null : 'Unexpected value'); next(); }); Test.run(); ``` The 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. To 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. ## Running tests with total5 test The 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: ``` tests/ config init.js orders.js strings.js ``` ```bash cd ~/projects/shop total5 test # all scripts total5 test strings # tests/strings.js total5 test strings orders # two scripts, in this order ``` The command: 1. takes the `tests` directory of the current directory, or the current directory when it has no `tests` directory, 2. loads the `config` file of that directory into `CONF`, in the format of the [configuration](../../guides/configuration/) file, 3. creates `Test` and loads `init.js` when it exists, 4. 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, 5. calls `Test.run()`. The 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: ```js // tests/strings.js Test.push('Strings', function(next) { Test.print('slug()', 'Hello World'.slug() === 'hello-world' ? null : 'Unexpected slug'); Test.print('config', CONF.name === 'Shop tests' ? null : 'Unexpected name'); next(); }); ``` The 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`). `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. The 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: ```js // tests/init.js Test.push('Init', function(next) { LOAD('actions', next); }); ``` ## Fake actions `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: ```js // actions/orders.js NEWACTION('Orders/create', { input: '*name:String', action: function($, model) { ACTION('Mail/send', { to: 'shop@example.com', subject: 'Order ' + model.name }).callback(function(err, response) { if (err) $.invalid(err); else $.callback({ name: model.name, mail: response }); }); } }); NEWACTION('Mail/send', { input: '*to:Email,*subject:String', action: function($, model) { // sends the e-mail $.callback('sent'); } }); ``` the test of `Orders/create` replaces `Mail/send`: ```js // tests/orders.js Test.push('Orders', async function(next) { var sent = []; // no e-mail goes out during the test Test.fake('Mail/send', { input: '*to:Email,*subject:String', action: function($, model) { sent.push(model.subject); $.callback('fake'); } }); var response = await ACTION('Orders/create', { name: 'A100' }).promise(); Test.print('Orders/create', response.mail === 'fake' ? null : 'The fake was not used'); Test.print('Mail/send', sent[0] === 'Order A100' ? null : 'No e-mail'); Test.restore(); next(); }); ``` When 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. --- title: Command line (total5) project: Total.js V5 version: 0.0.20 section: guides language: en license: MIT url: https://totaljs.es/docs/total-js-v5/0-0-20/guides/command-line/ updated: 2026-11-16T16:33:35.963Z --- # Command line (total5) > The total5 and flow5 programs: a static web server, translations, minifying, bundles, remote editing, a proxy client, tests and running flows. The `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/)): ```bash npm install -g total5 ``` Each `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: ```bash $ total5 minify /www/app/public/app.js * Total.js v5: [Minify] ---------------------------------------- Filename : /www/app/public/app.js Output : /www/app/public/app.min.js ---------------------------------------- [Done]: 1.2ms ``` ## Command syntax ```bash total5 <command> [arguments] ``` - 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`. - The words after it are the arguments, in order. Double quotes inside them are removed and spaces at the ends are trimmed. - A number as the command (`total5 8000`) starts the web server on that port. - `total5` with no command shows the help. - A word the program does not know prints only the header and does nothing. ## The help `total5` or `total5 help` lists the commands: | Command | What it does | | --- | --- | | `translate <filename>` | Makes a resource file from the `@(...)` texts of the current directory | | `minify <filename>` | Minifies a `.js`, `.css` or `.html` file | | `bundle <filename>` | Packs the current directory into a `.bundle` file | | `extract <filename>` | Unpacks a bundle into the current directory | | `edit <url>` | Opens the current directory for remote editing in the Total.js Code Editor | | `proxy <endpoint> <port>` | Connects a local port to a remote Total.js proxy server | | `test [names]` | Runs the tests of the current directory or of its `tests` directory | | `<port>` | Starts a web server for the current directory | ## A web server for a directory A 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. ```bash cd ~/projects/landing total5 8000 # http://0.0.0.0:8000/ ``` - Files are served from the current directory. Minification and source maps are off, so you get the files exactly as they are on disk. - 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. - The application folders (`controllers/`, `config`, …) are not loaded: it is only a file server. Stop it with `Ctrl+C`. ## Translations `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: ```bash total5 translate "$PWD/resources/default.resource" ``` ``` T1l964ro : Hello world T1j2ql : Save ``` Each 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/). ## Minifying a file `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: ```bash total5 minify "$PWD/public/js/app.js" # public/js/app.min.js total5 minify "$PWD/public/css/site.css" # public/css/site.min.css total5 minify "$PWD/views/index.html" # views/index.min.html ``` The 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/)). ## Bundles A 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/)). `total5 bundle <filename>` packs the current directory. Give the full path of the bundle and keep it outside the directory you pack: ```bash cd ~/projects/shop total5 bundle ~/backups/shop # ~/backups/shop.bundle ``` `.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/`. `total5 extract <filename>` unpacks a bundle into the current directory. Give the full path of the bundle: ```bash mkdir ~/projects/shop-copy && cd ~/projects/shop-copy total5 extract ~/backups/shop.bundle ``` ## Remote editing `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. ```bash cd ~/projects/shop total5 edit "https://code.example.com/?id=shop" # > Total.js Code Editor: Welcome to "Code (1.0)" # > Project: "shop" ``` The 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`. ## Proxy client `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: ```bash total5 8000 & total5 proxy wss://proxy.example.com/ 8000 total5 proxy wss://proxy.example.com/ 192.168.1.20:8000 ``` The 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. ## Running tests `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: ```bash cd ~/projects/shop total5 test total5 test strings orders ``` It 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/). ## Running flows with flow5 `flow5` loads FlowStream schemas and runs them with a small HTTP server, without an application (see [FlowStream](../../guides/flowstream/)): ```bash flow5 "$PWD/flowschema.json" flow5 "$PWD/flow1.json" "$PWD/flow2.json" 8001 flow5 https://example.com/flowschema.json ``` - 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. - A file holds one schema (an object with `components` and `design`) or an object of several schemas under their ids. - For each flow it prints a link that opens the flow in the Flow editor at `flow.totaljs.com`, connected to your machine. - 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. ``` [Total.js v5 Flow Engine] |--- http://127.0.0.1:8000 |--- Orders: https://flow.totaljs.com/?socket=http%3A%2F%2F127.0.0.1%3A8000%2Fflowstreams%2Forders%2F ``` The 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. --- title: Routing project: Total.js V5 version: 0.0.20 section: reference language: en license: MIT url: https://totaljs.es/docs/total-js-v5/0-0-20/reference/routing/ updated: 2026-11-18T16:57:14.575Z --- # Routing > ROUTE() syntax, flags, the route object, CORS(), PROXY() and the routing configuration. Every 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. ## API ### ROUTE(url, [action], [size]) Type: `method` Declares a route. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `url` | `String` | yes | | The method, the path and the flags, for example `+POST /api/orders/ @json <1MB`. | | `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 `/`). | | `size` | `Number` | no | `CONF.$httpmaxsize` | The maximum body size in bytes. It can be the second argument when there is no action. | Returns: `Route` The route object. `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`. Example: A page and a JSON endpoint ```js exports.install = function() { ROUTE('GET /', index); ROUTE('GET /api/time/', function($) { $.json({ now: new Date() }); }); }; function index($) { $.view('index'); } ``` Example: A view without code ```js exports.install = function() { ROUTE('GET /contact/', 'contact'); ROUTE('GET /about/'); }; ``` ### ROUTE('+METHOD /path/', action) Type: `type` The route is only for signed-in users. The `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`. Example: An account page ```js exports.install = function() { ROUTE('+GET /account/', function($) { $.json($.user); }); }; ``` ### ROUTE('-METHOD /path/', action) Type: `type` The route is only for visitors who are not signed in. Use 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`. Example: Login or account ```js exports.install = function() { ROUTE('+GET /', 'dashboard'); ROUTE('-GET /', 'login'); }; ``` ### ROUTE('GET /path/{name}/', action) Type: `type` A dynamic segment of the path. The 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. Example: Two parameters ```js exports.install = function() { ROUTE('GET /blog/{year}/{slug}/', function($) { $.json({ year: $.params.year, slug: $.params.slug }); }); }; ``` ### ROUTE('GET /path/*', action) Type: `type` Matches the path and everything below it. A wildcard route has a lower priority than fixed and dynamic routes, so it catches only the URLs that no other route takes. Example: A catch-all for a section ```js exports.install = function() { ROUTE('GET /app/*', 'app'); }; ``` ### ROUTE('[+|-]API ? endpoint[/{param}] --> Action', [action]) Type: `type` Declares one endpoint of the API route. The `?` 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. Example: Endpoints ```js exports.install = function() { ROUTE('API ? tasks_list --> Tasks/list'); ROUTE('+API ? tasks_read/{id} --> Tasks/read'); ROUTE('+API ? tasks_save <5MB --> Tasks/save'); }; ``` Example: A function instead of actions ```js exports.install = function() { ROUTE('API ? ping', function($) { $.success(); }); }; ``` Example: Client ```js AJAX('POST /api/', { schema: 'tasks_read/42', data: null }, function(err, response) { console.log(response); }); ``` ### ROUTE('METHOD /path/ --> Action1 [Action2 (response)]') Type: `type` Runs actions instead of a function. The 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. Example: One action ```js exports.install = function() { ROUTE('GET /api/users/ --> Users/list'); }; ``` Example: Insert and read back ```js exports.install = function() { ROUTE('+POST /api/users/ --> Users/insert Users/read (response)'); }; ``` ### ROUTE('METHOD /path/ <10MB', action) Type: `type` Sets the maximum size of the request body. Units: `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). Example: Uploads up to 50 MB ```js exports.install = function() { ROUTE('POST /upload/ @upload <50MB', upload); }; ``` ### ROUTE('METHOD /path/ <30s', action) Type: `type` Sets the timeout of the request. Units: `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. Example: A long export ```js exports.install = function() { ROUTE('GET /export/ <10m', exportdata); }; ``` ### ROUTE('METHOD /path/ #name', action) Type: `type` Runs a middleware before the action. The 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 `_`. Example: Two middleware ```js MIDDLEWARE('cors_api', function($, next) { $.response.headers['x-api'] = '1'; next(); }); exports.install = function() { ROUTE('GET /api/stats/ #cors_api #nocache', stats); }; ``` ### ROUTE('METHOD /path/ @json', action) Type: `type` The route matches only when the request body is JSON (`application/json` or `text/json`). If 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. Example: Usage ```js exports.install = function() { ROUTE('POST /api/orders/ @json', orders); }; ``` ### ROUTE('METHOD /path/ @xml', action) Type: `type` The route matches only when the request body is XML (`application/xml` or `text/xml`). If 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. Example: Usage ```js exports.install = function() { ROUTE('POST /feed/ @xml', feed); }; ``` ### ROUTE('METHOD /path/ @upload', action) Type: `type` The route matches only when the request body is `multipart/form-data`. If 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. Example: Usage ```js exports.install = function() { ROUTE('POST /upload/ @upload <20MB', function($) { $.json($.files.map(f => f.filename)); }); }; ``` ### ROUTE('METHOD /path/ @xhr', action) Type: `type` The route matches only when the request has the header `X-Requested-With: XMLHttpRequest`. If 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. Example: Usage ```js exports.install = function() { ROUTE('GET /partials/menu/ @xhr', 'partials/menu'); }; ``` ### ROUTE('METHOD /path/ @mobile', action) Type: `type` The route matches only when the client is a mobile device. If 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. Example: Usage ```js exports.install = function() { ROUTE('GET /', 'index'); ROUTE('GET /m/ @mobile', 'mobile'); }; ``` ### ROUTE('METHOD /path/ @robot', action) Type: `type` The route matches only when the client is a crawler. If 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. Example: Usage ```js exports.install = function() { ROUTE('GET /prerender/ @robot', 'static'); }; ``` ### ROUTE('METHOD /path/ @referrer', action) Type: `type` The route matches only when the `Referer` header contains the host of the request; `@referer` is the same flag. If 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. Example: Usage ```js exports.install = function() { ROUTE('GET /download/ @referrer', download); }; ``` ### ROUTE('METHOD /path/ @debug', action) Type: `type` The route matches only when the application runs in debug mode. If 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. Example: Usage ```js exports.install = function() { ROUTE('GET /dev/routes/ @debug', function($) { $.json(F.routes.routes.map(r => r.method + ' ' + r.url2)); }); }; ``` ### ROUTE('METHOD /path/ @release', action) Type: `type` The route matches only when the application runs in release mode. If 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. Example: Usage ```js exports.install = function() { ROUTE('GET /status/ @release', status); }; ``` ### ROUTE('FILE /path/pattern', action) Type: `type` Handles requests for static files with your code. File 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`. Example: Generated robots.txt ```js exports.install = function() { ROUTE('FILE /robots.txt', function($) { $.plain('User-agent: *\nDisallow: /admin/'); }); }; ``` Example: Files from a private folder ```js exports.install = function() { ROUTE('FILE /files/*.pdf|docx', function($) { $.file(PATH.databases($.split[1]), true); }); }; ``` ### ROUTE('SOCKET /path/ [flags]', action) Type: `type` Declares a WebSocket endpoint. `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/). Example: Chat ```js exports.install = function() { ROUTE('+SOCKET /chat/{room}/ <1MB', chat); }; ``` ### ROUTE('#code', action) Type: `type` Replaces the default error page for a status code. When 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. Example: Custom 404 ```js exports.install = function() { ROUTE('#404', function($) { $.response.status = 404; $.view('404'); }); }; ``` ### Route Type: `class` The object that ROUTE() returns. It 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`. Example: Inspect a route ```js var route = ROUTE('+POST /api/orders/ @json <2MB', create); console.log(route.method, route.auth, route.size, route.flags); ``` ### route.method Type: `property` The HTTP method in upper case, without `+` or `-`. Returns: `String` `API` routes have `POST`. `FILE` and `SOCKET` routes keep their method name. ### route.url Type: `property` The path split into lower-case segments. Returns: `Array` Parameter segments keep their `{name}` form. The path as written (with `CONF.$root`) is in `route.url2`. ### route.params Type: `property` The dynamic parameters of the path. Returns: `Array` Each item has `name` and `index`, the position of the segment in the path. ### route.flags Type: `property` The `@` flags of the route as an object. Returns: `Object` For example `@json @xhr` gives `{ json: 1, xhr: 1 }`. ### route.middleware Type: `property` The names of the middleware that run before the action. Returns: `Array` The `#name` flags in their order. `MIDDLEWARE(name, fn, assign)` can add names to existing routes. ### route.auth Type: `property` The authorization of the route. Returns: `Number` `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. ### route.size Type: `property` The maximum body size in bytes. Returns: `Number` Set by the size flag or the `size` argument; otherwise `CONF.$httpmaxsize * 1024` (`CONF.$wsmaxsize * 1024` for `SOCKET` routes). ### route.timeout Type: `property` The timeout in seconds, or `0`. Returns: `Number` `0` means the request uses `CONF.$httptimeout`. ### route.priority Type: `property` The order in which routes with the same method and path are checked. Returns: `Number` It starts at `100`, each `@` flag lowers it by one and a wildcard by 50. Higher values are checked first. ### route.type Type: `property` The kind of route. Returns: `String` `route`, `file` or `websocket`. ### route.remove() Type: `method` Removes the route. Returns: `undefined` Unregisters 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. Example: A temporary route ```js var route = ROUTE('GET /maintenance/', function($) { $.plain('Back soon'); }); setTimeout(function() { route.remove(); }, 60000); ``` ### CORS([origins]) Type: `method` Sets the origins allowed for cross-origin requests. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `origins` | `String` | no | `'*'` | The allowed origins, `*`, or `+origins` to add. | Returns: `undefined` Without 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)`. Example: Allow two apps ```js CORS('https://app.example.com,https://admin.example.com'); ``` Example: Add one and allow subdomains ```js CORS('+https://partner.com'); CORS('+*example.org'); ``` Example: Any origin ```js CORS(); ``` ### PROXY(path, [target]) Type: `method` Forwards requests under a path to another server. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `path` | `String` | yes | | The beginning of the request path, for example `/cdn/`. | | `target` | `String|Function` | no | | The target URL, a Unix socket path, or `function($)`. | Returns: `Proxy` The proxy object with chainable methods, or nothing when you remove a proxy. Proxies 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. Example: Forward to a service ```js PROXY('/search/', 'http://127.0.0.1:9200').copy('replace'); ``` Example: Unix socket ```js PROXY('/legacy/', '/var/run/legacy.sock'); ``` Example: Own handler ```js PROXY('/ping/', function($) { $.plain('pong'); }); ``` ### proxy.copy(type) Type: `method` Sets how the request path is copied to the target. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `type` | `String` | yes | | `none`, `replace` or `extend`. | Returns: `Proxy` The proxy. `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. Example: Keep sub-paths ```js // GET /cl/something/?q=1 --> https://example.com/something/?q=1 PROXY('/cl/', 'https://example.com').copy('extend'); ``` ### proxy.before(callback) Type: `method` Changes the outgoing request. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `callback` | `Function` | yes | | `function(uri, $)`. | Returns: `Proxy` The proxy. `callback(uri, $)` runs before the request is sent. `uri` holds the Node.js request options (`path`, `headers`, `method`...). Example: Add a token ```js PROXY('/api2/', 'https://internal.example.com').before(function(uri, $) { uri.headers['x-token'] = CONF.internal_token; }); ``` ### proxy.after(callback) Type: `method` Reads the response of the target. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `callback` | `Function` | yes | | `function(response)`. | Returns: `Proxy` The proxy. `callback(response)` gets the Node.js response before it is sent to the client; you can change `response.headers`. Example: Remove a header ```js PROXY('/cdn/', 'https://cdn.example.com').after(function(response) { delete response.headers['set-cookie']; }); ``` ### proxy.check(callback) Type: `method` Decides for each request whether the proxy is used. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `callback` | `Function` | yes | | `function($)` returning a boolean. | Returns: `Proxy` The proxy. `callback($)` returns `true` to forward the request. Otherwise the request goes to the routes. Example: Only GET ```js PROXY('/files/', 'http://127.0.0.1:8001').check($ => $.method === 'GET'); ``` ### proxy.timeout(ms) Type: `method` Sets the timeout of the forwarded request. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `ms` | `Number` | yes | | The timeout in milliseconds. | Returns: `Proxy` The proxy. In milliseconds. Without it (or with `0`) the proxy uses `CONF.$proxytimeout` seconds. Example: 30 seconds ```js PROXY('/reports/', 'http://127.0.0.1:8002').timeout(30000); ``` ### proxy.remove() Type: `method` Removes the proxy. Returns: `undefined` Requests under its path go to the routes again. `PROXY(path)` without a target does the same. Example: Remove ```js var proxy = PROXY('/old/', 'http://127.0.0.1:8003'); proxy.remove(); ``` ### $api : /api/ Type: `config` The path that `?` stands for in API routes. Returns: `String` Default `/api/`. When `$root` is set, it is added in front. Example: /config ```js $api : /rpc/ ``` ### $root : /app/ Type: `config` A path prefix for all routes. Returns: `String` Every route, proxy and `$api` path is prefixed with it, for example when the app runs under `/app/` behind a web server. Default empty. Example: /config ```js $root : /admin/ ``` ### $cors : https://app.example.com Type: `config` The origins allowed for cross-origin requests. Returns: `String` The same value as `CORS()` takes: `*`, or origins separated by commas, with `*domain` items for partial matches. Default empty (cross-origin requests are not checked). Example: /config ```js $cors : https://app.example.com, *example.org ``` ### $httpmaxsize : 256 Type: `config` The default maximum body size of HTTP routes, in kB. Returns: `Number` Default `256`. A route overrides it with a size flag. Example: /config ```js $httpmaxsize : 1024 ``` ### $httptimeout : 5 Type: `config` The default timeout of HTTP requests, in seconds. Returns: `Number` Default `5`. A route overrides it with a timeout flag. Example: /config ```js $httptimeout : 15 ``` ### $proxytimeout : 5 Type: `config` The default timeout of `PROXY()` requests, in seconds. Returns: `Number` Default `5`. `proxy.timeout()` overrides it for one proxy. Example: /config ```js $proxytimeout : 30 ``` --- title: Controller project: Total.js V5 version: 0.0.20 section: reference language: en license: MIT url: https://totaljs.es/docs/total-js-v5/0-0-20/reference/controller/ updated: 2026-11-18T16:57:24.576Z --- # Controller > Properties and methods of the controller `$` that every route action receives. The 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/). ## API ### $.req Type: `property` The Node.js request object. Returns: `IncomingMessage` The `http.IncomingMessage` of the request. Use it only for what the controller does not offer. ### $.res Type: `property` The Node.js response object. Returns: `ServerResponse` The `http.ServerResponse` of the request. When you write to it yourself, call `$.custom()` first so the framework does not answer the request too. ### $.method Type: `property` The HTTP method of the request. Returns: `String` An upper-case string such as `GET`, `POST`, `PUT`, `PATCH` or `DELETE`. Example: Example ```js ROUTE('POST /api/items/', function($) { // $.method === 'POST' $.success(); }); ``` ### $.url Type: `property` The path of the URL. Returns: `String` The path without the query string. A path without a file extension always ends with `/`, and double slashes are merged. The letters keep their case. Example: Example ```js ROUTE('GET /docs/', function($) { // /docs?page=1 gives '/docs/' $.plain($.url); }); ``` ### $.uri Type: `property` The parsed URL. Returns: `Object` An 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). ### $.split Type: `property` The segments of the path. Returns: `String[]` An array of the parts of the path: `/blog/2025/hello/` gives `['blog', '2025', 'hello']`. The root path `/` gives an empty array. Example: Example ```js ROUTE('GET /blog/*', function($) { $.json($.split); }); ``` ### $.params Type: `property` The dynamic parts of the URL. Returns: `Object` Each `{name}` of the route becomes a key with the matching segment of the path as a string. Convert numbers and dates yourself. Example: Example ```js exports.install = function() { ROUTE('GET /orders/{id}/', order); }; function order($) { var id = $.params.id; $.json({ id: id }); } ``` ### $.query Type: `property` The query string as an object. Returns: `Object` Values 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. Example: Paging ```js function list($) { var page = ($.query.page || '1').parseInt(); $.json({ page: page }); } ``` ### $.body Type: `property` The parsed body of the request. Returns: `Object` For `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. Example: Read the body ```js exports.install = function() { ROUTE('POST /api/contact/', contact); }; function contact($) { var email = $.body.email; $.success(); } ``` ### $.payload Type: `property` The raw body as a Buffer. Returns: `Buffer` The 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. Example: Example ```js ROUTE('POST /api/xml/', function($) { var xml = $.payload.toString('utf8'); $.plain('Received ' + xml.length + ' chars'); }); ``` ### $.files Type: `property` The uploaded files. Returns: `HttpFile[]` An 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)`. Example: Example ```js function upload($) { var names = []; for (var file of $.files) names.push(file.filename + ' (' + file.size + ' bytes)'); $.json(names); } ``` ### $.headers Type: `property` The request headers. Returns: `Object` The headers object of Node.js: names are in lower case. Example: Example ```js function info($) { $.json({ agent: $.headers['user-agent'], lang: $.headers['accept-language'] }); } ``` ### $.ip Type: `property` The IP address of the client. Returns: `String` The first address of `X-Forwarded-For` when the header exists (behind a proxy), otherwise the remote address of the connection. Example: Example ```js function track($) { console.log('Request from', $.ip); $.success(); } ``` ### $.ua Type: `property` A short name of the client from the User-Agent header. Returns: `String` The system and the browser found in `User-Agent`, for example `Mac OS Chrome`, or an empty string without the header. ### $.mobile Type: `property` `true` for a mobile device. Returns: `Boolean` `true` when `User-Agent` matches a phone or a tablet (Android, iPhone, iPad, Mobile, Tablet...). ### $.robot Type: `property` `true` for a crawler. Returns: `Boolean` `true` when `User-Agent` contains `search`, `agent`, `bot`, `crawler` or `spider`. ### $.xhr Type: `property` `true` for an XMLHttpRequest. Returns: `Boolean` `true` when the request has the header `X-Requested-With: XMLHttpRequest`. `$.fallback()` answers such requests with JSON instead of an HTML page. ### $.protocol Type: `property` The protocol of the request. Returns: `String` `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`. ### $.address Type: `property` The full URL of the request. Returns: `String` The protocol, the host and the original URL with the query string, for example `https://example.com/products/?page=2`. ### $.user Type: `property` The signed-in user. Returns: `Object` The object your authorization delegate returned for the request, or `undefined` when nobody is signed in. See [Authorization](../../guides/authorization/). Example: Example ```js ROUTE('+GET /api/account/', function($) { $.json({ name: $.user.name }); }); ``` ### $.language Type: `property` The language of the request. Returns: `String` The value your localization delegate returned, or an empty string. It selects the translation of views and of error messages. See [Localization](../../guides/localization/). ### $.response Type: `property` The response that will be sent. Returns: `Object` An 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. Example: Status and a header ```js function create($) { $.response.status = 201; $.response.headers['x-version'] = '1'; $.json({ id: UID() }); } ``` ### $.json(value, [beautify], [replacer]) Type: `method` Sends JSON. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `value` | `Object` | yes | | The value to serialize. | | `beautify` | `Boolean` | no | `false` | `true` indents the JSON with tabs. | | `replacer` | `Function|Array` | no | | A replacer for `JSON.stringify()`. | 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`). `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. Example: Example ```js ROUTE('GET /api/products/', function($) { $.json([{ id: 1, name: 'Shoes' }]); }); ``` Example: Beautify and hide a key ```js ROUTE('GET /api/debug/', function($) { $.json({ id: 1, password: 'secret' }, true, function(key, value) { return key === 'password' ? undefined : value; }); }); ``` ### $.jsonstring(value) Type: `method` Sends a string that is already JSON. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `value` | `String` | yes | | A JSON string. | Sends the string as it is with the same headers as `$.json()`. Use it for JSON you have cached or read from a file. Example: Example ```js function cached($) { $.jsonstring('{"ok":true}'); } ``` ### $.success([value]) Type: `method` Sends `{ success: true, value: value }`. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `value` | `Object` | no | | An optional value for the `value` key. | A shortcut for the usual answer of an API. Without `value` the response is `{"success":true}`. Example: Example ```js function remove($) { NOSQL('products').remove().id($.params.id); $.success($.params.id); } ``` ### $.invalid(error) Type: `method` Sends an error as JSON. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `error` | `String|Error|ErrorBuilder|Number` | yes | | The error. | Accepts 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. Example: Example ```js function save($) { if (!$.body.email) { $.invalid('@(Email is required)'); return; } $.success(); } ``` ### $.invalidsafe(message, [error]) Type: `method` Sends an error message and logs the real error. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `message` | `String|Number|ErrorBuilder` | yes | | The error for the client. | | `error` | `Error|String` | no | | The error for the log. | Sends `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`. Example: Example ```js function report($) { F.Fs.readFile(PATH.root('reports/2025.csv'), function(err, buffer) { if (err) $.invalidsafe('The report is not available', err); else $.content(buffer, 'text/csv'); }); } ``` ### $.html(value) Type: `method` Sends HTML. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `value` | `String` | yes | | HTML. | Sets `content-type: text/html` and sends the string. It is minified when the configuration key `$minifyhtml` is `true` (the default). Example: Example ```js ROUTE('GET /hello/', function($) { $.html('<h1>Hello</h1>'); }); ``` ### $.throw(error) Type: `method` Writes an error to the log. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `error` | `Error|String` | yes | | The error. | Returns: `Controller` The same controller. Passes `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 `$`. Example: Example ```js function save($) { NOSQL('visits').insert({ url: $.url, dtcreated: NOW }).callback(function(err) { err && $.throw(err); }); $.success(); } ``` ### $.plain(value) Type: `method` Sends plain text. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `value` | `String` | yes | | The text. | Sets `content-type: text/plain`. `$.text()` is the same method. Example: Example ```js ROUTE('FILE /robots.txt', function($) { $.plain('User-agent: *'); }); ``` ### $.xml(value) Type: `method` Sends XML. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `value` | `String` | yes | | XML. | Sets `content-type: text/xml` and sends the string. Example: Example ```js function feed($) { $.xml('<?xml version="1.0"?><rss></rss>'); } ``` ### $.empty() Type: `method` Sends status 204 without a body. Use it when a request needs no data in the answer. Example: Example ```js ROUTE('POST /api/ping/', function($) { $.empty(); }); ``` ### $.redirect(url, [permanent]) Type: `method` Redirects the client. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `url` | `String` | yes | | The target URL. | | `permanent` | `Boolean` | no | `false` | `true` for a permanent redirect (301). | Sets the `Location` header and the status `302`, or `301` when `permanent` is `true`. Example: Example ```js ROUTE('GET /old/', function($) { $.redirect('/new/', true); }); ``` ### $.view([name], [model]) Type: `method` Renders a view and sends it as HTML. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `name` | `String` | no | | The name of the view, without the extension. | | `model` | `Object` | no | | The model for the view. | Returns: `View` The view instance. Renders 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/). Example: Example ```js function detail($) { NOSQL('products').one().id($.params.id).callback(function(err, response) { if (response) $.view('detail', response); else $.fallback(404); }); } ``` ### $.layout(name) Type: `method` Chooses the layout for the next view. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `name` | `String` | yes | | The name of the layout view. | The view rendered with `$.view()` is placed into the layout `name`. Example: Example ```js function admin($) { $.layout('layout-admin'); $.view('dashboard'); } ``` ### $.file(path, [download]) Type: `method` Sends a file from the disk. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `path` | `String` | yes | | An absolute path of the file. | | `download` | `Boolean|String` | no | | A file name for the download, or `true`. | Sets 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`. Example: Example ```js ROUTE('GET /download/', function($) { $.file(PATH.root('reports/2025.pdf'), 'report.pdf'); }); ``` ### $.stream(type, stream, [download]) Type: `method` Sends a readable stream. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `type` | `String` | yes | | The content type. | | `stream` | `ReadableStream` | yes | | The stream. | | `download` | `String` | no | | A file name for the download. | Pipes `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. Example: Example ```js function exportcsv($) { var stream = F.Fs.createReadStream(PATH.root('export.csv')); $.stream('text/csv', stream, 'export.csv'); } ``` ### $.binary(buffer, type, [download]) Type: `method` Sends a Buffer. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `buffer` | `Buffer` | yes | | The data. | | `type` | `String` | yes | | The content type. | | `download` | `String` | no | | A file name for the download. | Sends the bytes with the content type `type`. A string `download` sends them as an attachment with that name. Example: Example ```js function pixel($) { var buffer = Buffer.from('R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7', 'base64'); $.binary(buffer, 'image/gif'); } ``` ### $.content(value, [type]) Type: `method` Sends a string or a Buffer with a content type. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `value` | `String|Buffer` | yes | | The content. | | `type` | `String` | no | `'application/octet-stream'` | The content type. | Sends `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. Example: CSV ```js ROUTE('GET /export/', function($) { $.content('id,name\n1,Mug\n', 'text/csv'); }); ``` ### $.image(opt) Type: `method` Processes an image and sends it. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `opt` | `Object` | yes | | The options. | Loads 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. Example: Example ```js function thumbnail($) { $.image({ ext: 'jpg', cache: 'thumb_' + $.params.id, load: function(next) { next(F.Fs.createReadStream(PATH.public('photos/' + $.params.id + '.jpg'))); }, image: function(img) { img.resize(200, 200); } }); } ``` ### $.filefs(name, id, [download], [checkmeta]) Type: `method` Sends a file from a file storage. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `name` | `String` | yes | | The name of the file storage. | | `id` | `String` | yes | | The identifier of the file. | | `download` | `Boolean|String` | no | | Send as an attachment. | | `checkmeta` | `Function` | no | | A check of the metadata. | Returns: `Object` The options passed to the storage. Sends 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. Example: Example ```js ROUTE('GET /files/{id}/', function($) { $.filefs('files', $.params.id); }); ``` ### $.proxy(opt) Type: `method` Forwards the request to another server. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `opt` | `String|Object` | yes | | The target URL or options. | Sends 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. Example: Example ```js ROUTE('GET /api/weather/', function($) { $.proxy('https://weather.example.com/today/'); }); ``` ### $.fallback(code, [error]) Type: `method` Sends an error page. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `code` | `Number` | yes | | The HTTP status code. | | `error` | `String|Error` | no | | The error for debug mode. | When 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. Example: Example ```js exports.install = function() { ROUTE('GET /secret/', function($) { $.fallback(404); }); ROUTE('#404', function($) { $.view('404'); }); }; ``` ### $.callback([err], [value]) Type: `method` Answers from a callback. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `err` | `Error` | no | | An error. | | `value` | `Object` | no | | The value to send. | Returns: `Function` A callback when called without arguments. Without 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)`. Example: Example ```js ROUTE('GET /api/products/', function($) { NOSQL('products').find().callback($.callback()); }); ``` ### $.done([value]) Type: `method` Returns a callback that answers with success. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `value` | `Object|Boolean` | no | | The value, or `true` for the response of the callback. | Returns: `Function` A callback. The 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. Example: Example ```js ROUTE('POST /api/products/', function($) { NOSQL('products').insert($.body).callback($.done(true)); }); ``` ### $.successful(callback) Type: `method` Returns a callback that handles errors for you. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `callback` | `Function` | yes | | Called when there is no error. | Returns: `Function` A callback. The returned function `(err, a, b, c)` calls `$.invalid(err)` on an error, otherwise `callback(a, b, c)` with the controller as `this`. Example: Example ```js ROUTE('GET /api/products/', function($) { NOSQL('products').find().callback($.successful(function(response) { $.json(response); })); }); ``` ### $.custom() Type: `method` Tells the framework you send the response yourself. Marks the controller as finished so that no response method writes to it. Then write to `$.res` with the Node.js API. Example: Example ```js ROUTE('GET /events/', function($) { $.custom(); $.res.writeHead(200, { 'content-type': 'text/event-stream' }); $.res.write('data: hello\n\n'); }); ``` ### $.cookie(name, [value], [expires], [options]) Type: `method` Reads or sets a cookie. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `name` | `String` | yes | | The name of the cookie. | | `value` | `String` | no | | The value to set. | | `expires` | `Date|String|Object` | no | | The expiration, or the options. | | `options` | `Object` | no | | The options of the cookie. | Returns: `String|Controller` The value when reading, the controller when setting. With 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'`). Example: Example ```js function login($) { $.cookie('session', 'abc123', '7 days', { httponly: true, samesite: 'Strict' }); $.success(); } function profile($) { $.json({ session: $.cookie('session') }); } ``` ### $.httpcache(date) Type: `method` Sets the HTTP cache headers. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `date` | `Date|String` | yes | | The date of the last change. | Sets `Last-Modified` to `date`, `ETag`, and `Expires` and `Cache-Control` when they are not set yet. Example: Example ```js function article($) { var updated = new Date(2025, 0, 1); if ($.notmodified(updated.toUTCString())) return; $.httpcache(updated); $.view('article'); } ``` ### $.notmodified(date) Type: `method` Answers 304 when the client has the same version. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `date` | `String` | yes | | The date of the last change as a UTC string. | Returns: `Boolean` `true` when the 304 response was sent. Compares `date` (a UTC string) with the `If-Modified-Since` header. When they are equal it sends `304 Not Modified` and returns `true`. ### $.hostname([path]) Type: `method` Returns the protocol and the host. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `path` | `String` | no | | A path to append. | Returns: `String` The URL. Gives `protocol://host` of the request with an optional path appended. Example: Example ```js function share($) { $.json({ url: $.hostname('/products/' + $.params.id + '/') }); } ``` ### $.href([key], [value]) Type: `method` Returns the query string with one parameter changed. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `key` | `String|Object` | no | | The name of the parameter, or an object with the parameters to set. | | `value` | `String|Number|Array|Object` | no | | The new value. | Returns: `String` The query string with `?`, or an empty string. Without 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. Example: Paging ```js // GET /products/?page=2&sort=name function products($) { $.json({ next: $.href('page', 3), // ?page=3&sort=name current: $.href() // ?page=2&sort=name }); } ``` Example: Remove a parameter, or change several ```js // GET /products/?page=2&sort=name&q=pen $.href('page', 1, 'sort'); // ?page=1&q=pen $.href({ page: 1, sort: 'price' }); // /products/?page=1&sort=price&q=pen ``` ### $.touch([url]) Type: `method` Clears the cached state of a static file. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `url` | `String` | no | `$.url` | The URL of the file. | Returns: `Controller` The same controller. Calls `TOUCH(url)`; without `url` it uses the URL of the request. Use it after the route changes a file in `public/`. Returns `$`. Example: Example ```js ROUTE('POST /api/theme/', function($) { F.Fs.writeFile(PATH.public('css/theme.css'), $.body.css || '', function(err) { if (err) { $.invalidsafe('The theme can\'t be saved', err); return; } $.touch('/css/theme.css'); $.success(); }); }); ``` ### $.action(name, model) Type: `method` Runs an action with this controller. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `name` | `String` | yes | | The name of the action, for example `Products/list`. | | `model` | `Object` | yes | | The data for the action. | Returns: `Object` The action instance. Calls 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. Example: Example ```js ROUTE('POST /api/orders/', function($) { $.action('Orders/create', $.body).autorespond(); }); ``` ### $.authorize([callback]) Type: `method` Runs the authorization delegate manually. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `callback` | `Function` | no | | Receives `(err, user)`. | Returns: `Promise` When called without a callback. Calls 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`). Example: Example ```js ROUTE('GET /api/me/', async function($) { var user = await $.authorize(); $.json({ signed: !!user }); }); ``` ### $.csrf() Type: `method` Creates a CSRF token. Returns: `String` The token. Returns 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. Example: Example ```js ROUTE('GET /form/', function($) { $.view('form', { token: $.csrf() }); }); ``` ### $.autoclear([value]) Type: `method` Keeps or removes uploaded files after the response. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `value` | `Boolean` | no | | `false` keeps the files. | Uploaded files are removed when the response ends. `$.autoclear(false)` keeps them, for example when you process them later. ### $.cancel() Type: `method` Stops the processing of the request in an event. Call it in `ON('request', fn)` or `ON('controller', fn)` when the handler answers the request itself. Example: Example ```js ON('request', function($) { if ($.url === '/health/') { $.cancel(); $.plain('OK'); } }); ``` ### HttpFile Type: `class` An uploaded file in `$.files`. Properties: `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`. Methods: - `move(filename, [callback])` (also `rename()`) moves the file; without a callback it returns a `Promise`. A moved file is not removed after the response. - `copy(filename, callback)` copies the file. - `read([callback])` reads the file into a `Buffer`; without a callback it returns a `Promise`. - `md5([callback])` computes the MD5 hash in hex; without a callback it returns a `Promise`. - `stream([opt])` returns a read stream; `pipe(stream, [opt])` pipes the file into a stream. - `image([shell])` returns an image object for [Images](../../guides/images/). - `fs(storage, id, [callback])` saves the file into a [file storage](../../guides/file-storage/). Example: Save to a file storage ```js ROUTE('POST /upload/ <10MB', function($) { var file = $.files[0]; file.fs('files', UID(), function(err, meta) { if (err) $.invalid(err); else $.success(meta.id); }); }); ``` --- title: Actions project: Total.js V5 version: 0.0.20 section: reference language: en license: MIT url: https://totaljs.es/docs/total-js-v5/0-0-20/reference/actions/ updated: 2026-11-18T16:57:24.576Z --- # Actions > NEWACTION() options, the $ object, ACTION() callers, NEWSCHEMA() and transformations. The 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()`. For 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/). ## API ### NEWACTION(name, options) Type: `method` Declares an action. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `name` | `String` | yes | | Name of the action, e.g. `products_create` | | `options` | `Object` | yes | | The definition: `action`, `input`, `output`, `params`, `query`, `user`, `permissions`, `route` and the other options | Returns: `Object` The definition of the action Registers 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`. Example: A complete action ```js NEWACTION('products_update', { name: 'Update a product', params: '*id:UID', input: '*name:String, price:Number', permissions: 'products', route: '+PUT /api/products/{id}/', action: function($, model) { DATA.modify('products', model).id($.params.id).error(404).callback($.done($.params.id)); } }); ``` Example: Remove an action ```js var action = NEWACTION('temp_test', { action: $ => $.success() }); action.remove(); ``` ### ACTION(name, [payload], [controller]) Type: `method` Runs one or more actions from code. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `name` | `String` | yes | | Action name, or names separated by spaces; a `+` or `-` prefix says whether the action uses the payload | | `payload` | `Object` | no | | The data validated by the `input` option | | `controller` | `Controller` | no | | A controller of an HTTP request | Returns: `ActionCaller` The caller with `callback()`, `promise()`, `user()` and the other methods Returns 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. Example: Callback ```js ACTION('products_list').query({ search: 'mouse' }).callback(function(err, response) { console.log(err, response); }); ``` Example: Several actions ```js ACTION('orders_create orders_notify (response)', model).user(user).callback(function(err, response) { // response is the response of orders_notify }); ``` ### EXEC(name, [payload], [controller]) Type: `method` An alias of `ACTION()`. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `name` | `String` | yes | | Action name or names | | `payload` | `Object` | no | | The payload | | `controller` | `Controller` | no | | A controller | Returns: `ActionCaller` The caller The same function as `ACTION()`. Example: Promise ```js var response = await EXEC('products_create', { name: 'Mouse' }).user(user).promise(); ``` ### NEWSCHEMA(name, callback) Type: `method` Groups actions under a common name. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `name` | `String` | yes | | Name of the schema | | `callback` | `Function|String` | yes | | `function(schema)`, or an inline schema definition | Returns: `Object` Nothing for a callback; the JSON schema for a string Calls `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. Example: Actions of a schema ```js NEWSCHEMA('Users', function(schema) { schema.action('read', { params: '*id:UID', action: function($) { DATA.read('users').id($.params.id).error(404).callback($); } }); }); ACTION('Users/read').params({ id: 'Jae9QB1c461f' }).callback(console.log); ``` Example: A JSON schema ```js NEWSCHEMA('Address', '*street:String, *city:String, zip:Zip'); ``` ### NEWTRANSFORM(name, fn, [id]) Type: `method` Adds a function to a named transformation. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `name` | `String` | yes | | Name of the transformation | | `fn` | `Function` | yes | | `function($, value)` | | `id` | `String` | no | | An identifier for removing the function later | Returns: `Object` An object with `id`, `action` and `remove()` Functions 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`. Example: Add and remove ```js NEWTRANSFORM('user', function($, value) { delete value.password; $.next(); }, 'password'); NEWTRANSFORM('user', null, 'password'); ``` ### TRANSFORM(name, value, [callback], [controller]) Type: `method` Runs a named transformation. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `name` | `String` | yes | | Name of the transformation | | `value` | `Object` | yes | | The value to transform | | `callback` | `Function` | no | | `function(err, value)` | | `controller` | `Controller` | no | | A controller; its user is `$.user` in the functions | Returns: `Promise` A Promise when there is no callback Runs 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. Example: Callback ```js TRANSFORM('user', user, function(err, value) { console.log(value); }); ``` Example: Promise ```js var value = await TRANSFORM('user', user); ``` Example: Errors of the Promise form ```js try { var value = await TRANSFORM('user', user); } catch (err) { console.log(err.toString()); // the errors of $.invalid() } ``` ### ON('@' + name, function($, response) {}) Type: `event` Emitted after an action responds successfully. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `$` | `Options` | yes | | The `$` of the action | | `response` | `Object` | yes | | The response of the action | The 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. Example: Notification ```js ON('@orders_create', function($, response) { console.log('New order', response.value, 'by', $.user.id); }); ``` ### action: Function Type: `config` The logic of the action. Returns: `Function` `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. Example: Basic ```js NEWACTION('ping', { action: function($) { $.success(NOW); } }); ``` ### input: String|Object Type: `config` Schema of the payload. Returns: `String|Object` An 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/). Example: Inline schema ```js NEWACTION('contact_send', { input: '*name:String, *email:Email, message:String', action: function($, model) { $.success(); } }); ``` ### output: String|Object Type: `config` Schema of the response. Returns: `String|Object` The 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. Example: Hide fields ```js NEWACTION('users_read', { params: '*id:UID', output: 'id:UID, name:String, email:Email', action: function($) { DATA.read('users').id($.params.id).callback($); } }); ``` ### params: String|Object Type: `config` Schema of the URL parameters. Returns: `String|Object` Validates `$.params`, the dynamic parts of the route (`{id}`). Errors have the prefix `params.`. Example: Parameter ```js NEWACTION('products_remove', { params: '*id:UID', route: '+DELETE /api/products/{id}/', action: function($) { DATA.remove('products').id($.params.id).callback($.done()); } }); ``` ### query: String|Object Type: `config` Schema of the query string. Returns: `String|Object` Validates `$.query`. Errors have the prefix `query.`. Example: Query ```js NEWACTION('products_search', { query: '*q:String, page:Number', route: 'GET /api/products/search/', action: function($) { DATA.find('products').search('name', $.query.q).callback($); } }); ``` ### user: Boolean Type: `config` Requires a signed-in or an anonymous user. Returns: `Boolean` `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. Example: Signed-in user ```js NEWACTION('account_read', { user: true, action: function($) { $.success($.user); } }); ``` ### permissions: String|Array Type: `config` Required permissions. Returns: `String|Array` A 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. Example: Permissions ```js NEWACTION('invoices_remove', { permissions: 'invoices_remove,admin', params: '*id:UID', action: function($) { DATA.remove('invoices').id($.params.id).callback($.done()); } }); ``` ### route: String Type: `config` A route that runs the action. Returns: `String` A 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. `route: true` creates an `API ?` endpoint named after the action (`+API ?` when the action has the `user` or `permissions` option). Example: Route ```js NEWACTION('products_create', { input: '*name:String', route: '+POST /api/products/', action: function($, model) { $.success(); } }); ``` Example: API endpoint ```js NEWACTION('products_list', { route: '+API ?', action: function($) { DATA.find('products').callback($); } }); ``` ### middleware: String Type: `config` Middleware to run before the action. Returns: `String` Names 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/). Example: Middleware ```js NEWACTION('reports_build', { middleware: 'ratelimit', action: function($) { $.success(); } }); ``` ### partial: Boolean Type: `config` Validates the input partially. Returns: `Boolean` With `true`, `input` validates only the fields present in the payload and does not check required fields. Useful for `PATCH` updates. Example: Patch ```js NEWACTION('products_patch', { params: '*id:UID', input: '*name:String, *price:Number', partial: true, action: function($, model) { DATA.modify('products', model).id($.params.id).callback($.done()); } }); ``` ### extend: String Type: `config` Adds the response to the payload. Returns: `String` The 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. Example: Extend ```js NEWACTION('order_totals', { extend: 'totals', action: function($, model) { $.callback({ count: 3, price: 120 }); } }); // response: { ...payload, totals: { count: 3, price: 120 } } ``` ### audit: Boolean|String Type: `config` Writes an audit record after success. Returns: `Boolean|String` `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`). Example: Audit message ```js NEWACTION('products_create', { input: '*name:String', audit: '{{ $.user.name }} created {{ $.model.name }}', action: function($, model) { $.success(); } }); ``` ### config: Object Type: `config` Custom configuration of the action. Returns: `Object` Any object; it is available as `$.config` in the action, so one function can serve several actions. Example: Shared logic ```js function list($) { DATA.find($.config.table).callback($); } NEWACTION('products_list', { config: { table: 'products' }, action: list }); NEWACTION('orders_list', { config: { table: 'orders' }, action: list }); ``` ### timeout: Number Type: `config` · Since: `0.0.16` A time limit of the action. Returns: `Number` In milliseconds. When the action does not respond in time, it fails with the error `Timeout.`; a later response is ignored. Example: Timeout ```js NEWACTION('reports_export', { timeout: 10000, action: function($) { setTimeout(() => $.success(), 2000); } }); ``` ### cache: true | { query, params, input, user, language, key, expire } Type: `config` Keeps the response of the action in the cache. Returns: `Boolean|Object` The 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. With `true` the action has one cached response. An object makes one entry for each combination of values: | Key | Value | | --- | --- | | `query`, `params`, `input` | `true` (all fields of the schema of the action) or a comma-separated list of fields | | `user` | `true` (`$.user.id`) or a comma-separated list of keys of `$.user` | | `language` | `true`: one entry for each `$.language` | | `key` | A name for the entries; `CACHE.reset('action|' + key + '|')` removes them | | `expire` | How long an entry is kept, default `'5 minutes'` | Without `user`, all users share the same cached response. Example: A list cached per page ```js NEWACTION('Products|list', { query: 'page:Number,category:String', cache: { query: true, key: 'products', expire: '10 minutes' }, action: function($) { DATA.list('products').where('category', $.query.category).page($.query.page, 20).callback($); } }); // after a product is saved CACHE.reset('action|products|'); ``` Example: One entry per user ```js NEWACTION('Account|profile', { user: true, cache: { user: true, expire: '1 minute' }, action: function($) { DATA.read('users').id($.user.id).callback($); } }); ``` ### summary: String Type: `config` A description of the action. Returns: `String` Free 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. Example: Summary ```js NEWACTION('tasks_create', { summary: 'Creates a task and returns its ID', input: '*name:String', action: function($, model) { $.success(UID()); } }); ``` ### oninput: Function Type: `config` · Since: `0.0.19` Called right before the action. Returns: `Function` `function($)`. It runs after validation and middleware, so `$.model`, `$.params` and `$.query` are ready and you can change them. Example: Prepare data ```js NEWACTION('notes_create', { input: '*body:String', oninput: function($) { $.model.body = $.model.body.trim(); }, action: function($, model) { $.success(); } }); ``` ### mcp: Boolean Type: `config` Makes the action a tool of the MCP server. Returns: `Boolean` With `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/). Example: A tool ```js NEWACTION('tasks_list', { summary: 'Lists the tasks', mcp: true, action: function($) { NOSQL('tasks').find().callback($); } }); ``` ### onoutput: Function Type: `config` · Since: `0.0.19` Called after the action responds. Returns: `Function` `function(err, response, $)`. It runs after a successful response has been delivered, so `err` is `null`; it is not called when the action fails. Example: Log ```js NEWACTION('orders_create', { input: '*productid:UID', onoutput: function(err, response, $) { console.log($.id, $.user ? $.user.id : '', response); }, action: function($, model) { $.success(UID()); } }); ``` ### $.model Type: `property` The validated payload. Returns: `Object` The 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`. Example: Model ```js action: function($) { var name = $.model.name; $.success(name); } ``` ### $.input Type: `property` · Since: `0.0.19` Another name of `$.model`. Returns: `Object` Reads and assigns the same value as `$.model`. Example: Input ```js oninput: function($) { $.input.email = $.input.email.toLowerCase(); } ``` ### $.params Type: `property` The URL parameters. Returns: `Object` Validated by the `params` option. In an HTTP request it contains the dynamic parts of the route; from code it is set with `ACTION().params()`. Example: Params ```js action: function($) { DATA.read('products').id($.params.id).callback($); } ``` ### $.query Type: `property` The query string. Returns: `Object` Validated by the `query` option. From code it is set with `ACTION().query()`. Example: Query ```js action: function($) { var page = $.query.page || 1; $.success(page); } ``` ### $.user Type: `property` The current user. Returns: `Object` The user of the HTTP request (see [Authorization](../../guides/authorization/)), or the user set with `ACTION().user()`. Empty for anonymous calls. Example: User ```js action: function($) { $.success($.user.name); } ``` ### $.config Type: `property` The `config` option of the action. Returns: `Object` An empty object when the action has no `config`. Example: Config ```js action: function($) { $.success($.config.table); } ``` ### $.id Type: `property` The name of the running action. Returns: `String` In a chain of actions, the name of the current one. Example: Name ```js action: function($) { console.log('Running', $.id); $.success(); } ``` ### $.controller Type: `property` The controller of the HTTP request. Returns: `Controller` `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. Example: Controller ```js action: function($) { $.success($.controller ? $.controller.url : 'code'); } ``` ### $.error Type: `property` The errors of the call. Returns: `ErrorBuilder` An `ErrorBuilder`. `$.invalid()` adds to it; `$.error.length` is the number of errors. Example: Errors ```js action: function($) { if (!$.model.items.length) { $.invalid('No items', 'items'); return; } $.success(); } ``` ### $.response Type: `property` The responses of the actions in a chain. Returns: `Object` An 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. Example: Previous response ```js NEWACTION('orders_notify', { action: function($) { var created = $.response.orders_create; $.success(created); } }); ``` ### $.xhr Type: `property` · Since: `0.0.19` Whether the request is an XHR request. Returns: `Boolean` `true` when the HTTP request has the `X-Requested-With: XMLHttpRequest` header; `null` without a controller. Example: XHR ```js action: function($) { if ($.xhr) $.success(); else $.redirect('/'); } ``` ### $.meta Type: `property` · Since: `0.0.19` The definition of the action. Returns: `Object` The object passed to `NEWACTION()`, with all its options. Example: Meta ```js action: function($) { $.success($.meta.name); } ``` ### $.env Type: `property` The environment of the call. Returns: `Any` The 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. Example: Environment ```js NEWACTION('orders_sync', { action: function($) { if ($.env === 'test') { $.success(); return; } $.success('synced'); } }); ACTION('orders_sync').env('test').callback(console.log); ``` ### $.ip Type: `property` Request data shortcuts. Returns: `String` `$.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). Example: IP and agent ```js action: function($) { $.success({ ip: $.ip, ua: $.ua }); } ``` ### $.success([value]) Type: `method` Ends the action with a success object. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `value` | `Object` | no | | A value for the `value` property | Responds with `{ success: true, value: value }` (the shape comes from `DEF.onSuccess`). Without a value, `value` is `undefined`. Example: Success ```js action: function($) { $.success(UID()); } ``` ### $.invalid(error, [path], [index]) Type: `method` Ends the action with an error. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `error` | `String|Number|Error` | yes | | The error, or an HTTP status code | | `path` | `String` | no | | The field the error belongs to | | `index` | `Number` | no | | The index of the item in an array | Returns: `ErrorBuilder` The errors Adds 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`. Example: Not found ```js action: function($) { DATA.read('products').id($.params.id).callback(function(err, response) { if (response) $.callback(response); else $.invalid(404); }); } ``` ### $.callback([value]) Type: `method` Ends the action with a value as it is. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `value` | `Object` | no | | The response | Returns: `Function` A callback when called without arguments Responds 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()`. Example: Value ```js action: function($) { $.callback({ count: 5 }); } ``` Example: Callback of a query ```js action: function($) { DATA.find('products').callback($.callback()); } ``` ### $.done([value]) Type: `method` Returns a callback that ends the action. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `value` | `Object|Boolean` | no | | The value of the success object, or `true` for the response | Returns: `Function` `function(err, response)` Returns `function(err, response)`. An error ends the action with the error; otherwise it calls `$.success(value)`, or `$.success(response)` when `value` is `true`. Example: Done ```js action: function($, model) { model.id = UID(); DATA.insert('products', model).callback($.done(model.id)); } ``` ### $.promisify(fn, [a], [b], [c]) Type: `method` Calls a callback function as a Promise. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `fn` | `Function` | yes | | A function whose last argument is `function(err, response)` | | `a` | `Object` | no | | First argument | | `b` | `Object` | no | | Second argument | | `c` | `Object` | no | | Third argument | Returns: `Promise` The response Calls `fn(a, b, c, callback)` and resolves with the response. An error ends the action with `$.invalid()` and the Promise never resolves. Example: Promisify ```js action: async function($) { var files = await $.promisify(F.Fs.readdir, PATH.public()); $.success(files); } ``` ### $.action(name, [payload]) Type: `method` Runs another action from an action. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `name` | `String` | yes | | Action name or names | | `payload` | `Object` | no | | The payload | Returns: `ActionCaller` The caller Same as `ACTION()` with the controller of this action. Without a controller, the new call gets the user, query and params of this one. Example: Nested action ```js action: async function($, model) { var response = await $.action('stock_check', model).promise($); $.success(response); } ``` ### $.transform(name, value, [callback]) Type: `method` Runs a transformation with the controller of the action. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `name` | `String` | yes | | Name of the transformation | | `value` | `Object` | yes | | The value | | `callback` | `Function` | no | | `function(err, value)` | Returns: `Promise` A Promise without a callback Same as `TRANSFORM()`, with the controller (and its user) of the action. Without a callback it returns a Promise. Example: Transform ```js action: async function($) { var user = await DATA.read('users').id($.params.id).promise($); $.callback(await $.transform('user', user)); } ``` ### $.unauthorized(permission, [permission2], [...]) Type: `method` Checks permissions of the user. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `permission` | `String` | yes | | A permission name; more can follow | Returns: `Boolean` `true` when the user is not allowed Returns `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. Example: Check ```js action: function($) { if ($.unauthorized('reports')) return; $.success(); } ``` ### $.redirect(url) Type: `method` Redirects the HTTP request. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `url` | `String` | yes | | The target URL | Redirects the controller to `url` and cancels the action; the caller gets no response. Example: Redirect ```js action: function($) { $.redirect('/login/'); } ``` ### $.invalidsafe(message, [error]) Type: `method` Ends the action with a message and logs the real error. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `message` | `String|Number` | yes | | The error for the caller, or an HTTP status code | | `error` | `Error|String` | no | | The error for the log | Returns: `ErrorBuilder` The errors Adds `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`. Example: Hide the details ```js NEWACTION('orders_invoice', { action: async function($) { try { var template = await F.FsPromises.readFile(PATH.root('templates/invoice.html'), 'utf8'); $.success(template.length); } catch (e) { $.invalidsafe('The invoice can\'t be created', e); } } }); ``` ### ACTION(name).callback(fn) Type: `method` Receives the result of the call. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `fn` | `Function|Options` | yes | | `function(err, response)` or a `$` | Returns: `ActionCaller` The caller, for chaining `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. Example: Callback ```js ACTION('products_list').callback(function(err, response) { console.log(err ? err.toString() : response); }); ``` Example: Pass to another action ```js action: function($) { ACTION('products_list').user($).callback($); } ``` ### $.throw(error) Type: `method` Writes an error to the log. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `error` | `Error|String` | yes | | The error | Returns: `Options` The same `$` Passes `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 `$`. Example: Log and continue ```js NEWACTION('orders_notify', { action: function($) { NOSQL('notifications').insert({ type: 'order', dtcreated: NOW }).callback(function(err) { err && $.throw(err); }); $.success(); } }); ``` ### $.touch([url]) Type: `method` Clears the cached state of a static file. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `url` | `String` | no | `$.url` | The URL of the file | Returns: `Options` The same `$` Calls `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 `$`. Example: After a change ```js NEWACTION('theme_save', { input: '*css:String', action: async function($, model) { await F.FsPromises.writeFile(PATH.public('css/theme.css'), model.css); $.touch('/css/theme.css'); $.success(); } }); ``` ### ACTION(name).promise([$]) Type: `method` Returns a Promise with the result. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `$` | `Options` | no | | The `$` of an action that receives the errors | Returns: `Promise` The response Resolves 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. Example: Await ```js var response = await ACTION('products_list').promise(); ``` ### ACTION(name).user(user) Type: `method` Sets the user of the call. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `user` | `Object|Options` | yes | | A user object, or a `$` | Returns: `ActionCaller` The caller, for chaining Sets `$.user`. When you pass a `$`, its user is used. Example: User ```js ACTION('account_read').user({ id: '123', name: 'Peter' }).callback(console.log); ``` ### ACTION(name).query(obj) Type: `method` Sets the query string of the call. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `obj` | `Object` | yes | | The query | Returns: `ActionCaller` The caller, for chaining Sets the object validated by the `query` option. Example: Query ```js ACTION('products_list').query({ page: 2 }).callback(console.log); ``` ### ACTION(name).params(obj) Type: `method` Sets the URL parameters of the call. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `obj` | `Object` | yes | | The parameters | Returns: `ActionCaller` The caller, for chaining Sets the object validated by the `params` option. Example: Params ```js ACTION('products_read').params({ id: 'Jae9QB1c461f' }).callback(console.log); ``` ### ACTION(name).ctrl(controller) Type: `method` Runs the call with a controller. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `controller` | `Controller` | yes | | A controller | Returns: `ActionCaller` The caller, for chaining The action gets `$.controller` and the request shortcuts. Accepts a controller or an object with a `controller` property (a `$`). Example: Controller ```js function handler($) { ACTION('products_list').ctrl($).autorespond(); } ``` ### ACTION(name).autorespond() Type: `method` Sends the result to the controller. Returns: `ActionCaller` The caller, for chaining On 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. Example: Route handler ```js exports.install = function() { ROUTE('GET /api/products/', function($) { $.action('products_list').autorespond(); }); }; ``` ### ACTION(name).status(fn) Type: `method` Receives status messages from the action. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `fn` | `Function` | yes | | `function(a, b, c, d)` | Returns: `ActionCaller` The caller, for chaining The action sends them with `$.status(a, b, c, d)`; the arguments go to `fn`. Without this method, `$.status()` does nothing. Example: Status ```js NEWACTION('import_run', { action: function($) { $.status('started'); $.success(); } }); ACTION('import_run').status(console.log).callback(console.log); ``` ### ACTION(name).progress(fn) Type: `method` · Since: `0.0.16` Receives progress messages from the action. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `fn` | `Function` | yes | | `function(a, b, c, d)` | Returns: `ActionCaller` The caller, for chaining The action sends them with `$.progress(a, b, c, d)`; the arguments go to `fn` with `$` as `this`. Without this method, `$.progress()` does nothing. Example: Progress ```js NEWACTION('import_run', { action: function($) { for (var i = 1; i <= 10; i++) $.progress(i * 10); $.success(); } }); ACTION('import_run').progress(p => console.log(p + '%')).callback(console.log); ``` ### ACTION(name).config(obj) Type: `method` · Since: `0.0.17` Adds configuration for this call. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `obj` | `Object` | yes | | Keys for `$.config` | Returns: `ActionCaller` The caller, for chaining The 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. Example: Config ```js NEWACTION('report_build', { config: { format: 'pdf' }, action: function($) { $.success($.config); } }); ACTION('report_build').config({ lang: 'en' }).callback(console.log); // { success: true, value: { format: 'pdf', lang: 'en' } } ``` ### ACTION(name).env(value) Type: `method` Sets the environment of the call. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `value` | `Any|Options` | yes | | The environment, such as `'test'`, or a `$` | Returns: `ActionCaller` The caller, for chaining Sets `$.env` in the action. When you pass a `$`, its `env` is used, so an inner call can keep the environment of the outer one. Example: Environment ```js ACTION('orders_sync').env('test').callback(console.log); ``` Example: Pass it on ```js NEWACTION('orders_close', { action: async function($) { await $.action('orders_sync').env($).promise($); $.success(); } }); ``` ### SUCCESS([value]) Type: `method` Creates the success object that actions and controllers respond with. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `value` | `Object` | no | | A value for the `value` property | Returns: `Object` `{ success: true, value: value }` Returns `{ 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. Example: A success response in a controller ```js ROUTE('POST /api/ping/', function($) { $.json(SUCCESS(NOW)); }); ``` --- title: Schemas and validation project: Total.js V5 version: 0.0.20 section: reference language: en license: MIT url: https://totaljs.es/docs/total-js-v5/0-0-20/reference/json-schemas/ updated: 2026-11-18T16:57:24.576Z --- # Schemas and validation > Inline schema types and modifiers, JSON schema keywords, schema methods and ErrorBuilder. The 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/). ## API ### NEWSCHEMA(name, schema) Type: `method` Registers an inline schema under a name. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `name` | `String` | yes | | The name of the schema; a leading `@` is ignored. | | `schema` | `String|Function` | yes | | An inline schema, or a function that defines actions. | Returns: `Object` The JSON schema object when `schema` is a string. With 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`. With 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/). Example: Register and use a schema ```js NEWSCHEMA('@Address', '*street:String,*city:String,zip:Zip'); NEWSCHEMA('@Customer', '*name:String,address:@Address'); NEWACTION('Customers/save', { input: '@Customer', action: function($, model) { $.success(); } }); ``` Example: Actions in a schema ```js NEWSCHEMA('Orders', function(schema) { schema.action('list', { query: 'page:Number', action: function($) { $.callback([]); } }); }); // creates the action "Orders/list" ``` ### '...'.toJSONSchema([name], [url]) Type: `method` Parses an inline schema into a JSON schema object. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `name` | `String` | no | | Stores the schema in `F.jsonschemas` under this name and uses it in `$id`. | | `url` | `String` | no | `CONF.url` | The base URL of `$id`. | Returns: `Object` A JSON schema object. Returns 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]`. The `$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. Example: Parse and validate ```js var schema = '*name:String(50),email:Email,age:Number'.toJSONSchema(); var result = schema.transform({ name: 'Peter', email: 'peter@example.com' }); console.log(result.response); ``` Example: Register under a name ```js '*street:String,*city:String'.toJSONSchema('Address'); // F.jsonschemas.Address exists now ``` ### F.newjsonschema(name, [schema]) Type: `method` Registers a JSON schema or an inline schema. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `name` | `String|Object` | yes | | The name of the schema, an inline schema, or a JSON schema object with `$id`. | | `schema` | `Object|String` | no | | A JSON schema object or an inline schema. | Returns: `Object` The registered schema. The schema is stored in `F.jsonschemas` under the name and under its `$id`, and gets the `transform()` method. The forms: - `F.newjsonschema(object)`: a JSON schema object; its `$id` is the name. - `F.newjsonschema(name, object)`: a JSON schema object under `name`. - `F.newjsonschema(name, 'inline schema')`: an inline schema; `$id` is set to `name`. - `F.newjsonschema('inline schema')`: an inline schema registered under its generated `$id`. The files of the `jsonschemas/` folder are registered with this method. Example: A JSON schema object ```js F.newjsonschema({ $id: 'Product', type: 'object', properties: { name: { type: 'string', maxLength: 100 }, price: { type: 'number', minimum: 1 } }, required: ['name'] }); var result = F.jsonschemas.Product.transform({ name: 'Mug', price: '9.90' }); ``` Example: An inline schema ```js F.newjsonschema('Contact', '*name:String,*email:Email'); ``` ### F.jsonschemas Type: `property` All registered schemas by name. Returns: `Object` An 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. Example: Validate with a registered schema ```js NEWSCHEMA('@Contact', '*name:String,*email:Email'); var result = F.jsonschemas.Contact.transform({ name: 'Peter', email: 'bad' }); if (result.error) console.log(result.error.output()); ``` ### jsonschemas/*.json Type: `config` A folder of schemas loaded when the application starts. Every `.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`. Example: jsonschemas/Address.json ```js { "$id": "Address", "type": "object", "properties": { "street": { "type": "string" }, "city": { "type": "string" }, "zip": { "type": "string", "subtype": "zip" } }, "required": ["street", "city"] } ``` Example: Use it ```js NEWACTION('Addresses/create', { input: '@Address', action: function($, model) { $.success(); } }); ``` ### schema.transform(value, [partial], [error], [path]) Type: `method` Validates and converts a value. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `value` | `Object` | yes | | The value to validate. | | `partial` | `Boolean` | no | `false` | Validates only the fields that exist in the value. | | `error` | `ErrorBuilder` | no | `new ErrorBuilder()` | A builder that receives the errors. | | `path` | `String` | no | | A path prefix for the error paths. | Returns: `Object` `{ error: ErrorBuilder|null, response: Object }` Returns `{ 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. With `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. Example: Validate a body ```js var schema = '*name:String,*email:Email'.toJSONSchema(); var result = schema.transform({ name: 'Peter', email: 'wrong' }); if (result.error) console.log(result.error.output()); // [{ name: 'email', error: 'The field "email" is invalid', path: 'email' }] else console.log(result.response); ``` Example: Partial update ```js var schema = '*name:String,*email:Email,age:Number'.toJSONSchema(); var result = schema.transform({ age: 40 }, true); // result.response === { age: 40 }, result.error === null ``` ### schema.validate(value, [partial], [path]) Type: `method` Validates a value and throws on the first error. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `value` | `Object` | yes | | The value to validate. | | `partial` | `Boolean` | no | `false` | Validates only the fields that exist in the value. | | `path` | `String` | no | | A path prefix for the error paths. | Returns: `Object` The converted value. Returns 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. Example: Throw on invalid data ```js var schema = '*name:String,*email:Email'.toJSONSchema(); try { var model = schema.validate({ name: 'Peter' }); } catch (e) { console.log(e.message); // The field "email" is invalid } ``` ### schema.toAITool(name) Type: `method` Creates an AI tool definition from an inline schema. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `name` | `String` | yes | | The name of the tool. | Returns: `Object` The tool definition. Returns 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/). Example: A tool from a schema ```js var schema = '*city:String // The name of the city,days:Number // Number of days'.toJSONSchema(); schema.description = 'Returns the weather forecast'; var tool = schema.toAITool('weather'); // { // type: 'function', // function: { // name: 'weather', // description: 'Returns the weather forecast', // parameters: { // type: 'object', // properties: { // city: { type: 'string', description: 'The name of the city' }, // days: { type: 'number', description: 'Number of days' } // }, // required: ['city'], // additionalProperties: false // } // } // } ``` ### schema.toAIObject(name, [description]) Type: `method` Converts an inline schema into a named JSON Schema object for AI models. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `name` | `String` | yes | | The name of the object. | | `description` | `String` | no | | A description of the object. | Returns: `Object` The JSON Schema object. Returns `{ 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. Example: A structured answer ```js var schema = '*city:String // The name of the city,days:Number // Number of days'.toJSONSchema(); var obj = schema.toAIObject('forecast', 'The weather forecast for a city'); // { // name: 'forecast', // description: 'The weather forecast for a city', // properties: { // city: { type: 'string', description: 'The name of the city' }, // days: { type: 'number', description: 'Number of days' } // }, // type: 'object', // additionalProperties: false, // required: ['city'] // } ``` ### *name:Type or !name:Type Type: `type` Marks a field of an inline schema as required. A 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 `*`. Example: Required fields ```js var schema = '*name:String,*email:Email,phone:Phone'.toJSONSchema(); var result = schema.transform({ name: '' }); // errors for "name" and "email" ``` ### name:Type // Message Type: `type` Sets a custom error message for a field of an inline schema. The 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`. Example: Custom messages ```js var schema = `*name:String // Enter your name *email:Email // Enter a valid email address`.toJSONSchema(); var result = schema.transform({ email: 'x' }); console.log(result.error.output()); // [{ name: 'name', error: 'Enter your name', ... }, { name: 'email', error: 'Enter a valid email address', ... }] ``` ### name:String name:String(max) name:Text name:String2 Type: `type` Text values. Any 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`. Example: Strings ```js var schema = '*title:String(100),note:Text,code:String2'.toJSONSchema(); schema.transform({ title: ' Hello ', code: '' }).response; // { title: 'Hello', note: '', code: null } ``` ### name:Number (Number2, Int, Integer, Float, Decimal) Type: `type` Numeric values. A 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. Example: Numbers ```js var schema = 'price:Number,count:Int'.toJSONSchema(); schema.transform({ price: '9,90', count: '3' }).response; // { price: 9.9, count: 3 } ``` ### name:SmallInt Type: `type` A number from -32767 to 32767. Parsed like `Number`; a value outside the range is an error. Example: SmallInt ```js 'priority:SmallInt'.toJSONSchema().transform({ priority: 40000 }).error.output(); // [{ name: 'priority', error: 'The field "priority" is invalid', path: 'priority' }] ``` ### name:TinyInt Type: `type` A number from 0 to 255. Parsed like `Number`; a value outside the range is an error. Example: TinyInt ```js 'level:TinyInt'.toJSONSchema().transform({ level: '12' }).response; // { level: 12 } ``` ### name:Boolean name:Bool Type: `type` True or false. A 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`. Example: Checkbox ```js 'newsletter:Boolean,terms:Bool'.toJSONSchema().transform({ newsletter: 'on' }).response; // { newsletter: true, terms: false } ``` ### name:Date Type: `type` A date. A `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`. Example: Date ```js 'birthday:Date'.toJSONSchema().transform({ birthday: '1990-05-20' }).response; // { birthday: Date } ``` ### name:Email Type: `type` An email address. All 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. Example: Email ```js '*email:Email'.toJSONSchema().transform({ email: ' Peter@Example.COM ' }).response; // { email: 'peter@example.com' } ``` ### name:Email2 Type: `type` An email address without its tag. Works 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'`. Example: Email2 ```js '*email:Email2'.toJSONSchema().transform({ email: ' Peter+News@Example.COM ' }).response; // { email: 'peter@example.com' } ``` ### name:Phone Type: `type` A phone number. Whitespace is removed, then the value is checked with `String.isPhone()`. Example: Phone ```js 'phone:Phone'.toJSONSchema().transform({ phone: '+421 900 123 456' }).response; // { phone: '+421900123456' } ``` ### name:URL Type: `type` A URL address. Trimmed and checked with `String.isURL()`. Example: URL ```js 'website:URL'.toJSONSchema().transform({ website: 'https://www.totaljs.com' }).response; ``` ### name:Zip Type: `type` A ZIP code. Trimmed and checked with `String.isZIP()`. Example: Zip ```js 'zip:Zip'.toJSONSchema().transform({ zip: '12345' }).response; ``` ### name:UID Type: `type` A Total.js unique identifier. Trimmed and checked with `String.isUID()`, the format made by `UID()`. An empty value becomes `null`. Example: UID ```js '*id:UID'.toJSONSchema().transform({ id: UID() }).response; ``` ### name:GUID Type: `type` A GUID. Trimmed and checked with `String.isGUID()`. An empty value becomes `null`. Example: GUID ```js 'token:GUID'.toJSONSchema().transform({ token: GUID() }).response; ``` ### name:Name Type: `type` A person name. The value is formatted with `String.toName()`: every word starts with an upper-case letter. Example: Name ```js 'fullname:Name'.toJSONSchema().transform({ fullname: 'peter sirka' }).response; // { fullname: 'Peter Sirka' } ``` ### name:Lower name:Lowercase name:Upper name:Uppercase Type: `type` Text in lower or upper case. `Lower` and `Lowercase` trim the value and convert it to lower case. `Upper` and `Uppercase` convert it to upper case. Example: Case ```js 'login:Lower,country:Upper'.toJSONSchema().transform({ login: 'PETER', country: 'sk' }).response; // { login: 'peter', country: 'SK' } ``` ### name:Capitalize name:Capitalize2 Type: `type` Text with capital letters. `Capitalize` puts the first letter of every word in upper case. `Capitalize2` puts only the first letter of the text in upper case. Example: Capitalize ```js 'title:Capitalize,sentence:Capitalize2'.toJSONSchema().transform({ title: 'hello world', sentence: 'hello world' }).response; // { title: 'Hello World', sentence: 'Hello world' } ``` ### name:Color Type: `type` A hex color. The value must be `#RGB`, `#RRGGBB` or `#RRGGBBAA` (letters in any case). Example: Color ```js 'color:Color'.toJSONSchema().transform({ color: '#4285F4' }).response; ``` ### name:Icon Type: `type` An icon class. The 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`. Example: Icon ```js 'icon:Icon'.toJSONSchema().transform({ icon: 'ti ti-home' }).response; ``` ### name:Base64 Type: `type` A Base64 string. Trimmed and checked with `String.isBase64()`. An empty value becomes `null`. Example: Base64 ```js 'file:Base64'.toJSONSchema().transform({ file: 'SGVsbG8=' }).response; ``` ### name:JSON Type: `type` A JSON text. Trimmed 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`. Example: JSON ```js 'settings:JSON'.toJSONSchema().transform({ settings: '{"theme":"dark"}' }).response; // { settings: '{"theme":"dark"}' } 'settings:JSON'.toJSONSchema().transform({ settings: 'dark' }).error.output(); // [{ name: 'settings', error: 'The field "settings" is invalid', path: 'settings' }] ``` ### name:DataURI Type: `type` A data URI parsed into a buffer. The 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`. Example: Upload a photo as JSON ```js NEWACTION('Users/photo', { input: '*photo:DataURI', action: function($, model) { // model.photo.type === 'image/png' // model.photo.buffer is a Buffer $.success(); } }); ``` ### name:IP Type: `type` An IP address. Trimmed 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`. Example: IP ```js 'server:IP'.toJSONSchema().transform({ server: ' 10.0.0.1 ' }).response; // { server: '10.0.0.1' } 'server:IP'.toJSONSchema().transform({ server: '10.0.0.300' }).error.output(); // [{ name: 'server', error: 'The field "server" is invalid', path: 'server' }] ``` ### name:DataURI2 Type: `type` A data URI kept as text. The 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`. Example: Keep the text ```js 'avatar:DataURI2'.toJSONSchema().transform({ avatar: 'data:image/png;base64,iVBORw0KGgo=' }).response; // { avatar: 'data:image/png;base64,iVBORw0KGgo=' } ``` ### name:SafeString Type: `type` Text without XSS or SQL injection patterns. Trimmed and rejected when `String.isXSS()` or `String.isSQLInjection()` finds a dangerous pattern, such as an HTML tag. Example: SafeString ```js 'comment:SafeString'.toJSONSchema().transform({ comment: '<script>alert(1)</script>' }).error.output(); // [{ name: 'comment', error: 'The field "comment" is invalid', path: 'comment' }] ``` ### name:Search Type: `type` A normalized search phrase. Trimmed and converted with `String.toSearch()`: lower case, without diacritics and with simplified letters, so it can be compared with indexed search text. Example: Search ```js 'q:Search'.toJSONSchema().transform({ q: 'Hello Wörld' }).response; // { q: 'helo world' } ``` ### name:{a|b|c} or { type: 'string', enum: [...] } Type: `type` A value from a fixed list. In 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. Example: Inline enum ```js '*status:{draft|published|archived}'.toJSONSchema().transform({ status: 'published' }).response; ``` Example: JSON schema enum ```js F.newjsonschema({ $id: 'Task', type: 'object', properties: { priority: { type: 'string', enum: ['low', 'normal', 'high'] } } }); ``` ### name:[Type] Type: `type` An array of values of one type. The 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`. Example: Arrays ```js var schema = 'tags:[String],scores:[Number],lines:[{sku:String,qty:Number}]'.toJSONSchema(); schema.transform({ tags: ['a', ' b '], scores: ['1', 2], lines: [{ sku: 'A1', qty: '2' }] }).response; // { tags: ['a', 'b'], scores: [1, 2], lines: [{ sku: 'A1', qty: 2 }] } ``` ### name:{field:Type,...} Type: `type` A nested object. Braces 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}}}`. Example: Nested object ```js var schema = '*name:String,address:{street:String,*city:String,zip:Zip}'.toJSONSchema(); var result = schema.transform({ name: 'Peter', address: { street: 'Main 1' } }); // error: { name: 'city', path: 'address.city' } ``` ### name:@Schema name:[@Schema] Type: `type` A nested object validated by a registered schema. The 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. Example: Reuse a schema ```js NEWSCHEMA('@Address', '*street:String,*city:String'); NEWSCHEMA('@Company', '*name:String,headquarters:@Address,branches:[@Address]'); var result = F.jsonschemas.Company.transform({ name: 'Acme', branches: [{ street: 'A 1', city: 'X' }, { street: 'B 2' }] }); // error: { name: 'city', path: 'branches[1].city', index: 1 } ``` ### required: ['field', ...] Type: `property` The required fields of an object schema. An array of property names. The rules for empty values are the same as for `*` in inline schemas. Example: required ```js F.newjsonschema({ $id: 'Login', type: 'object', properties: { email: { type: 'string', subtype: 'email' }, password: { type: 'string' } }, required: ['email', 'password'] }); ``` ### { type: 'string', subtype: 'email' } Type: `property` A Total.js keyword that selects a special conversion. For `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`. Example: subtype ```js F.newjsonschema({ $id: 'Server', type: 'object', properties: { host: { type: 'string', subtype: 'ip' }, config: { type: 'string', subtype: 'json' }, port: { type: 'number', subtype: 'smallint' } } }); ``` ### { type: 'string', nullable: true } Type: `property` A Total.js keyword that turns an empty string into null. For a `string` property, an empty value becomes `null` instead of `''`. Inline types `String2`, `UID`, `GUID`, `Base64`, `DataURI` and `DataURI2` set it for you. Example: nullable ```js var schema = F.newjsonschema({ $id: 'Note', type: 'object', properties: { text: { type: 'string', nullable: true } } }); schema.transform({ text: '' }).response; // { text: null } ``` ### { type: 'string', minLength: 3, maxLength: 50 } Type: `property` The length limits of a string. `minLength` and `maxLength` check the number of characters of a string. `String(50)` in an inline schema sets `maxLength`. Example: Length ```js F.newjsonschema({ $id: 'Nick', type: 'object', properties: { nick: { type: 'string', minLength: 3, maxLength: 20 } } }); ``` ### { type: 'number', minimum: 1, maximum: 100 } Type: `property` The limits of a number. `minimum` and `maximum` are inclusive limits, `exclusiveMinimum` and `exclusiveMaximum` exclusive ones. `multipleOf` requires a value divisible by the given number. Example: Number limits ```js F.newjsonschema({ $id: 'Order', type: 'object', properties: { quantity: { type: 'number', minimum: 1, maximum: 100 }, discount: { type: 'number', exclusiveMaximum: 50 }, pack: { type: 'number', multipleOf: 6 } } }); ``` ### { type: 'array', items: { type: 'string' } } Type: `property` The schema of the items of an array. `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. Example: Array of tags ```js F.newjsonschema({ $id: 'Article', type: 'object', properties: { tags: { type: 'array', items: { type: 'string' }, minItems: 1, uniqueItems: true } } }); F.jsonschemas.Article.transform({ tags: ['a', 'b', 'a'] }).response; // { tags: ['a', 'b'] } ``` Example: Array of objects ```js F.newjsonschema({ $id: 'Order', type: 'object', properties: { items: { type: 'array', items: { type: 'object', properties: { sku: { type: 'string' }, qty: { type: 'number' } }, required: ['qty'] } } } }); var result = F.jsonschemas.Order.transform({ items: [{ sku: 'A', qty: '2' }, { sku: 'B' }] }); // result.error.items[0]: name 'items.qty', path 'items.qty', index 1 ``` ### { type: 'object', $ref: '#/definitions/Name' } Type: `property` A reference to another schema. `$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`. Example: Local and registered references ```js F.newjsonschema({ $id: 'Address', type: 'object', properties: { city: { type: 'string' } }, required: ['city'] }); F.newjsonschema({ $id: 'Invoice', type: 'object', properties: { billing: { type: 'object', $ref: 'Address' }, lines: { type: 'array', items: { $ref: '#/definitions/Line' } } }, definitions: { Line: { type: 'object', properties: { name: { type: 'string' }, price: { type: 'number' } } } } }); ``` ### new ErrorBuilder() Type: `class` A list of errors with an HTTP status. Returns: `ErrorBuilder` Validation 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). Example: Collect errors ```js var err = new ErrorBuilder(); if (!model.email) err.push2('email'); if (model.age < 18) err.push('You must be 18 or older'); if (err.length) console.log(err.output()); ``` ### err.push(error, [path], [index]) Type: `method` Adds an error message or an HTTP status. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `error` | `String|Number` | yes | | A message or an HTTP status code. | | `path` | `String` | no | | The path of the field. | | `index` | `Number` | no | | The index of an array item. | Returns: `ErrorBuilder` The same builder. A 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)')`. Example: Messages and statuses ```js var err = new ErrorBuilder(); err.push('The product is sold out'); err.push(409); err.status; // 409 err.output(); // [{ error: 'The product is sold out' }, { error: '409: Conflict' }] ``` ### err.push2(name, [path], [index], [error]) Type: `method` Adds an error of a field, with an optional message. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `name` | `String` | yes | | The name of the field. | | `path` | `String` | no | | The path of the field. | | `index` | `Number` | no | | The index of an array item. | Returns: `ErrorBuilder` The same builder. Adds 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. Signature: `err.push2(name, [path], [index], [error])`. Example: Field error ```js var err = new ErrorBuilder(); err.push2('email', 'contact.email'); err.output(); // [{ name: 'email', error: 'The field "email" is invalid', path: 'contact.email' }] ``` ### err.output([language]) Type: `method` Returns the errors as an array of objects. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `language` | `String` | no | `'default'` | The language for resources and translations. | Returns: `Array` The list of errors. Each 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. Example: Output ```js var err = new ErrorBuilder(); err.push2('name'); console.log(err.output('en')); ``` ### err.toString([language], [divider]) Type: `method` Returns the messages as one text. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `language` | `String` | no | `'default'` | The language. | | `divider` | `String` | no | `'\n'` | The text between messages. | Returns: `String` The messages of `output(language)` joined by `divider`. Example: Text ```js var err = new ErrorBuilder(); err.push('First'); err.push('Second'); err.toString(); // 'First\nSecond' err.toString('default', ', '); // 'First, Second' ``` ### err.reject([language]) Type: `method` Returns the errors as an Error object. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `language` | `String` | no | `'default'` | The language. | Returns: `Error` Creates `new Error()` with all messages joined without a divider. Useful to reject a promise. Example: Reject a promise ```js return new Promise(function(resolve, reject) { var err = new ErrorBuilder(); err.push('Not allowed'); reject(err.reject()); }); ``` ### err.throw() Type: `method` Makes the builder throw on the next error. Returns: `ErrorBuilder` The same builder. After `throw()`, every `push()` or `push2()` throws an `Error` with the message of the first error. `schema.validate()` uses it. Example: Throw at once ```js var err = new ErrorBuilder().throw(); try { err.push('Invalid token'); } catch (e) { console.log(e.message); // Invalid token } ``` ### err.replace(search, value) Type: `method` Replaces a text in all messages. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `search` | `String` | yes | | The text to find. | | `value` | `String` | yes | | The new text. | Returns: `ErrorBuilder` The same builder. The replacement is applied by `output()` to every message, so you can push a message with a placeholder and fill it later. Example: Placeholder ```js var err = new ErrorBuilder(); err.push('The limit is {limit} items'); err.replace('{limit}', 10); err.toString(); // 'The limit is 10 items' ``` ### ErrorBuilder.assign(value) Type: `method` Creates a builder from an error output, a message or an Error. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `value` | `Array|String|Number|Error` | yes | | The errors. | Returns: `ErrorBuilder` A new builder. With 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. Example: Errors from another service ```js var err = ErrorBuilder.assign([{ name: 'email', error: 'Email is taken' }]); err.length; // 1 ``` ### ErrorBuilder.transform(callback) Type: `method` Sets a global handler that changes the output of every ErrorBuilder. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `callback` | `Function` | yes | | `function(output, language)` that returns the new output. | `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. Example: A custom error format ```js ErrorBuilder.transform(function(output, language) { return { success: false, errors: output }; }); ``` --- title: Views project: Total.js V5 version: 0.0.20 section: reference language: en license: MIT url: https://totaljs.es/docs/total-js-v5/0-0-20/reference/views/ updated: 2026-11-18T16:57:29.576Z --- # Views > The view commands, the view object, helpers and TEMPLATE(). Views 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. ## API ### controller.view([name], [model]) Type: `method` Renders a view and sends it as the HTML response. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `name` | `String` | no | | The name of the view without `.html`, for example `products/detail`. | | `model` | `Object` | no | | The model, available as `model` in the view. | Returns: `View` The view object. The 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. Example: Render a view ```js exports.install = function() { ROUTE('GET /products/{id}/', detail); }; function detail($) { var id = $.params.id; $.view('products/detail', { id: id }); } ``` Example: Render it yourself ```js function preview($) { var view = $.view(); view.layout(''); $.html(view.render('preview', { name: 'Test' })); } ``` ### controller.layout(name) Type: `method` Sets the layout for the next `controller.view()`. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `name` | `String` | yes | | The name of the layout view. | Call 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()}`. Example: Use another layout ```js function admin($) { $.layout('layout-admin'); $.view('admin/index'); } ``` ### F.view(name, [model], [prepare]) Type: `method` Renders a view outside of a request and returns the HTML. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `name` | `String` | yes | | The name of the view. | | `model` | `Object` | no | | The model. | | `prepare` | `Function` | no | | `function(view)` called before the rendering, to set `view.language`, `view.repository` or the layout. | Returns: `String` The rendered HTML. The 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. Example: Render an e-mail body ```js var html = F.view('mail/order', { id: 'A100' }, function(view) { view.language = 'sk'; view.layout(''); }); ``` ### new F.TViewEngine.View([controller]) Type: `class` The object that renders a view; it is `self` inside the compiled view. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `controller` | `Controller` | no | | The controller of the request. | `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()`. Example: Set values before rendering ```js function page($) { var view = $.view(); view.repository.menu = 'products'; $.html(view.render('products', { items: [] })); } ``` ### view.render(name, [model]) Type: `method` Renders a view with its layout and returns the HTML. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `name` | `String` | yes | | The name of the view. | | `model` | `Object` | no | | The model. | Returns: `String` The HTML. The 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. Example: Render ```js var view = new F.TViewEngine.View(); view.layout(''); var html = view.render('fragments/card', { name: 'Pen' }); ``` ### view.repository Type: `property` An object shared by the view, its partial views and the layout. Returns: `Object` It 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. Example: View to layout ```html <!-- view --> @{repository.menu = 'products'} <!-- layout --> <nav class="@{repository.menu}">...</nav> ``` ### view.language Type: `property` The language used for `@(...)` translations. Returns: `String` It 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. Example: Language in F.view() ```js var html = F.view('mail/welcome', model, function(view) { view.language = 'de'; }); ``` ### @{expression} Type: `command` Prints the value of a JavaScript expression, HTML-encoded. Any 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. Example: Values ```html <h1>@{model.name}</h1> <p>@{model.items.length} items</p> <p>@{model.price.format(2)}</p> @{repository.count = model.items.length} ``` ### @{!expression} Type: `command` Prints the value of an expression without HTML encoding. Use it for HTML you trust, for example content of a CMS stored by your administrators. Example: Raw HTML ```html <article>@{!model.body}</article> ``` ### @{model} Type: `command` The model passed to the view. It is the second argument of `controller.view()`, `F.view()`, `view.render()` or `@{view()}`. The layout does not receive the model. Example: Read the model ```html <h1>@{model.title}</h1> @{if model.user}<p>@{model.user.name}</p>@{fi} ``` ### @{repository} Type: `command` The shared object of the view, its partial views and the layout. See `view.repository`. Assign values with `@{repository.key = value}`; the assignment prints nothing. Example: Set and read ```html @{repository.menu = 'contact'} <li class="@{repository.menu === 'contact' ? 'active' : ''}">Contact</li> ``` ### @{config.key} / @{'%key'} Type: `command` Prints a configuration value. `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. Example: Configuration ```html <title>@{config.name}
    @{'%name'} @{config.version}
    ``` ### @{query} / @{body} / @{files} / @{user} / @{session} / @{controller} Type: `command` The data of the current request. `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. Example: Request values ```html @{if user}

    Hello @{user.name}

    @{else} Sign in @{fi} ``` ### @{body} Type: `command` In a layout, prints the HTML of the rendered view. The output is not encoded. With a property (`@{body.name}`) it reads the body of the request instead. Example: Layout ```html @{import('meta')} @{body} ``` ### @{language} Type: `command` The language of the view. The 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. Example: Language attribute ```html ``` Example: In F.view() ```js var html = F.view('mail/welcome', model, function(view) { view.language = 'de'; }); // ``` ### @{url} Type: `command` The URL path of the current request. It 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`. Example: Active link ```html Products ``` ### @{hostname([path])} Type: `command` Prints the absolute URL of the current page or of another path. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `path` | `String` | no | | A path that starts with `/`. Without it, the path of the current request. | Returns: `String` The absolute URL. `@{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. In `F.view()` there is no request, so it prints only `path` (or an empty string). Example: Canonical link and share image ```html ``` ### @{cookie(name)} Type: `command` Prints the value of a cookie of the request, HTML-encoded. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `name` | `String` | yes | | The name of the cookie. | Without a controller it prints an empty string. Example: Read a cookie ```html ``` ### @{now} Type: `command` A new `Date` with the current time. Use properties and methods of the date directly: `@{now.getFullYear()}`. Example: Copyright ```html
    © @{now.getFullYear()} @{config.name}
    ``` ### @{root} Type: `command` Prints `CONF.$root` without its trailing slash. Use it for links when the application runs under a sub-path. It prints an empty string when `CONF.$root` is not set. Example: Link under a sub-path ```html Products ``` ### @{if condition} ... @{else if condition} ... @{else} ... @{fi} Type: `command` Renders a part of the view only when a condition is true. The condition is any JavaScript expression. `@{endif}` is the same as `@{fi}`. `@{if(condition)}` with parentheses works as well. Example: Condition ```html @{if model.stock > 10} In stock @{else if model.stock > 0} Last pieces @{else} Sold out @{fi} ``` ### @{foreach item in source} ... @{end} Type: `command` Repeats a part of the view for every item of an array or an object. For 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. Example: Array ```html
      @{foreach item in model.items} @{if item.hidden}@{continue}@{fi}
    • @{index + 1}. @{item.name}
    • @{end}
    ``` Example: Object ```html @{foreach prop in model.settings}
    @{prop.key}
    @{prop.value}
    @{end} ``` ### @{index} Type: `command` The zero-based position of the current item in `@{foreach}`. Example: Numbered rows ```html @{foreach row in model.rows} @{index + 1}@{row.name} @{end} ``` ### @{layout(name)} Type: `command` Sets the layout of the view. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `name` | `String` | yes | | The name of the layout view, or an empty string. | The default layout is `layout` (`/views/layout.html`). An empty string renders the view without a layout. The command prints nothing. Example: Another layout ```html @{layout('layout-print')}

    @{model.title}

    ``` Example: No layout ```html @{layout('')}
    @{model.name}
    ``` ### @{view(name, [model])} Type: `command` Renders another view in place (a partial view). | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `name` | `String` | yes | | The name of the view. | | `model` | `Object` | no | | The model of the partial view. | The 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/`. Example: Partial views ```html @{foreach item in model.items} @{view('partials/card', item)} @{end} @{view('#blog/sidebar')} ``` ### @{section name} ... @{end} / @{section(name)} Type: `command` Collects HTML in a view and prints it in another place, usually the layout. `@{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. Example: Scripts for the layout ```html @{section scripts} @{end} @{section('scripts')} ``` ### view.section(name, [value], [replace]) Type: `method` Reads or fills a section from JavaScript. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `name` | `String` | yes | | The name of the section. | | `value` | `String` | no | | The HTML to add. | | `replace` | `Boolean` | no | `false` | Replace the current content. | Returns: `String|View` The section when reading; the view when writing. Without `value` it returns the HTML of the section. With `value` it appends the HTML to the section, or replaces it when `replace` is `true`. Example: Fill a section ```js function page($) { var view = $.view(); view.section('scripts', ''); $.html(view.render('page')); } ``` ### @{title(value)} / @{title} Type: `command` Sets or prints the title of the page. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `value` | `String` | yes | | The title. | `@{title('Text')}` stores the text in `repository.title` and prints nothing. `@{title}` prints it HTML-encoded, `@{!title}` without encoding. Example: Title ```html @{title('Products / ' + model.category)}

    @{title}

    ``` ### @{title2(value)} Type: `command` Appends text to the title of the page. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `value` | `String` | yes | | The text to append. | Adds `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. Example: Title in two steps ```html @{title('Products')} @{if model}@{title2(' / ' + model.name)}@{fi}

    @{title}

    ``` ### @{description(value)} / @{description} Type: `command` Sets or prints the description of the page. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `value` | `String` | yes | | The description. | The value goes to `repository.description`; `@{import('meta')}` prints it as a `` tag. Example: Description ```html @{description('Pens, pencils and paper for the office.')} ``` ### @{keywords(value)} / @{keywords} Type: `command` Sets or prints the keywords of the page. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `value` | `String|Array` | yes | | The keywords. | An array is joined with `, `. The value goes to `repository.keywords`. Example: Keywords ```html @{keywords(['pens', 'paper', 'office'])} ``` ### @{meta([title], [description], [keywords], [image])} / @{meta} Type: `command` Sets the title, description, keywords and image at once, or prints the meta tags. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `title` | `String` | no | | The title. | | `description` | `String` | no | | The description. | | `keywords` | `String|Array` | no | | The keywords. | | `image` | `String` | no | | An absolute URL or a path of an image. | With 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')}`: ``, 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`. Example: Set and print ```html <!-- view --> @{meta(model.name, model.summary, model.tags, model.photo)} <!-- layout --> <head>@{meta}</head> ``` ### CONF.$customtitles Type: `config` Prints the page title without the application name. Returns: `Boolean` Default `false`. By default the title tag of `@{meta}` and `@{import('meta')}` is `Title - CONF.name`. With `true` the title is printed as you set it. Example: /config ```text $customtitles : true ``` ### @{import(name, [name2], ...)} Type: `command` Prints the tags for static files, the meta tags or a favicon. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `name` | `String` | yes | | A file name, `meta` or a favicon name. | Each argument gives one tag: - `meta` prints the meta tags (see `@{meta}`). - `favicon.ico`, `favicon.png` or `favicon.gif` prints a `<link rel="icon">` tag. - 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. - An `@` before the name appends `?ts=` with the start time of the application. - Names joined with `+` are merged into one minified file (see the next entry). The tags are cached, so the command is cheap. Example: Head of a layout ```html <head> @{import('meta', 'favicon.ico', '@default.css', 'ui.js', '/vendor/editor.js')} </head> ``` ### @{import('a.css + b.css')} Type: `command` Merges several CSS or JavaScript files into one minified file. The 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=`. Example: One CSS and one JS file ```html @{import('reset.css + layout.css + forms.css', '@ui.js + app.js')} <!-- <link rel="stylesheet" href="/wqxjrnefjv-min.css" /> --> <!-- <script src="/wbxyamtxmw-min.js?ts=mwi48bh6"></script> --> ``` ### @{json(value, [id], [beautify], [replacer])} Type: `command` Prints a value as JSON, or in a `<script type="application/json">` tag. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `value` | `Object` | yes | | The value. | | `id` | `String` | no | | The id of the script tag. | | `beautify` | `Boolean` | no | `false` | Indent the JSON. | | `replacer` | `Function|Boolean` | no | | A replacer for `JSON.stringify()`. | With `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)}`. Example: Data for the client ```html @{json(model.products, 'products')} <script> var products = JSON.parse(document.getElementById('products').innerHTML); </script> ``` ### @{href([key], [value])} Type: `command` Prints the current query string with one parameter changed. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `key` | `String|Object` | no | | The name of the parameter, or an object with the parameters to set. | | `value` | `Any` | no | | The new value. | Returns: `String` The query string with `?`, or an empty string. `@{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. Example: Paging ```html <a href="@{href('page', model.page - 1)}">Previous</a> <a href="@{href('page', model.page + 1)}">Next</a> ``` Example: Remove a parameter, or change several ```html <!-- /products/?page=2&sort=name&q=pen --> <a href="@{href('page', 1, 'sort')}">First page</a> <!-- ?page=1&q=pen --> <a href="@{href({ page: 1, sort: 'price' })}">By price</a> <!-- /products/?page=1&sort=price&q=pen --> ``` ### DEF.helpers Type: `property` Custom functions you call from every view. Returns: `Object` Add 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/`. Example: Register and use ```js // /definitions/helpers.js DEF.helpers.price = function(value, currency) { return value.format(2) + ' ' + (currency || 'EUR'); }; // in a view: <span>@{price(model.price, 'USD')}</span> ``` ### @{helper(name, [arg1], [arg2], ...)} Type: `command` Calls a helper from `DEF.helpers` by its name. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `name` | `String` | yes | | The name of the helper. | The other arguments go to the helper. It prints an empty string when the helper does not exist. Example: Call a helper ```html <span>@{helper('price', model.price, 'EUR')}</span> ``` ### @(text) Type: `command` Translates a text into the language of the view. The 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. Example: Translated text ```html <h1>@(Welcome)</h1> <button>@(Add to cart)</button> ``` ### @{compile [name]} ... @{end} Type: `command` Passes a part of the view to `DEF.onViewCompile` on every render. The 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. Example: Markdown ```html @{compile markdown} # @{model.title} @{model.text} @{end} ``` ### DEF.onViewCompile = function(name, html, model) Type: `delegate` Processes the content of `@{compile}` blocks. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `name` | `String` | yes | | The name of the block, or an empty string. | | `html` | `String` | yes | | The content of the block. | | `model` | `Object` | yes | | The model of the view. | Returns: `String` The HTML to print. `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. Example: Markdown blocks ```js DEF.onViewCompile = function(name, html, model) { return name === 'markdown' ? html.markdown() : html; }; ``` ### ON('$view', function(meta) {}) Type: `event` Changes the source of a view before it is compiled. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `meta` | `Object` | yes | | `{ name, body, debug }`. | `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. Example: Replace a placeholder ```js ON('$view', function(meta) { meta.body = meta.body.replace(/\{year\}/g, new Date().getFullYear() + ''); }); ``` ### @{nocompress html|js|css|all} Type: `command` Turns off a compression step for the view. When 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. Example: Keep whitespace ```html @{nocompress html} <pre> formatted text </pre> ``` ### @{{ text }} Type: `command` Prints `@{{ ... }}` as it is, without running it. Use it to keep `@{{ }}` text for client-side templates. Example: Literal text ```html <code>@{{ value }}</code> ``` ### TEMPLATE(body, [model], [$]) Type: `method` Renders a Tangular template and returns a promise with the HTML. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `body` | `String` | yes | | The template, a URL, a path or a name of a file in `/templates/`. | | `model` | `Object` | no | | The model, available as `value`. | | `$` | `Options` | no | | The `$` of an action or a controller, for the language and error handling. | Returns: `Promise<String>` The rendered HTML. `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`. The 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. Example: Inline template ```js var html = await TEMPLATE('<p>Hello {{ value.name }}</p>', { name: 'Peter' }); ``` Example: A file in a route ```js exports.install = function() { ROUTE('GET /invoice/{id}/', invoice); }; function invoice($) { TEMPLATE('invoice', { number: $.params.id }, $).then(function(html) { $.html(html); }); } ``` ### {{ value }} / {{ if }} / {{ foreach }} Type: `command` The commands of Tangular templates used by `TEMPLATE()`. `{{ 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 }}`. Example: Invoice ```html <h1>Invoice {{ value.number }}</h1> {{ if value.items.length }} <table> {{ foreach item in value.items }} <tr><td>{{ $index + 1 }}</td><td>{{ item.name }}</td><td>{{ item.price | format(2) }}</td></tr> {{ end }} </table> {{ else }} <p>No items</p> {{ fi }} ``` ### Thelpers Type: `property` The helpers of Tangular templates. Returns: `Object` Built-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`. Example: A template file with a helper and a default model ```html <script type="text/json">{ "name": "Guest" }</script> <script> Thelpers.upper = function(value) { return (value || '').toUpperCase(); }; </script> <h1>{{ value.name | upper }}</h1> <p>{{ value.count | pluralize('# items', '# item', '# items', '# items') }}</p> <p>{{ value.date | format('yyyy-MM-dd') }} {{ value.note | def('none') }}</p> ``` --- title: Configuration project: Total.js V5 version: 0.0.20 section: reference language: en license: MIT url: https://totaljs.es/docs/total-js-v5/0-0-20/reference/configuration/ updated: 2026-11-18T16:57:29.576Z --- # Configuration > CONF, LOADCONFIG(), DEBUG and every $ key of the framework with its default. Every 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. ## API ### CONF Type: `property` The global object with the configuration of the application. Returns: `Object` Holds 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. Example: Read values ```js exports.install = function() { ROUTE('GET /about/', function($) { $.json({ name: CONF.name, version: CONF.version }); }); }; ``` ### LOADCONFIG(value) Type: `method` Applies configuration values at runtime. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `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). | Parses `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. Example: Text ```js LOADCONFIG('$httptimeout (number) : 15\nmaintenance : true'); ``` Example: Array with types ```js LOADCONFIG([ { id: 'limit', type: 'number', value: '25' }, { id: 'tags', type: 'array', value: 'a, b, c' } ]); ``` Example: Object ```js LOADCONFIG({ name: 'Shop', $cors: 'https://shop.example.com' }); ``` ### DEBUG Type: `property` true in debug mode, false in release mode. Returns: `Boolean` A 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). Example: Conditional code ```js if (DEBUG) console.log('Debug mode'); ``` ### ON('$reconfigure', function() {}) Type: `event` Emitted after LOADCONFIG() applies new values. Emitted 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. Example: Refresh a client ```js ON('$reconfigure', function() { MAIN.client = createclient(CONF.service_url); }); ``` ### totalapi : String|Boolean Type: `config` · Since: `0.0.16` Sets the Total API token or turns Total API on or off. Returns: `String|Boolean` A 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`. Example: In the config file ```text totalapi : your-total-api-token ``` ### $root : String Type: `config` A URL prefix for the whole application. Returns: `String` Normalized 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. Default: `''`. Example: In the config file ```text $root : /app/ ``` ### $api : String Type: `config` The default API endpoint. Returns: `String` A `?` 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. Default: `'/api/'`. Example: In the config file ```text $api : /v1/ ``` ### $mcp : Boolean Type: `config` Turns on the MCP server. Returns: `Boolean` `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/). Default: `false`. Example: In the config file ```text $mcp : true ``` ### $cors : String Type: `config` Origins allowed for cross-origin requests. Returns: `String` `*` 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). Default: `''`. Example: In the config file ```text $cors : https://app.example.com, *example.org ``` ### $port : Number Type: `config` The port of the HTTP server. Returns: `Number` The 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. Default: `'auto'`. Example: In the config file ```text $port : 8000 ``` ### $ip : String Type: `config` The IP address the HTTP server listens on. Returns: `String` The `ip` option of `F.http()` overrides it. Use `127.0.0.1` to accept only local connections. Default: `'0.0.0.0'`. Example: In the config file ```text $ip : 127.0.0.1 ``` ### $unixsocket : String Type: `config` A Unix socket path for the HTTP server. Returns: `String` When set (or when `F.http()` gets the `unixsocket` option), the server listens on the socket instead of a port. Default: `''`. Example: In the config file ```text $unixsocket : /var/run/app.sock ``` ### $timezone : String Type: `config` The time zone of the process. Returns: `String` Copied into `process.env.TZ`, so all `Date` values of the process use it. Default: `'utc'`. Example: In the config file ```text $timezone : Europe/Bratislava ``` ### $insecure : Boolean Type: `config` Accepts invalid TLS certificates in outgoing requests. Returns: `Boolean` Sets `process.env.NODE_TLS_REJECT_UNAUTHORIZED` to `0` when `true` and `1` otherwise. Use it only for development against self-signed servers. Default: `false`. Example: In the config file ```text $insecure : true ``` ### $performance : Boolean Type: `config` Tunes the HTTP sockets for many connections. Returns: `Boolean` Sets `maxSockets` of the global HTTP agent to 9999 and turns on `setNoDelay` and keep-alive for incoming connections. Default: `false`. Example: In the config file ```text $performance : true ``` ### $httpreqlimit : Number Type: `config` The maximum number of requests per IP address per minute. Returns: `Number` `0` turns the limit off. Above the limit, requests get the error 503 until the counters are cleared at the next minute. Default: `0`. Example: In the config file ```text $httpreqlimit (number) : 300 ``` ### $blacklist : String Type: `config` Blocked IP addresses. Returns: `String` A 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. Default: `''`. Example: In the config file ```text $blacklist : 10.0.0.5, 10.0.0.6 ``` ### $httpcompress : Boolean Type: `config` Compresses responses with gzip. Returns: `Boolean` When the client accepts gzip, text responses larger than 256 bytes and compressible static files are compressed. Default: `true`. Example: In the config file ```text $httpcompress : false ``` ### $httpetag : String Type: `config` A value added to the ETag of static files and cached responses. Returns: `String` When empty, it is created from `CONF.version` without dots and spaces, so a new version invalidates browser caches. Default: `''`. Example: In the config file ```text $httpetag : build42 ``` ### $httpmaxsize : Number Type: `config` The maximum size of a request body in kB. Returns: `Number` The default limit of every HTTP route without its own limit. Default: `256`. Example: In the config file ```text $httpmaxsize (number) : 1024 ``` ### $httprangebuffer : Number Type: `config` The size of one chunk of a range response in kB. Returns: `Number` Used for `Range` requests of static files (video, audio) when the client does not give the end. Default: `5120`. Example: In the config file ```text $httprangebuffer (number) : 2048 ``` ### $httptimeout : Number Type: `config` The request timeout in seconds. Returns: `Number` A route can set its own timeout. Requests are checked every five seconds. Default: `5`. Example: In the config file ```text $httptimeout (number) : 10 ``` ### $httpfiles : String Type: `config` File extensions served as static files. Returns: `String` In 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. Default: `common web extensions`. Example: In the config file ```text $httpfiles : glb, gltf ``` ### $httpchecktypes : Boolean Type: `config` Checks the content type of uploaded files. Returns: `Boolean` For `multipart/form-data` only. `false` skips the check. Default: `true`. Example: In the config file ```text $httpchecktypes : false ``` ### $httpmaxage : Number Type: `config` The max-age of cached responses in seconds. Returns: `Number` Used in the `Cache-Control` header of static files and of responses cached with `controller.httpcache()`. Default: `60`. Example: In the config file ```text $httpmaxage (number) : 300 ``` ### $httpmaxkeys : Number Type: `config` Limits of URL-encoded data. Returns: `Number` `$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. Default: `33`. Example: In the config file ```text $httpmaxkeys (number) : 100 $httpmaxkey (number) : 50 ``` ### $httpcacheoffset : String Type: `config` · Since: `0.0.16` Moves the Last-Modified date of static files. Returns: `String` A 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. Default: `''`. Example: In the config file ```text $httpcacheoffset : 1 minute ``` ### $xpoweredby : String Type: `config` The value of the X-Powered-By header. Returns: `String` An empty value removes the header. Default: `'Total.js'`. Example: In the config file ```text $xpoweredby : ``` ### $minify* : Boolean Type: `config` Minification of JavaScript, CSS and HTML. Returns: `Boolean` `$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. Example: In the config file ```text $minifyhtml : false $minifyjs : true $minifycss : true ``` ### $filtererrors : Boolean Type: `config` Ignores harmless uncaught errors. Returns: `Boolean` Uncaught `EPIPE`, `invalid distance` and `ERR_IPC_CHANNEL_CLOSED` errors are not logged. Default: `true`. Example: In the config file ```text $filtererrors : false ``` ### $cleartemp : Boolean Type: `config` Clears the tmp directory at start. Returns: `Boolean` Deletes the `.js`, `.css`, `.html`, `.htm`, `.tmp` and `.upload` files of the `tmp` directory when the application loads. Default: `true`. Example: In the config file ```text $cleartemp : false ``` ### $customtitles : Boolean Type: `config` Turns off the automatic suffix of page titles. Returns: `Boolean` By default a view title on pages other than `/` gets ` - ` and `CONF.name` appended. `true` keeps the title as you set it. Default: `false`. Example: In the config file ```text $customtitles : true ``` ### $clearcache : Number Type: `config` How often internal caches are cleared, in minutes. Returns: `Number` Clears the caches of actions, paths, views, images, templates, query builders and file storages. Default: `10`. Example: In the config file ```text $clearcache (number) : 30 ``` ### $imageconverter : String Type: `config` The program used by the image module. Returns: `String` `gm` for GraphicsMagick, `im` for the ImageMagick `convert` command or `magick` for ImageMagick 7. See [Images](../../guides/images/). Default: `'gm'`. Example: In the config file ```text $imageconverter : magick ``` ### $stats : Boolean Type: `config` Writes the statistics file of the application. Returns: `Boolean` Every 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. Default: `true`. Example: In the config file ```text $stats : false ``` ### $sourcemap : Boolean Type: `config` Writes the source map of the application. Returns: `Boolean` Writes 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`. Example: Turn off ```text $sourcemap : false ``` ### $npmcache : String Type: `config` The npm cache directory for NPMINSTALL(). Returns: `String` Passed to npm as `NPM_CONFIG_CACHE`. Default: `'/var/www/.npm'`. Example: In the config file ```text $npmcache : /tmp/.npm ``` ### $nodemodules : String Type: `config` The directory of installed npm modules. Returns: `String` `NPMINSTALL()` installs into it and `REQUIRE()` loads from it when a normal `require()` fails. Default: `'<root>/node_modules'`. Example: In the config file ```text $nodemodules : /www/shared/node_modules ``` ### $python : String Type: `config` The Python command. Returns: `String` Used by `F.python()` and `F.pipinstall()`. `PYPELINE()` always runs `python3`. Default: `'python3'`. Example: In the config file ```text $python : /usr/bin/python3.12 ``` ### $shell : String Type: `config` The shell for SHELL(). Returns: `String` When set, `SHELL()` runs commands in this shell instead of the default one. Default: `''`. Example: In the config file ```text $shell : /bin/bash ``` ### $wsmaxsize : Number Type: `config` The maximum size of a WebSocket message in kB. Returns: `Number` The default limit of every WebSocket route without its own limit. Default: `256`. Example: In the config file ```text $wsmaxsize (number) : 1024 ``` ### $wscompress : Boolean Type: `config` Compresses WebSocket messages. Returns: `Boolean` Uses `permessage-deflate` when the client supports it. Default: `true`. Example: In the config file ```text $wscompress : false ``` ### $wsencodedecode : Boolean Type: `config` URL-encodes WebSocket messages. Returns: `Boolean` `true` encodes outgoing messages with `encodeURIComponent` and decodes incoming ones. Default: `false`. Example: In the config file ```text $wsencodedecode : true ``` ### $wsmaxlatency : Number Type: `config` The maximum ping latency of a WebSocket client in milliseconds. Returns: `Number` When the framework pings the connections, clients without an answer or with a higher latency are closed. Default: `2000`. Example: In the config file ```text $wsmaxlatency (number) : 5000 ``` ### $proxytimeout : Number Type: `config` The timeout of proxied requests in seconds. Returns: `Number` Used by `PROXY()` routes without their own timeout. Default: `5`. Example: In the config file ```text $proxytimeout (number) : 30 ``` ### $proxyrequest : String Type: `config` A proxy server for outgoing requests. Returns: `String` `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. Default: `not set`. Example: In the config file ```text $proxyrequest : http://proxy.local:3128 ``` ### $cookie* : String|Boolean Type: `config` Defaults of cookies. Returns: `String|Boolean` `$cookiesamesite` (default `Lax`) is the `SameSite` value of cookies without their own. `$cookiesecure` (default `false`) adds `Secure` to cookies that do not set `secure`. Example: In the config file ```text $cookiesamesite : Strict $cookiesecure : true ``` ### $csrfexpiration : String Type: `config` The lifetime of CSRF tokens. Returns: `String` A time in the format of `Date.add()`. Tokens are created only when `secret_csrf` is set. Default: `'30 minutes'`. Example: In the config file ```text $csrfexpiration : 2 hours ``` ### $crypto : String Type: `config` A Node.js cipher for ENCRYPT() and DECRYPT(). Returns: `String` When 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`. Default: `not set`. Example: In the config file ```text $crypto : aes-256-cbc $cryptoiv : 000102030405060708090a0b0c0d0e0f ``` ### $tapi* : Boolean|String Type: `config` Total API settings. Returns: `Boolean|String` `$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. Example: In the config file ```text secret_totalapi : your-token $tapiurl : eu ``` ### $tms* : Boolean|String|Number Type: `config` Total.js Message Service settings. Returns: `Boolean|String|Number` `$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/). Example: In the config file ```text $tms : true secret_tms : my-secret ``` ### $imprint : Boolean Type: `config` Prints the start screen. Returns: `Boolean` `false` hides the information block (name, version, Node.js, URL) printed when the application starts. Default: `true`. Example: In the config file ```text $imprint : false ``` ### $logger : Boolean Type: `config` Writes console output to logs/debug.log. Returns: `Boolean` `true` redirects `console.log`, `console.warn`, `console.error`, `console.time` and `console.timeEnd` to the file `logs/debug.log`. Default: `false`. Example: In the config file ```text $logger : true ``` ### $dir* : String Type: `config` Custom paths of the application directories. Returns: `String` `$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. Example: In the config file ```text $dirpublic : /www/cdn/public $dirdatabases : /data/app ``` --- title: Authorization project: Total.js V5 version: 0.0.20 section: reference language: en license: MIT url: https://totaljs.es/docs/total-js-v5/0-0-20/reference/authorization/ updated: 2026-11-18T16:57:29.576Z --- # Authorization > AUTH(), route flags, permissions, sessions and BLOCKED(). Everything 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. Encryption and audit logs have their own pages: [Encryption](../encryption/) and [Audit logs](../audit-logs/). ## API ### AUTH(callback) Type: `delegate` Registers the authorization delegate that decides who the user of a request is. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `callback` | `Function` | yes | | `function($)`; call `$.success(user)` or `$.invalid()`. | Returns: `undefined` The 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. Example: Token in a header ```js AUTH(function($) { var token = $.headers['x-token']; if (!token) { $.invalid(); return; } DATA.read('tbl_user').where('token', token).callback(function(err, user) { if (user) $.success(user); else $.invalid(); }); }); ``` ### AUTH(options) Type: `method` Installs the built-in cookie session system. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `options.secret` | `String` | yes | | The secret that signs the session tokens. | | `options.cookie` | `String` | no | | The name of the session cookie. | | `options.header` | `String` | no | | A lower-case header name to read the token from when there is no cookie. | | `options.options` | `Object` | no | | Cookie options used by `authcookie()` and when the cookie is removed (`httponly`, `security`, `domain`...). | | `options.expire` | `String` | no | `'5 minutes'` | How long loaded user data stays in memory. | | `options.cleaner` | `Number` | no | `5` | How often, in minutes, expired sessions are removed. | | `options.strict` | `Boolean` | no | `true` | A cached session is valid only for the same user agent. | | `options.ddos` | `Number` | no | | How many invalid tokens one IP address may send before it is refused until the next cleaning. | | `options.onread` | `Function` | yes | | `function(meta, callback, $)` loads the user; see `opt.onread`. | Returns: `undefined` With 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. Example: Session setup ```js var opt = {}; opt.secret = 'a-long-random-string'; opt.cookie = '__user'; opt.expire = '10 minutes'; opt.onread = function(meta, next) { DATA.read('tbl_user').id(meta.userid).callback(next); }; AUTH(opt); MAIN.session = opt; ``` ### opt.onread = function(meta, callback, $) Type: `delegate` Loads the user of a session that is not in memory. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `meta` | `Object` | yes | | `{ sessionid, userid, ip, ua }`. | | `callback` | `Function` | yes | | `function(err, data)`. | | `$` | `Object` | yes | | The options of the request. | `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()`. Example: Read from the database ```js opt.onread = function(meta, next) { DATA.read('tbl_user').fields('id,name,sa,permissions').id(meta.userid).where('isdisabled', false).callback(next); }; ``` ### opt.onsession = function(session, $, [isnew]) Type: `delegate` Runs for each authorized request before the user is accepted. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `session` | `Object` | yes | | The session. | | `$` | `Object` | yes | | The options of the request. | | `isnew` | `Boolean` | no | | `true` when the data was just read. | Returns: `Boolean` `true` to stop the default success. `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. Example: Count requests ```js opt.onsession = function(session, $) { session.data.requests = (session.data.requests || 0) + 1; }; ``` ### opt.onauthorize = function($) Type: `delegate` Runs first in the session delegate; return true to handle the request yourself. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `$` | `Object` | yes | | The options of the request. | Returns: `Boolean` `true` to skip the session check. Use 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()`. Example: API key ```js opt.onauthorize = function($) { if ($.headers['x-apikey'] === CONF.apikey) { $.success({ id: 'api', sa: true }); return true; } }; ``` ### opt.onfree = function(meta) Type: `delegate` Runs after expired sessions are removed from memory. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `meta` | `Object` | yes | | `{ sessions: Array, users: Array }`. | `meta.sessions` is an array of removed session IDs, `meta.users` the IDs of users that have no live session left. Example: Log it ```js opt.onfree = function(meta) { console.log('Released', meta.sessions.length, 'sessions'); }; ``` ### opt.onlogout = function(session) Type: `delegate` Runs when logout() removes a session from memory. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `session` | `Object` | yes | | The removed session. | Gets the removed session object `{ sessionid, userid, data, ua, expire }`. When the session is not in memory, `opt.onremove(sessionid)` is called instead. Example: Store the time ```js opt.onlogout = function(session) { DATA.modify('tbl_user', { dtlogout: NOW }).id(session.userid); }; ``` ### opt.onddos = function($) Type: `delegate` Runs when an IP address exceeded the ddos limit of invalid tokens. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `$` | `Object` | yes | | The options of the request. | The request is refused right after this call. The counters are cleared every `cleaner` minutes. Example: Log it ```js opt.ddos = 10; opt.onddos = function($) { console.warn('Too many invalid tokens from', $.ip); }; ``` ### opt.localize = function(user, controller) Type: `delegate` Returns the language of the request from the user data. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `user` | `Object` | yes | | The user data or `null`. | | `controller` | `Controller` | yes | | The controller. | Returns: `String` A language code. Called 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. Example: User language ```js opt.localize = function(user, ctrl) { return user ? user.language : (ctrl.headers['accept-language'] || '').substring(0, 2); }; ``` ### opt.authcookie($, sessionid, userid, [expire], [options]) Type: `method` Signs a token and sets the session cookie. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `$` | `Object` | yes | | The `$` of an action or a controller. | | `sessionid` | `String` | yes | | A new unique ID, for example `UID()`. | | `userid` | `String` | yes | | The user ID passed later to `onread()`. | | `expire` | `String|Date` | no | | The cookie expiration, for example `'1 month'`. | | `options` | `Object` | no | | Cookie options. | Returns: `String` The token. Call 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()`. Example: Login ```js MAIN.session.authcookie($, UID(), user.id, '1 month'); $.success(); ``` ### opt.sign(sessionid, userid) Type: `method` Creates a signed session token without setting a cookie. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `sessionid` | `String` | yes | | A unique session ID. | | `userid` | `String` | yes | | The user ID. | Returns: `String` The token. Use it for clients that send the token in the `header` option instead of a cookie. Example: Token for a mobile app ```js opt.header = 'x-token'; // in the login action $.success(MAIN.session.sign(UID(), user.id)); ``` ### opt.logout($) Type: `method` Removes the session of the request and its cookie. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `$` | `Object|String` | yes | | The request or a session ID. | Returns: `Boolean` `true` when a session was removed. `$` 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. Example: Logout action ```js NEWACTION({ id: 'Account/logout', action: function($) { MAIN.session.logout($); $.success(); } }); ``` ### opt.update(userid, fn) Type: `method` Changes the cached data of every session of a user. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `userid` | `String` | yes | | The user ID. | | `fn` | `Function` | yes | | `function(data, session)`. | Returns: `Number` How many sessions were updated. Calls `fn(data, session)` for each session of `userid` in memory. Example: Rename ```js MAIN.session.update(user.id, function(data) { data.name = model.name; }); ``` ### opt.refresh(userid, [exceptsessionid]) Type: `method` Drops the cached sessions of a user so the next request reads the user again. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `userid` | `String` | yes | | The user ID. | | `exceptsessionid` | `String` | no | | A session to keep. | Returns: `Number` How many sessions were dropped. The cookies stay valid; `onread()` loads fresh data on the next request. Pass `exceptsessionid` to keep one session in memory. Example: After a permission change ```js MAIN.session.refresh(model.userid); ``` ### opt.sessions Type: `property` The sessions in memory, keyed by session ID. Returns: `Object` Each item is `{ sessionid, userid, data, ua, expire }`. Example: Online users ```js var count = Object.keys(MAIN.session.sessions).length; ``` ### DEF.onAuthorize Type: `property` The registered authorization delegate. Returns: `Function` `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. Example: Check ```js if (!DEF.onAuthorize) console.warn('No AUTH() delegate'); ``` ### ROUTE('+METHOD /url/ ...') Type: `type` The route is only for authorized requests. The 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. Example: Admin area ```js ROUTE('+GET /admin/', dashboard); ROUTE('+API /api/ orders_list --> Orders/list'); ROUTE('+SOCKET /chat/', chat); ``` ### ROUTE('-METHOD /url/ ...') Type: `type` The route is only for unauthorized requests. Typical for login and registration pages. With a `+` route on the same URL you serve visitors and users differently. Example: Same URL for both ```js ROUTE('+GET /', 'app'); ROUTE('-GET /', 'login'); ``` ### controller.user Type: `property` The user accepted by the AUTH() delegate. Returns: `Object` `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`. Example: Read it ```js function dashboard($) { $.json({ name: $.user.name }); } ``` ### $.user Type: `property` The user of the request inside an action. Returns: `Object` Taken from the controller that called the action, or from `ACTION().user(obj)` when you call an action from code. Example: Owner filter ```js action: function($) { DATA.find('tbl_order').where('userid', $.user.id).callback($); } ``` ### controller.authorize([callback]) Type: `method` Runs the AUTH() delegate on demand. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `callback` | `Function` | no | | `function(err, user)`. | Returns: `Promise` When `callback` is not given. Sets `controller.user` when the delegate accepts the request. Without `callback` it returns a `Promise` that resolves with the user or `undefined`; it never rejects. Example: Inside a route ```js async function detail($) { var user = await $.authorize(); $.json({ logged: !!user }); } ``` ### controller.session Type: `property` The built-in session of the request. Returns: `Object` Set by `AUTH(options)`: `{ sessionid, userid, data, ua, expire }`. `controller.sessionid` holds the session ID and `$.sessionid` reads it in actions. Example: Session ID ```js function info($) { $.json({ sessionid: $.sessionid }); } ``` ### UNAUTHORIZED($, [permission1], [permission2], [...]) Type: `method` Checks the permissions of the user and responds with 401 when they are missing. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `$` | `Object` | yes | | The `$` of an action or a controller. | | `permission` | `String` | no | | One or more permission names; any of them is enough. | Returns: `Boolean` `true` when the user is not allowed and the request was answered. Returns `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. Example: Guard an action ```js action: function($) { if (UNAUTHORIZED($, 'orders')) return; $.success(); } ``` ### $.unauthorized([permission1], [permission2], [...]) Type: `method` UNAUTHORIZED() for the current $. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `permission` | `String` | no | | One or more permission names. | Returns: `Boolean` `true` when the user is not allowed. The same check with `$` taken from the action. Example: Short form ```js if ($.unauthorized('orders')) return; ``` ### user.permissions Type: `property` The permissions of the user, read by UNAUTHORIZED() and the permissions of actions. Returns: `Array|Object` An array of names or an object with names as keys. `user.roles` is used when `permissions` is missing. Example: Accept with roles ```js $.success({ id: '1', name: 'Anna', roles: ['orders', 'products'] }); ``` ### user.sa Type: `property` Marks a super admin. Returns: `Boolean` A user with `sa` or `su` passes `UNAUTHORIZED()`, action `permissions` and is the only user allowed by actions with `sa: true`. Example: Admin ```js $.success({ id: '1', name: 'Root', sa: true }); ``` ### new User([obj]) Type: `class` A class for user objects. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `obj` | `Object` | no | | The keys of the user. | Returns: `User` A 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. Example: A user for a job ```js NEWACTION('reports_daily', { sa: true, action: function($) { $.success($.user.name); } }); var scheduler = new User({ id: 'cron', name: 'Scheduler', sa: true }); ACTION('reports_daily').user(scheduler).callback(console.log); // { success: true, value: 'Scheduler' } ``` ### NEWACTION({ user: true }) Type: `config` Limits an action to authorized (true) or unauthorized (false) requests. When the condition fails, the action responds with `401`. Example: Only users ```js NEWACTION({ id: 'Account/profile', user: true, action: function($) { $.success($.user); } }); ``` ### NEWACTION({ sa: true }) Type: `config` Limits an action to super admins. The user must have `sa` or `su`, otherwise the action responds with `401`. `su: true` works the same. Example: Admin action ```js NEWACTION({ id: 'Users/remove', sa: true, params: '*id:UID', action: function($) { $.success(); } }); ``` ### NEWACTION({ permissions: 'name1,name2' }) Type: `config` Limits an action to users with any of the permissions. A string separated by commas or semicolons, or an array. The check is `UNAUTHORIZED()`, so super admins always pass. Example: Permissions ```js NEWACTION({ id: 'Orders/list', permissions: 'orders,admin', action: function($) { $.success([]); } }); ``` ### BLOCKED($, [limit], [expire]) Type: `method` Counts attempts per IP address and tells when the address is blocked. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `$` | `Object` | yes | | The `$` of an action or a controller. | | `limit` | `Number|null` | no | `5` | Allowed attempts; `null` or `-1` resets the counter. | | `expire` | `String` | no | `'15 minutes'` | How long the counter lives. | Returns: `Boolean` `true` when blocked. Each 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. Example: Login guard ```js if (BLOCKED($, 10)) { $.invalid(401); return; } // ... the password is correct BLOCKED($, null); ``` --- title: Encryption project: Total.js V5 version: 0.0.20 section: reference language: en license: MIT url: https://totaljs.es/docs/total-js-v5/0-0-20/reference/encryption/ updated: 2026-11-18T16:57:19.575Z --- # Encryption > ENCRYPT(), DECRYPT(), ENCRYPTREQ(), DECRYPTREQ() and the keys $crypto, $cryptoiv and secret. The 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. ## API ### ENCRYPT(value, key, [unique]) Type: `method` Encrypts a value into a string. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `value` | `Object` | yes | | Any JSON-serializable value. | | `key` | `String` | yes | | A key that must also be used to decrypt. | | `unique` | `Boolean` | no | | A random output for the same input. | Returns: `String` The encrypted value. `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. Example: Reset link ```js var token = ENCRYPT({ id: user.id, expire: NOW.add('1 day') }, 'reset'); $.success(token); ``` ### DECRYPT(value, key, [tojson]) Type: `method` Decrypts a string made by ENCRYPT(). | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `value` | `String` | yes | | The encrypted string. | | `key` | `String` | yes | | The key used by `ENCRYPT()`. | | `tojson` | `Boolean` | no | `true` | Parse the result as JSON. | Returns: `Object|String` The value, or `null`. Decrypts 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. Example: Verify a token ```js var data = DECRYPT($.query.token, 'reset'); if (!data || data.expire < NOW) { $.invalid(400); return; } ``` ### ENCRYPTREQ($, value, key, [strict]) Type: `method` Encrypts a value bound to the client of the request. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `$` | `Object` | yes | | The `$` of an action or a controller. | | `value` | `Object` | yes | | Any JSON-serializable value. | | `key` | `String` | yes | | The key. | | `strict` | `Boolean` | no | | Bind the value to the IP address too. | Returns: `String` The encrypted value. Stores 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. Example: Download token ```js var token = ENCRYPTREQ($, { file: model.id }, 'download', true); $.success(token); ``` ### DECRYPTREQ($, value, key) Type: `method` Decrypts a value made by ENCRYPTREQ() for the same client. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `$` | `Object` | yes | | The `$` of an action or a controller. | | `value` | `String` | yes | | The encrypted string. | | `key` | `String` | yes | | The key used by `ENCRYPTREQ()`. | Returns: `Object` The value, or `undefined`. Returns `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. Example: Check the token ```js var data = DECRYPTREQ($, $.query.token, 'download'); if (!data) { $.invalid(401); return; } ``` ### $crypto : aes-256-cbc Type: `config` A Node.js cipher for ENCRYPT() and DECRYPT(). Returns: `String` Any 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`). Example: Config ```js // /config $crypto : aes-256-cbc $cryptoiv : 00112233445566778899aabbccddeeff ``` ### $cryptoiv : <hex or base64> Type: `config` The initialization vector for $crypto. Returns: `Buffer` Read as base64 when it contains upper-case letters, `=`, `/` or `+`, otherwise as hex. The default is the first 16 bytes of the application hash. Example: Config ```js $cryptoiv : 00112233445566778899aabbccddeeff ``` ### secret : <string> Type: `config` The application secret used by ENCRYPT() and DECRYPT(). Returns: `String` It 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. Example: Config ```js secret : a-long-random-string ``` --- title: Audit logs project: Total.js V5 version: 0.0.20 section: reference language: en license: MIT url: https://totaljs.es/docs/total-js-v5/0-0-20/reference/audit-logs/ updated: 2026-11-18T16:57:19.575Z --- # Audit logs > AUDIT(), $.audit(), DEF.onAudit and the audit option of NEWACTION(). The 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. ## API ### AUDIT([name], $, [message], [type]) Type: `method` Writes an audit record about the request. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `name` | `String` | no | `'audit'` | The log name. | | `$` | `Object` | yes | | The `$` of an action or a controller. | | `message` | `String` | no | | A message. | | `type` | `String` | no | | A type, for example `info` or `warning`. | Returns: `undefined` Builds 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. Example: Log a removal ```js AUDIT('orders', $, 'Order removed', 'warning'); ``` ### $.audit([message], [type]) Type: `method` AUDIT() for the current $ with variables in the message. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `message` | `String` | no | | A message with optional variables. | | `type` | `String` | no | | A type. | Returns: `undefined` The 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`. Example: With variables ```js $.audit('Updated product {model.name} by {user.name}'); ``` ### DEF.onAudit = function(name, data, $) Type: `delegate` Stores audit records. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `name` | `String` | yes | | The log name, or `null`. | | `data` | `Object` | yes | | The record. | | `$` | `Object` | yes | | The request. | The 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. Example: Into a table ```js DEF.onAudit = function(name, data) { data.id = UID(); data.name = name; data.dtcreated = NOW; DATA.insert('tbl_auditlog', data); }; ``` ### NEWACTION({ audit: true }) Type: `config` Audits an action after it succeeds. `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`. Example: Audited action ```js NEWACTION({ id: 'Orders/remove', params: '*id:UID', audit: 'Removed order {{ $.params.id }}', action: function($) { $.success(); } }); ``` ### $tapilogger : true Type: `config` Sends audit records to the Total.js API logger. Returns: `Boolean` Works together with `$tapi` (default `true`) and `secret_totalapi`; then `DEF.onAudit` is not called. Default `false`. Example: Config ```js $tapilogger : true secret_totalapi : your-totalapi-token ``` --- title: Middleware project: Total.js V5 version: 0.0.20 section: reference language: en license: MIT url: https://totaljs.es/docs/total-js-v5/0-0-20/reference/middleware/ updated: 2026-11-18T16:57:14.575Z --- # Middleware > NEWMIDDLEWARE(), the middleware handler, the #name route flag and the middleware option of actions. ## API ### NEWMIDDLEWARE(name, fn, [assign]) Type: `method` Registers a named middleware, or removes it. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `name` | `String` | yes | | Name of the middleware, used as `#name` in routes. Letters, digits and `_`. | | `fn` | `Function` | no | | `function($, next)`. Without it, the middleware is removed. | | `assign` | `String|Array` | no | | `routes`, `dynamic` or `websockets`, separated by commas. | Returns: `undefined` The 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. `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. Called with only `name`, it removes the middleware from the registry and from every route. Example: API key check ```js NEWMIDDLEWARE('apikey', function($, next) { if ($.headers['x-api-key'] === CONF.apikey) next(); else $.invalid(401); }); ROUTE('GET /api/orders/ #apikey', function($) { $.json([]); }); ``` Example: Remove a middleware ```js NEWMIDDLEWARE('apikey'); ``` ### MIDDLEWARE(name, fn, [assign]) Type: `method` The same function as `NEWMIDDLEWARE()`. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `name` | `String` | yes | | Name of the middleware. | | `fn` | `Function` | no | | `function($, next)`. Without it, the middleware is removed. | | `assign` | `String|Array` | no | | `routes`, `dynamic` or `websockets`. | Returns: `undefined` `MIDDLEWARE` and `NEWMIDDLEWARE` are two names for one function; the arguments and the behaviour are the same. Example: Register ```js MIDDLEWARE('timing', function($, next) { $.started = Date.now(); next(); }); ``` ### function($, next) Type: `delegate` The function of a middleware. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `$` | `Controller|Options` | yes | | The controller of the request, or the action's `$`. | | `next` | `Function` | yes | | Continues with the next middleware or the action. | It 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)`. For HTTP routes, the body, the query, the URL parameters and `$.user` are already set when the middleware runs. Example: Redirect anonymous users ```js NEWMIDDLEWARE('login', function($, next) { if ($.user) next(); else $.redirect('/login/'); }); ``` ### ROUTE('METHOD /url/ #name', action) Type: `property` Lists a middleware in a route declaration. Each `#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. Example: Two middleware ```js ROUTE('POST /api/upload/ #apikey #ratelimit', upload); ROUTE('SOCKET /live/ #apikey', live); ``` ### NEWACTION({ middleware: 'name1, name2' }) Type: `property` Middleware that runs before an action. The `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. Example: Action with middleware ```js NEWACTION({ name: 'Orders/list', middleware: 'tenant', action: function($) { $.callback([]); } }); ``` ### middleware/*.js Type: `type` Folder with files that register middleware. `.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. Example: middleware/auth.js ```js exports.install = function() { NEWMIDDLEWARE('admin', function($, next) { if ($.user && $.user.sa) next(); else $.invalid(401); }); }; ``` --- title: Static files project: Total.js V5 version: 0.0.20 section: reference language: en license: MIT url: https://totaljs.es/docs/total-js-v5/0-0-20/reference/static-files/ updated: 2026-11-18T16:57:14.575Z --- # Static files > The public folder, cache headers, compression, ranges, MERGE(), TOUCH() and their configuration. ## API ### public/ Type: `type` The folder of static files. A 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. Example: Structure ```text public/ css/default.css js/app.js img/logo.png favicon.ico manifest.webmanifest ``` ### /_<plugin>/<path> Type: `type` URLs that read static files from a plugin. A 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. Example: Link a plugin file ```html <link rel="stylesheet" href="/_shop/css/shop.css" /> ``` ### *.min.js, *-min.css, *@min.js Type: `type` Files that are sent without minification. A `.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. Example: Sent unchanged ```text /js/jquery.min.js /css/bootstrap-min.css /js/spa@min.js ``` ### Expires, Cache-Control, Last-Modified, ETag Type: `type` HTTP cache headers of static files. Static 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`. `.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`. Example: Response headers ```text Cache-Control: public, must-revalidate, max-age=60 Last-Modified: Mon, 02 Nov 2026 10:00:00 GMT ETag: 858100 ``` ### Content-Encoding: gzip Type: `type` Gzip compression of static files. With `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. ### Range: bytes=<start>-<end> Type: `type` Partial responses for large files. A 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. Example: Request ```text GET /video/intro.mp4 Range: bytes=0- ``` ### application/manifest+json Type: `type` Web app manifest files. `webmanifest` is in the default `CONF.$httpfiles`, so `public/manifest.webmanifest` is served with the content type `application/manifest+json`. Example: Link the manifest ```html <link rel="manifest" href="/manifest.webmanifest" /> ``` ### $.resume() Type: `method` Sends the static file of the request the normal way. In 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. Example: Check before sending ```js ROUTE('FILE /docs/*.pdf', function($) { if ($.query.key === CONF.docskey) $.resume(); else $.fallback(401); }); ``` ### $.notmodified(date) Type: `method` Answers 304 when the browser already has this version. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `date` | `String` | yes | | A UTC date string, the same value you send in `Last-Modified`. | Returns: `Boolean` `true` when the 304 response was sent. Compares `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. Example: Cache a generated file ```js ROUTE('GET /feed/', function($) { var date = MAIN.feeddate.toUTCString(); if ($.notmodified(date)) return; $.httpcache(date); $.plain(MAIN.feed); }); ``` ### $.httpcache(date) Type: `method` Adds the static cache headers to the response. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `date` | `Date|String` | yes | | The date of the content. | Sets `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. Example: Generated content ```js $.httpcache(new Date(2026, 0, 1)); $.plain('Hello'); ``` ### TOUCH([url]) Type: `method` Clears the cached state of static files. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `url` | `String` | no | | URL of the file, for example `/css/default.css`. | Removes 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. Example: After writing a file ```js Total.Fs.writeFile(PATH.public('css/theme.css'), css, function() { TOUCH('/css/theme.css'); }); ``` ### MERGE(url, file1, [file2], [...]) Type: `method` Creates a virtual file made of several files. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `url` | `String` | yes | | The URL of the merged file, for example `/css/all.css`. | | `files` | `String|Array` | yes | | Files to merge, as more arguments. | Returns: `String` The URL of the merged file. Registers `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. Example: CSS and JS bundles ```js exports.install = function() { MERGE('/css/all.css', 'bootstrap.min.css + default.css'); MERGE('/js/all.js', '/js/app.js + /js/forms.js'); }; ``` ### LOCALIZE(fn) Type: `method` Sets the delegate that picks the language of a request. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `fn` | `Function` | yes | | `function($)` that returns the language. | `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/). Example: Language from the header ```js LOCALIZE(function($) { return ($.headers['accept-language'] || 'en').substring(0, 2); }); ``` ### PATH.public([path]) Type: `method` Returns the path of a file in the public folder. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `path` | `String` | no | | Relative path. | Returns: `String` Absolute path. Joins `path` to the `public/` folder (or `CONF.$dirpublic`). Without `path`, it returns the folder. Example: Write a public file ```js Total.Fs.writeFile(PATH.public('robots.txt'), 'User-agent: *', NOOP); ``` ### $dirpublic Type: `config` Folder of static files. Returns: `String` An absolute path to use instead of `public/` in the app folder. Default: `'' (public/)`. Example: Config file ```text $dirpublic : /www/static ``` ### $httpfiles Type: `config` Extensions served as static files. Returns: `Object` In 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`. Default: `a list of common web types`. Example: Config file ```text $httpfiles : avif, glb ``` ### $httpcompress Type: `config` Gzip compression of responses. Returns: `Boolean` When on, text static files and text responses are compressed for clients that accept gzip. Default: `true`. Example: Config file ```text $httpcompress : false ``` ### $httpmaxage Type: `config` The max-age of static files, in seconds. Returns: `Number` Used in `Cache-Control: public, must-revalidate, max-age=<value>`. After this time the browser asks again and usually gets 304. Default: `60`. Example: Config file ```text $httpmaxage : 300 ``` ### CONF.$httpexpire Type: `config` The Expires header of static files. Returns: `String` A UTC date one year ahead. Total.js sets it at start and refreshes it every hour; do not set it in the config file. ### $httpetag Type: `config` Suffix of the ETag header. Returns: `String` The 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. Default: `'' (from version)`. Example: Config file ```text $httpetag : build42 ``` ### $httprangebuffer Type: `config` Maximum size of an open range, in kB. Returns: `Number` For a `Range` header without an end, this many kB are sent. Default: `5120`. Example: Config file ```text $httprangebuffer : 10240 ``` ### $minifyjs Type: `config` Minifies JavaScript files. Returns: `Boolean` Minifies static `.js` files, files sent with `$.file()` and merged files. Files with `.min`, `-min` or `@min` are not minified. Default: `true`. Example: Config file ```text $minifyjs : false ``` ### $minifycss Type: `config` Minifies CSS files. Returns: `Boolean` Minifies static `.css` files, files sent with `$.file()` and merged files. Default: `true`. Example: Config file ```text $minifycss : false ``` ### $minifyhtml Type: `config` Minifies HTML. Returns: `Boolean` Minifies static `.html` files and HTML responses. Default: `true`. Example: Config file ```text $minifyhtml : false ``` ### $root Type: `config` Root path of the app. Returns: `String` When 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/). Default: `''`. Example: Config file ```text $root : /app/ ``` ### $httpcacheoffset Type: `config` · Since: `0.0.16` Moves the Last-Modified date of static files. Returns: `String` A time such as `1 minute` added to the file date in the `Last-Modified` header of static files. See [Configuration](../../guides/configuration/). Default: `''`. Example: Config file ```text $httpcacheoffset : 1 minute ``` --- title: WebSockets project: Total.js V5 version: 0.0.20 section: reference language: en license: MIT url: https://totaljs.es/docs/total-js-v5/0-0-20/reference/websockets/ updated: 2026-11-19T16:17:12.159Z --- # WebSockets > The WebSocket object, its clients, WEBSOCKETCLIENT() and the WebSocket configuration. Methods, 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/). ## API ### ROUTE('SOCKET /url/ [@flags] [#middleware] [<size]', action, [size]) Type: `method` Registers a WebSocket route. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `url` | `String` | yes | | Method, path, flags and middleware | | `action` | `Function` | yes | | Called with the WebSocket object | | `size` | `Number` | no | `CONF.$wsmaxsize * 1024` | Max. size of one message in bytes | Returns: `Route` The registered route The 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. Example: Chat room ```js exports.install = function() { ROUTE('SOCKET /room/{name}/', room); }; function room() { var self = this; self.on('message', function(client, message) { self.send(message); }); } ``` Example: Authorized users, text messages, 1 MB ```js ROUTE('+SOCKET /console/ @text <1MB', terminal); ``` Example: Binary messages ```js ROUTE('SOCKET /files/ @binary', function($) { $.on('message', function(client, buffer) { client.send(buffer); // a binary frame back }); }); ``` ### CONF.$wsmaxsize Type: `config` Default max. size of a WebSocket message in kB. Returns: `Number` Default `256`. A larger message closes the client with code `1009`. A route can set its own size. Example: config file ```js $wsmaxsize : 512 ``` ### CONF.$wscompress Type: `config` Allows `permessage-deflate` compression. Returns: `Boolean` Default `true`. When the browser offers `permessage-deflate`, messages are compressed in both directions. Example: Disable compression ```js $wscompress : false ``` ### CONF.$wsencodedecode Type: `config` Encodes and decodes all WebSocket messages with URI encoding. Returns: `Boolean` Default `false`. With `true`, outgoing messages and close reasons go through `encodeURIComponent()` and incoming ones through `decodeURIComponent()`. The other side must do the same. Example: config file ```js $wsencodedecode : true ``` ### CONF.$wsmaxlatency Type: `config` Max. latency in ms before the ping check closes a client. Returns: `Number` Default `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. Example: config file ```js $wsmaxlatency : 5000 ``` ### function() { var websocket = this; } Type: `class` The object that groups all clients of one WebSocket URL. Returns: `WebSocket` It 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`). Example: Events ```js function live() { var self = this; self.on('open', function(client) {}); self.on('message', function(client, message) {}); self.on('close', function(client) {}); } ``` ### websocket.online Type: `property` The number of connected clients. Returns: `Number` Example: Count ```js self.on('open', function() { self.send({ type: 'online', count: self.online }); }); ``` ### websocket.connections Type: `property` The connected clients as an object `{ id: client }`. Returns: `Object` Example: Iterate ```js for (var id in self.connections) { var client = self.connections[id]; } ``` ### websocket.params Type: `property` The dynamic parameters of the URL. Returns: `Object` Filled from the first client of the URL; all clients of the object share the same values. Example: Room name ```js ROUTE('SOCKET /room/{name}/', function() { var name = this.params.name; }); ``` ### websocket.url Type: `property` The URL of the group in lower case. Returns: `String` ### websocket.send(message, [comparer], [replacer], [params]) Type: `method` Sends a message to all clients, or to the clients chosen by a comparer. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `message` | `Object|String|Buffer` | yes | | The message | | `comparer` | `Function` | no | | `function(client, message, params)` returning a boolean | | `replacer` | `Function` | no | | A JSON replacer | | `params` | `Object` | no | | Passed to the comparer | Returns: `WebSocket` The same object The 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`. Example: Everyone ```js self.send({ type: 'refresh' }); ``` Example: Only admins ```js self.send({ type: 'alert' }, function(client) { return client.user && client.user.isadmin; }); ``` ### websocket.find(fn) Type: `method` Finds the first client for which `fn(client)` returns `true`. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `fn` | `Function` | yes | | `function(client)` returning a boolean | Returns: `Controller` The client, or `undefined` Example: By user ```js var client = self.find(function(client) { return client.user && client.user.id === id; }); ``` ### websocket.close([code], [message]) Type: `method` Closes all clients. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `code` | `Number` | no | `1000` | The close code | | `message` | `String` | no | | The close reason | Returns: `WebSocket` The WebSocket object stays, so new clients can connect. Example: Close everyone ```js self.close(4000, 'Maintenance'); ``` ### websocket.destroy() Type: `method` Closes all clients and removes the WebSocket object. Emits `destroy`. The next client that connects to the URL runs the route action again and gets a new object. Example: Destroy ```js self.destroy(); ``` ### websocket.autodestroy([callback]) Type: `method` Destroys the object 5 seconds after the last client leaves. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `callback` | `Function` | no | | Called before the object is destroyed | Returns: `WebSocket` If 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. Example: Stop a timer ```js var timer = setInterval(function() { self.send({ ts: Date.now() }); }, 1000); self.autodestroy(function() { clearInterval(timer); }); ``` ### websocket.encrypt([enable]) Type: `method` Encrypts and decrypts all messages of the group with `CONF.secret_encryption`. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `enable` | `Boolean` | no | `true` | | With no argument or `true` it enables encryption; `false` disables it. It does nothing while `CONF.secret_encryption` is empty. Example: Enable ```js function secure() { this.encrypt(); } ``` ### websocket.ping() Type: `method` Pings all clients. Returns: `WebSocket` Each pong sets `client.latency`. The framework calls it three times a minute (15, 30 and 60 seconds into each minute) for all WebSocket objects. Example: Ping now ```js self.ping(); ``` ### websocket.error(err) Type: `method` Logs an error with the URL of the WebSocket. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `err` | `Error|String` | yes | | | A string is converted to an `Error`. The error goes to the framework error log. Example: Log ```js self.on('message', function(client, message) { if (!message.type) self.error('Missing type'); }); ``` ### websocket.on('open', function(client) {}) Type: `event` A client has connected. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `client` | `Controller` | yes | | The new client | Example: Welcome ```js self.on('open', function(client) { client.send({ type: 'welcome' }); }); ``` ### websocket.on('message', function(client, message, size) {}) Type: `event` A client has sent a message. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `client` | `Controller` | yes | | | | `message` | `Object|String|Buffer` | yes | | | | `size` | `Number` | yes | | | On `@json` routes `message` is a parsed object; on `@text` routes a string; on `@binary` routes a `Buffer`. `size` is the size in bytes. Example: Echo ```js self.on('message', function(client, message) { client.send(message); }); ``` ### websocket.on('close', function(client, code, message) {}) Type: `event` A client has disconnected. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `client` | `Controller` | yes | | | | `code` | `Number` | yes | | | | `message` | `String` | yes | | | `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. Example: Left ```js self.on('close', function(client) { self.send({ type: 'left', id: client.id }); }); ``` ### websocket.on('error', function(err, client) {}) Type: `event` An error on a client socket. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `err` | `Error` | yes | | | | `client` | `Controller` | yes | | | Connection 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. Example: Log ```js self.on('error', function(err, client) { self.error(err); }); ``` ### websocket.on('destroy', function() {}) Type: `event` The WebSocket object is being destroyed. Emitted by `destroy()` and `autodestroy()`. Example: Cleanup ```js self.on('destroy', function() { clearInterval(timer); }); ``` ### ON('websocket_end', function(websocket, client) {}) Type: `event` Any client of any WebSocket route has disconnected. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `websocket` | `WebSocket` | yes | | | | `client` | `Controller` | yes | | | Example: Global log ```js ON('websocket_end', function(websocket, client) { console.log(websocket.url, client.ip); }); ``` ### client Type: `class` One connected client of a WebSocket route. Clients 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. Example: Own data ```js self.on('open', function(client) { client.nick = client.query.nick || 'guest'; }); ``` ### client.id Type: `property` A unique identifier of the client. Returns: `String` Also `client.ID`. It is the key in `websocket.connections`. Example: Send id ```js client.send({ id: client.id }); ``` ### client.user Type: `property` The user returned by the authorization delegate. Returns: `Object` `undefined` for anonymous clients. Example: Greet ```js self.on('open', function(client) { client.send({ name: client.user ? client.user.name : 'guest' }); }); ``` ### client.ip Type: `property` The IP address of the client. Returns: `String` The first address of `X-Forwarded-For` behind a proxy. ### client.query Type: `property` The query string of the WebSocket URL as an object. Returns: `Object` Use it to pass data that browsers cannot send in headers, such as a token. Example: Token ```js // new WebSocket('ws://localhost:8000/live/?token=abc') var token = client.query.token; ``` ### client.params Type: `property` The dynamic parameters of the URL. Returns: `Object` ### client.headers Type: `property` The headers of the upgrade request, with lower-case names. Returns: `Object` ### client.latency Type: `property` The time in ms between the last ping and its pong. Returns: `Number` Each ping resets it to `null`; the pong sets the measured time. Example: Show latency ```js self.on('message', function(client) { client.send({ latency: client.latency }); }); ``` ### client.address Type: `property` The full URL the client connected to. Returns: `String` The protocol (`http` or `https`), the host and the path with the query string. ### client.ua Type: `property` A short name of the browser and system, parsed from `User-Agent`. Returns: `String` `client.mobile` and `client.robot` are `true` for mobile devices and crawlers. ### client.send(message, [raw], [replacer]) Type: `method` Sends a message to one client. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `message` | `Object|String|Buffer` | yes | | | | `raw` | `Boolean` | no | `false` | Send a string without JSON serialization (`@text` routes) | | `replacer` | `Function` | no | | A JSON replacer | On `@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()`. Example: JSON ```js client.send({ type: 'pong' }); ``` Example: Plain text ```js client.send('OK', true); ``` ### client.close([code], [message]) Type: `method` Closes the connection with the client. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `code` | `Number` | no | `1000` | The close code | | `message` | `String` | no | | The close reason | The close frame is sent after 1 second and then the socket is destroyed. Example: Reject ```js self.on('open', function(client) { if (!client.query.token) client.close(4003, 'Forbidden'); }); ``` ### client.ping() Type: `method` Sends a ping to the client. Returns: `Controller` The same client The pong sets `client.latency`. ### client.cookie(name) Type: `method` Reads a cookie of the upgrade request. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `name` | `String` | yes | | | Returns: `String` The decoded value, or an empty string Example: Session ```js var sid = client.cookie('sid'); ``` ### client.hostname([path]) Type: `method` Returns the protocol and host of the request, with an optional path. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `path` | `String` | no | | Appended to the host | Returns: `String` For example `https://example.com/path/` ### client.destroy() Type: `method` Destroys the socket immediately, without a close frame. ### WEBSOCKETCLIENT([callback]) Type: `method` Creates a WebSocket client that connects to another server. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `callback` | `Function` | no | | `function(client)` | Returns: `WebSocketClient` The client `callback(client)` is called at once with the new client. Set the options, headers and events, then call `client.connect()`. Example: Connect ```js WEBSOCKETCLIENT(function(client) { client.on('open', function() { client.send({ type: 'hello' }); }); client.on('message', function(message) { console.log(message); }); client.connect('ws://127.0.0.1:8000/live/'); }); ``` ### wsclient.connect(url, [protocol], [origin]) Type: `method` Opens the connection. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `url` | `String|Object` | yes | | | | `protocol` | `String` | no | | | | `origin` | `String` | no | | | `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. Example: Secure ```js client.connect('wss://example.com/live/'); ``` ### wsclient.options Type: `property` The options of the client. Returns: `Object` Set 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. Example: Text client ```js var client = WEBSOCKETCLIENT(); client.options.type = 'text'; client.options.reconnect = 0; client.connect('ws://127.0.0.1:8000/terminal/'); ``` ### wsclient.headers Type: `property` Extra headers of the upgrade request. Returns: `Object` Set them before `connect()`. Example: Token ```js client.headers['x-token'] = 'secret'; ``` ### wsclient.send(message, [raw], [replacer]) Type: `method` Sends a message to the server. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `message` | `Object|String|Buffer` | yes | | | | `raw` | `Boolean` | no | `false` | Send a prepared JSON string | | `replacer` | `Function` | no | | A JSON replacer | Returns: `Boolean` `true` when the message was written With 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. Example: Send ```js client.send({ type: 'subscribe', channel: 'news' }); ``` ### wsclient.sendcustom(type, message) Type: `method` Sends one message as text or binary, regardless of `options.type`. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `type` | `String` | yes | | `binary` or `text` | | `message` | `String|Buffer` | yes | | | Returns: `Boolean` `true` when the message was written `type` is `'binary'` or any other value for text. Example: Binary ```js client.sendcustom('binary', Buffer.from([1, 2, 3])); ``` ### wsclient.close([code], [message]) Type: `method` Closes the connection. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `code` | `Number` | no | `1000` | | | `message` | `String|Boolean` | no | | The close reason, or `true` | Returns: `WebSocketClient` It stops reconnecting. Pass `true` as `message` to close the connection and keep the automatic reconnection. Example: Close ```js client.close(); ``` ### wsclient.destroy() Type: `method` Destroys the connection and stops reconnecting. Emits `destroy`. Example: Destroy ```js client.destroy(); ``` ### wsclient.ping([timeout]) Type: `method` Sends a ping and waits for the pong. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `timeout` | `Number` | no | `3000` | Time in ms | Returns: `WebSocketClient` The 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. Example: Keep checking ```js setInterval(function() { client.ping(5000); }, 30000); ``` ### wsclient.api(schema, [data], [callback], [timeout]) Type: `method` Sends an API request over the connection and waits for the answer. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `schema` | `String` | yes | | | | `data` | `Object` | no | | | | `callback` | `Function` | no | | `function(err, response)` | | `timeout` | `Number` | no | `5000` | Time in ms | Returns: `Promise` When no callback is given Sends `{ 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. Example: Promise ```js var response = await client.api('users_list', { page: 1 }); ``` ### wsclient.on('message', function(message, size) {}) Type: `event` A message from the server. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `message` | `Object|String|Buffer` | yes | | | | `size` | `Number` | yes | | | A parsed object with type `json`, a string with `text`, a `Buffer` with `binary`. ### wsclient.on('open', function() {}) Type: `event` The connection is open. Also emitted after each reconnection. ### wsclient.on('close', function(code, message) {}) Type: `event` The connection was closed. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `code` | `Number` | yes | | | | `message` | `String` | yes | | | ### wsclient.on('error', function(err) {}) Type: `event` A connection error, an unexpected HTTP response, an invalid server key or a ping timeout. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `err` | `Error` | yes | | | Example: Log ```js client.on('error', function(err) { console.log('WS error', err.message); }); ``` ### route.remove() Type: `method` · Since: `0.0.17` Removes a route registered with `ROUTE()`. For a `SOCKET` route it removes the route and destroys all its WebSocket objects, so every connected client is disconnected. Example: Remove ```js var route = ROUTE('SOCKET /live/', live); route.remove(); ``` --- title: NoSQL database project: Total.js V5 version: 0.0.20 section: reference language: en license: MIT url: https://totaljs.es/docs/total-js-v5/0-0-20/reference/nosql/ updated: 2026-11-19T16:17:12.159Z --- # NoSQL database > NOSQL(name), its query builder methods and the NoSQL engine of DATA. Methods 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/). ## API ### NOSQL(name) Type: `method` Returns a NoSQL database stored in a text file. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `name` | `String` | yes | | Name of the database, or a file path with a slash. | Returns: `Object` An object with `insert()`, `find()`, `read()`, `update()`, `modify()`, `remove()`, `clear()` and `clean()`. A 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. Example: Use a database ```js var db = NOSQL('users'); db.find().where('active', true).callback(console.log); ``` ### NOSQL(name).insert(doc) Type: `method` Appends a new document. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `doc` | `Object` | yes | | The document. | Returns: `QueryBuilder` Builder; the response is `1`. Adds 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`. Example: Insert ```js NOSQL('users').insert({ id: UID(), name: 'Peter', dtcreated: NOW }).callback(function(err, response) { // response === 1 }); ``` ### NOSQL(name).find() Type: `method` Finds documents. Returns: `QueryBuilder` Builder; the response is an Array. Returns all matching documents as an array, or an empty array. Without `sort()` the most recently written documents come first. Example: Find ```js NOSQL('users').find().where('age', '>', 18).sort('name').take(10).callback(function(err, items) { console.log(items); }); ``` ### NOSQL(name).read() Type: `method` Reads one document. Returns: `QueryBuilder` Builder; the response is an Object or `undefined`. Returns 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. Example: Read by id ```js NOSQL('users').read().id(id).error('Not found').callback($); ``` ### NOSQL(name).update(data) Type: `method` Updates matching documents. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `data` | `Object` | yes | | Fields to write, optionally with a prefix. | Returns: `QueryBuilder` Builder; the response is the count of updated documents. Writes 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. Example: Update ```js NOSQL('products').update({ '+stock': -1, dtupdated: NOW }).id(id).callback(function(err, count) { console.log(count); }); ``` Example: Counters and limits ```js NOSQL('products').update({ '-stock': 1, '*price': 1.1, '>maxorder': 3 }).id(id).callback(console.log); ``` ### NOSQL(name).modify(data) Type: `method` Alias of `update()`. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `data` | `Object` | yes | | Fields to write, optionally with a prefix. | Returns: `QueryBuilder` Builder; the response is the count of updated documents. Writes 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. Example: Modify ```js NOSQL('users').modify({ '!active': 1 }).id(id).callback(console.log); ``` ### NOSQL(name).remove() Type: `method` Removes matching documents. Returns: `QueryBuilder` Builder; the response is the count of removed documents. Marks 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()`. Example: Remove old logs ```js NOSQL('logs').remove().where('dtcreated', '<', NOW.add('-30 days')).callback(console.log); ``` ### NOSQL(name).clear() Type: `method` Deletes all documents. Returns: `QueryBuilder` Builder. Deletes the database file. The next insert creates it again. Example: Clear ```js NOSQL('cache').clear().callback(function(err) { console.log('empty'); }); ``` ### NOSQL(name).clean() Type: `method` Compacts the database file. Returns: `QueryBuilder` Builder. Rewrites the file without the lines of removed documents and of old versions of updated documents. Writes wait until it finishes. Example: Clean once a day ```js ON('service', function(counter) { if (counter % 1440 === 0) NOSQL('logs').clean(); }); ``` ### builder.where(name, [comparer], value) Type: `method` Compares a field with a value. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `name` | `String` | yes | | Field name. | | `comparer` | `String` | no | `'='` | Comparison operator. | | `value` | `Object` | yes | | Value to compare. | Returns: `QueryBuilder` The same builder, for chaining. Comparers: `=` (default), `==`, `<>`, `!=`, `>`, `>=`, `<`, `<=`. `=` compares loosely, so `'5'` matches `5`. The name can be nested (`address.city`). With only one argument it works as `query()`. Example: Where ```js NOSQL('users').find().where('age', '>=', 18).where('address.city', 'Bratislava').callback(console.log); ``` ### builder.query(code) Type: `method` Adds a raw JavaScript condition. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `code` | `String` | yes | | JavaScript expression. | Returns: `QueryBuilder` The same builder, for chaining. The condition can use `doc`, the document. A condition that contains `require` or `global` matches nothing. Never build it from user input. Example: Raw condition ```js NOSQL('orders').find().query('doc.items.length > 2').callback(console.log); ``` ### builder.equal(obj) Type: `method` Adds `where(key, value)` for every key of an object. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `obj` | `Object` | yes | | Fields and values. | Returns: `QueryBuilder` The same builder, for chaining. Each key of the object must equal its value. Example: Equal ```js NOSQL('users').find().equal({ role: 'admin', active: true }).callback(console.log); ``` ### builder.id(id) Type: `method` Filters by the `id` field. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `id` | `String|Array` | yes | | Identifier or identifiers. | Returns: `QueryBuilder` The same builder, for chaining. A value adds `where('id', id)`, an array adds `in('id', id)`. Example: By id ```js NOSQL('users').read().id($.params.id).callback($); ``` ### builder.userid(id) Type: `method` Filters by the `userid` field. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `id` | `String|Array|Object` | yes | | Identifier, identifiers, a user object or `$`. | Returns: `QueryBuilder` The same builder, for chaining. Accepts a string, an array of identifiers, an object with `id`, or `$` (it then uses `$.user.id`). Example: Documents of the user ```js NOSQL('notes').find().userid($).callback($); ``` ### builder.in(name, value, [key]) Type: `method` The field is one of the values. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `name` | `String` | yes | | Field name. | | `value` | `Array` | yes | | Allowed values. | | `key` | `String` | no | | Property to read from objects in `value`. | Returns: `QueryBuilder` The same builder, for chaining. A 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`. Example: In ```js NOSQL('products').find().in('tags', ['usb', 'wireless']).callback(console.log); ``` ### builder.notin(name, value, [key]) Type: `method` The field is none of the values. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `name` | `String` | yes | | Field name. | | `value` | `Array` | yes | | Forbidden values. | | `key` | `String` | no | | Property to read from objects in `value`. | Returns: `QueryBuilder` The same builder, for chaining. The opposite of `in()`, with the same arguments. Example: Not in ```js NOSQL('users').find().notin('role', ['guest', 'banned']).callback(console.log); ``` ### builder.between(name, a, b) Type: `method` The field is between two values, inclusive. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `name` | `String` | yes | | Field name. | | `a` | `Number|Date` | yes | | Lower bound. | | `b` | `Number|Date` | yes | | Upper bound. | Returns: `QueryBuilder` The same builder, for chaining. Works with numbers, strings and dates. Example: Between ```js NOSQL('orders').find().between('price', 10, 100).callback(console.log); ``` ### builder.search(name, value, [where]) Type: `method` Searches text in a field. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `name` | `String` | yes | | Field name. | | `value` | `String` | yes | | Text to find. | | `where` | `String` | no | | `'beg'` or `'end'`. | Returns: `QueryBuilder` The same builder, for chaining. Case-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. Example: Search ```js NOSQL('users').find().search('email', '@example.com', 'end').callback(console.log); ``` ### builder.contains(name) Type: `method` The field has a value. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `name` | `String` | yes | | Field name. | Returns: `QueryBuilder` The same builder, for chaining. Matches a truthy value, or an array with at least one item. Example: Contains ```js NOSQL('users').find().contains('photo').callback(console.log); ``` ### builder.empty(name) Type: `method` The field has no value. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `name` | `String` | yes | | Field name. | Returns: `QueryBuilder` The same builder, for chaining. Matches a missing or falsy value, or an empty array. Example: Empty ```js NOSQL('products').find().empty('tags').callback(console.log); ``` ### builder.or(fn) Type: `method` Joins a group of filters with OR. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `fn` | `Function` | yes | | function(builder) that adds the filters. | Returns: `QueryBuilder` The same builder, for chaining. The function receives the builder (also as `this`); filters added inside it form one group where any of them can match. Example: Or ```js NOSQL('users').find().or(function(builder) { builder.where('role', 'admin'); builder.where('owner', true); }).callback(console.log); ``` ### builder.year(name, [comparer], value) Type: `method` Compares the full year of a Date field. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `name` | `String` | yes | | Date field. | | `comparer` | `String` | no | `'='` | Comparison operator. | | `value` | `Number` | yes | | Value to compare. | Returns: `QueryBuilder` The same builder, for chaining. Documents where the field is not a `Date` do not match. Comparers are the same as in `where()`. Example: Year ```js NOSQL('orders').find().year('dtcreated', 2024).callback(console.log); ``` ### builder.month(name, [comparer], value) Type: `method` Compares the month (1-12) of a Date field. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `name` | `String` | yes | | Date field. | | `comparer` | `String` | no | `'='` | Comparison operator. | | `value` | `Number` | yes | | Value to compare. | Returns: `QueryBuilder` The same builder, for chaining. Documents where the field is not a `Date` do not match. Comparers are the same as in `where()`. Example: Month ```js NOSQL('orders').find().month('dtcreated', '>=', 6).callback(console.log); ``` ### builder.day(name, [comparer], value) Type: `method` Compares the day of the month (1-31) of a Date field. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `name` | `String` | yes | | Date field. | | `comparer` | `String` | no | `'='` | Comparison operator. | | `value` | `Number` | yes | | Value to compare. | Returns: `QueryBuilder` The same builder, for chaining. Documents where the field is not a `Date` do not match. Comparers are the same as in `where()`. Example: Day ```js NOSQL('orders').find().day('dtcreated', 1).callback(console.log); ``` ### builder.fields(fields) Type: `method` Chooses the returned fields. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `fields` | `String` | yes | | Comma-separated field names. | Returns: `QueryBuilder` The same builder, for chaining. A comma-separated list of fields to return, or of fields with `-` to leave out (`'-password,-token'`). Example: Fields ```js NOSQL('users').find().fields('id,name,email').callback(console.log); ``` ### builder.sort(name, [desc]) Type: `method` Sorts the result. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `name` | `String` | yes | | Field name. | | `desc` | `Boolean|String` | no | `false` | `true` or `'desc'` for descending order. | Returns: `QueryBuilder` The same builder, for chaining. Call it more times to sort by more fields. Nested fields work (`address.city`). Without sorting the most recently written documents come first. Example: Sort ```js NOSQL('articles').find().sort('dtcreated', true).sort('title').callback(console.log); ``` ### builder.take(count) Type: `method` Limits the number of documents. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `count` | `Number` | yes | | Maximum count. | Returns: `QueryBuilder` The same builder, for chaining. Reading stops as soon as enough documents are found, unless the result is sorted. Example: Take ```js NOSQL('logs').find().take(50).callback(console.log); ``` ### builder.limit(count) Type: `method` Alias of `take()`. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `count` | `Number` | yes | | Maximum count. | Returns: `QueryBuilder` The same builder, for chaining. Limits the number of documents. Example: Limit ```js NOSQL('logs').find().limit(50).callback(console.log); ``` ### builder.skip(count) Type: `method` Skips documents. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `count` | `Number` | yes | | Count to skip. | Returns: `QueryBuilder` The same builder, for chaining. Skips the first `count` matching documents. Example: Skip ```js NOSQL('logs').find().skip(100).take(50).callback(console.log); ``` ### builder.first() Type: `method` Returns only one document. Returns: `QueryBuilder` The same builder, for chaining. Sets `take(1)` and the response is an object (or `undefined`) instead of an array. Example: First ```js NOSQL('users').find().where('email', email).first().callback(console.log); ``` ### builder.page(page, [limit]) Type: `method` Sets skip from a page number. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `page` | `Number` | yes | | Page number from 1. | | `limit` | `Number` | no | | Documents per page. | Returns: `QueryBuilder` The same builder, for chaining. Page numbers start at 1. `limit` sets `take()`; without it the current `take()` value is used. Example: Page ```js NOSQL('articles').find().sort('dtcreated', true).page(2, 20).callback(console.log); ``` ### builder.paginate(page, limit, [maxlimit]) Type: `method` Sets skip and take from untrusted values. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `page` | `Number|String` | yes | | Page number from 1. | | `limit` | `Number|String` | yes | | Documents per page. | | `maxlimit` | `Number` | no | | Maximum and default limit. | Returns: `QueryBuilder` The same builder, for chaining. Accepts strings (for example from the query string). A page below 1 becomes 1; `limit` is capped at `maxlimit`, and a missing limit uses `maxlimit`. Example: Paginate in an action ```js NOSQL('articles').find().sort('dtcreated', true).paginate($.query.page, $.query.limit, 50).callback($); ``` ### builder.debug() Type: `method` Prints the compiled operation. Returns: `QueryBuilder` The same builder, for chaining. Logs the file, the operation and the compiled filter to the console with the prefix `-- NoSQL -->`. Example: Debug ```js NOSQL('users').find().where('age', '>', 18).debug().callback(console.log); ``` ### builder.callback(fn) Type: `method` Reads the result with a callback. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `fn` | `Function|Object` | yes | | function(err, response), or `$`. | Returns: `QueryBuilder` The same builder, for chaining. `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. Example: Callback ```js NOSQL('users').find().callback(function(err, items) { if (err) return console.error(err); console.log(items.length); }); ``` ### builder.pipe(fn) Type: `method` Alias of `callback()`. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `fn` | `Function|Object` | yes | | function(err, response), or `$`. | Returns: `QueryBuilder` The same builder, for chaining. `fn(err, response)`, or `$`. Example: Pipe ```js NOSQL('users').find().pipe($); ``` ### builder.promise([$]) Type: `method` Returns the result as a Promise. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `$` | `Object` | no | | Options of an action. | Returns: `Promise` Resolves with the response. The Promise resolves with the response. On an error it rejects, or, when `$` is given, the error is sent to `$.invalid()`. Example: Await ```js var items = await NOSQL('users').find().where('active', true).promise($); ``` ### builder.done($, fn, [param]) Type: `method` Calls a function with the response, errors go to `$`. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `$` | `Object` | yes | | Options of an action. | | `fn` | `Function` | yes | | function(response, param). | | `param` | `Object` | no | | A value passed to `fn`. | Returns: `QueryBuilder` The same builder, for chaining. On success `fn(response, param)` is called; an error is sent to `$.invalid()`. Example: Done ```js NOSQL('users').read().id(id).error('Not found').done($, function(user) { $.callback({ name: user.name }); }); ``` ### builder.data(fn) Type: `method` Calls a function only with a response. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `fn` | `Function` | yes | | function(response). | Returns: `QueryBuilder` The same builder, for chaining. `fn(response)` is called only when there is no error. It can be combined with `callback()`. Example: Data ```js NOSQL('users').find().data(function(items) { console.log(items); }); ``` ### builder.fail(fn) Type: `method` Calls a function only with an error. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `fn` | `Function` | yes | | function(err). | Returns: `QueryBuilder` The same builder, for chaining. `fn(err)` is called only when the operation fails. Example: Fail ```js NOSQL('users').read().id(id).error('Not found').fail(function(err) { console.log(err); }); ``` ### builder.error(message, [reverse]) Type: `method` Turns an empty result into an error. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `message` | `String|Number` | yes | | Error message. | | `reverse` | `Boolean` | no | `false` | Fail when the result is not empty. | Returns: `QueryBuilder` The same builder, for chaining. The 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. Example: Not found and duplicate ```js NOSQL('users').read().id(id).error('Not found').callback($); NOSQL('users').read().where('email', email).error('E-mail is already used', true).callback(function(err) { // err when the e-mail exists }); ``` ### DATA.count('nosql/' + name) Type: `method` Counts matching documents. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `name` | `String` | yes | | Database name with the `nosql/` prefix. | Returns: `QueryBuilder` Builder; the response is `{ count }`. Uses the NoSQL engine through the global query builder. The response is an object `{ count: Number }`. Example: Count ```js DATA.count('nosql/users').where('active', true).callback(function(err, response) { console.log(response.count); }); ``` ### DATA.check('nosql/' + name) Type: `method` Checks if a document exists. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `name` | `String` | yes | | Database name with the `nosql/` prefix. | Returns: `QueryBuilder` Builder; the response is a Boolean. Stops at the first matching document. The response is `true` or `false`. Example: Check ```js DATA.check('nosql/users').where('email', email).callback(function(err, exists) { console.log(exists); }); ``` ### DATA.scalar('nosql/' + name, type, key, [key2]) Type: `method` Computes a sum, minimum, maximum, count or groups. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `name` | `String` | yes | | Database name with the `nosql/` prefix. | | `type` | `String` | yes | | `'sum'`, `'min'`, `'max'`, `'avg'`, `'count'` or `'group'`. | | `key` | `String` | no | `'*'` | Field to compute or to group by. `'*'` (the default) counts each document as `1`. | | `key2` | `String` | no | | Field to sum per group (only with `'group'`). | Returns: `QueryBuilder` Builder; the response is `{ value }` or an Array of groups. With `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. Example: Sum ```js DATA.scalar('nosql/orders', 'sum', 'price').where('paid', true).callback(function(err, response) { console.log(response.value); }); ``` Example: Group ```js DATA.scalar('nosql/orders', 'group', 'status').callback(function(err, groups) { // [{ status: 'paid', value: 12 }, { status: 'new', value: 3 }] }); ``` Example: Average and count ```js DATA.scalar('nosql/orders', 'avg', 'price').callback(function(err, response) { console.log(response.value); // the average price }); DATA.scalar('nosql/orders', 'count').where('paid', true).callback(console.log); ``` ### $dirdatabases : String Type: `config` Directory of the database files. Returns: `String` The directory where `NOSQL()` keeps its `.nosql` files. The default is `databases` in the root of the application. Example: config ```text $dirdatabases : /var/data/myapp/ ``` --- title: QueryBuilder project: Total.js V5 version: 0.0.20 section: reference language: en license: MIT url: https://totaljs.es/docs/total-js-v5/0-0-20/reference/querybuilder/ updated: 2026-11-19T20:13:51.296Z --- # QueryBuilder > DATA, DB(), NEWDB() and the methods of the QueryBuilder. The 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/). ## API ### DATA Type: `property` The global database object that starts each query immediately. Returns: `Database` A 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. Example: Find rows ```js DATA.find('users').where('isremoved', false).callback(function(err, response) { console.log(response); }); ``` ### DB() Type: `method` Creates a database object that runs queries in sequence. Returns: `Database` A new database controller. Each 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. Example: Two queries ```js var db = DB(); db.read('users').id('u1').set('user'); db.find('orders').where('userid', 'u1').set('orders'); db.callback(function(err, response) { // response.user, response.orders }); ``` ### NEWDB([name], [fn]) Type: `method` Registers or removes a database adapter. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `name` | `String` | no | `'default'` | The connection name. | | `fn` | `Function` | no | | `function(filter, callback)` that executes the query. Omit it to remove the adapter. | The 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/)). Example: A logging adapter ```js NEWDB('default', function(filter, callback) { console.log(filter.exec, filter.table, filter.filter); callback(null, filter.exec === 'list' ? { items: [], count: 0 } : []); }); ``` ### db.find(table) Type: `method` Finds all rows that match the filter. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `table` | `String` | yes | | The table name. `connection/table` selects a connection; without a slash the connection is `default`. | Returns: `QueryBuilder` Returns a QueryBuilder with the operation `find`. The response is the array that the adapter returns. Alias: `db.all()`. Example: Find ```js DATA.find('products').where('price', '>', 10).sort('name').callback(console.log); ``` ### db.read(table) Type: `method` Reads one row. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `table` | `String` | yes | | The table name. `connection/table` selects a connection; without a slash the connection is `default`. | Returns: `QueryBuilder` Returns 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()`. Example: Read by id ```js DATA.read('users').id('u1').error('@(User not found)').callback(console.log); ``` ### db.list(table) Type: `method` Reads one page of rows with paging metadata. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `table` | `String` | yes | | The table name. `connection/table` selects a connection; without a slash the connection is `default`. | Returns: `QueryBuilder` Returns 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. Example: A page ```js DATA.list('products').page(2, 20).callback(function(err, response) { console.log(response.items, response.count, response.pages); }); ``` ### db.check(table) Type: `method` Checks whether a row exists. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `table` | `String` | yes | | The table name. `connection/table` selects a connection; without a slash the connection is `default`. | Returns: `QueryBuilder` Returns 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`). Example: Unique e-mail ```js DATA.check('users').where('email', model.email).error('@(E-mail already exists)', true).callback($); ``` ### db.count(table) Type: `method` Counts the rows that match the filter. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `table` | `String` | yes | | The table name. `connection/table` selects a connection; without a slash the connection is `default`. | Returns: `QueryBuilder` Returns a QueryBuilder with the operation `count`. The adapter decides the form of the response. Example: Count ```js DATA.count('orders').where('status', 'paid').callback(console.log); ``` ### db.scalar(table, type, [key], [key2]) Type: `method` Computes an aggregate value. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `table` | `String` | yes | | The table name. `connection/table` selects a connection; without a slash the connection is `default`. | | `type` | `String` | yes | | The aggregate, for example `sum`, `avg`, `min`, `max`, `count`. | | `key` | `String` | no | `'*'` | The column. | | `key2` | `String` | no | | A second column to group by `key`. | Returns: `QueryBuilder` Returns 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`). Example: Sum ```js DATA.scalar('orders', 'sum', 'price').where('status', 'paid').callback(console.log); ``` ### db.insert(table, data) Type: `method` Inserts a row. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `table` | `String` | yes | | The table name. `connection/table` selects a connection; without a slash the connection is `default`. | | `data` | `Object` | yes | | The row to insert. | Returns: `QueryBuilder` Returns a QueryBuilder with the operation `insert` and `data` as the payload. Alias: `db.ins()`. Example: Insert ```js DATA.insert('users', { id: UID(), name: 'Peter', dtcreated: NOW }).callback(console.log); ``` ### db.update(table, data, [upsert]) Type: `method` Updates the rows that match the filter. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `table` | `String` | yes | | The table name. `connection/table` selects a connection; without a slash the connection is `default`. | | `data` | `Object` | yes | | The columns to change. | | `upsert` | `Boolean` | no | `false` | Insert the payload when nothing was updated. | Returns: `QueryBuilder` Returns 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()`. Example: Update ```js DATA.update('users', { name: 'Lucia', dtupdated: NOW }).id('u1').error('@(User not found)').callback(console.log); ``` ### db.remove(table) Type: `method` Removes the rows that match the filter. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `table` | `String` | yes | | The table name. `connection/table` selects a connection; without a slash the connection is `default`. | Returns: `QueryBuilder` Returns a QueryBuilder with the operation `remove`. Alias: `db.rem()`. Example: Remove ```js DATA.remove('users').id('u1').callback(console.log); ``` ### db.query([connection], query, [params]) Type: `method` Runs a raw query. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `connection` | `String` | no | `'default'` | The connection name. | | `query` | `String` | yes | | The raw query. | | `params` | `Object|Array` | no | | Parameters for the adapter. | Returns: `QueryBuilder` Returns 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. Example: Raw SQL ```js DATA.query('SELECT id, name FROM tbl_user WHERE isremoved=FALSE').callback(console.log); ``` ### db.truncate(table) Type: `method` Removes all rows of a table. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `table` | `String` | yes | | The table name. `connection/table` selects a connection; without a slash the connection is `default`. | Returns: `QueryBuilder` Returns 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. Example: Truncate ```js DATA.truncate('logs/requests').callback(console.log); ``` ### db.exec(filter, callback) Type: `method` Runs a query described by a plain object. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `filter` | `Object` | yes | | The options, for example `{ exec: 'find', table: 'users', take: 10 }`. | | `callback` | `Function` | yes | | `function(err, response)`. | `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`. Example: Exec ```js DATA.exec({ exec: 'find', table: 'users', take: 5 }, console.log); ``` ### db.load([connection], options) Type: `method` Creates a query from prepared options. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `connection` | `String` | no | `'default'` | The connection name. | | `options` | `Object` | yes | | The prepared options. | Returns: `QueryBuilder` Creates 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`. Example: Load ```js DATA.load({ table: 'users', exec: 'find', take: 10, filter: [{ type: 'where', name: 'isremoved', comparer: '=', value: false }] }).callback(console.log); ``` ### db.language(prefix, skip) Type: `method` Sets the defaults for localized columns. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `prefix` | `String` | yes | | The prefix put before the language code. | | `skip` | `String` | yes | | A language that means "no language". | Returns: `Database` Sets the global prefix and the language to skip that `builder.language()` uses when it gets no own values. The default skipped language is `_`. Example: Defaults ```js DATA.language('_', 'en'); ``` ### db.debug() Type: `method` Sets the debug option on every query of a DB() chain. Returns: `Database` Each query created after this call gets the option `debug = true`, so an adapter that supports it can log the generated query. Example: Debug ```js var db = DB().debug(); db.find('users'); db.callback(console.log); ``` ### db.callback(fn) Type: `method` Sets the callback of a DB() chain. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `fn` | `Function|$` | yes | | `function(err, response)` or the `$` of an action. | Returns: `Database` The callback gets the first error or the final response. Pass `$` of an action instead of a function to answer the action. Alias: `db.pipe()`. Example: Callback ```js var db = DB(); db.read('users').id('u1').set('user'); db.callback($); ``` ### db.promise([$]) Type: `method` Returns a promise of a DB() chain. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `$` | `Object` | no | | The `$` of an action. | Returns: `Promise` The promise resolves with the final response. On error it is rejected, or, with `$`, the error goes to `$.invalid()`. Example: Await ```js var db = DB(); db.read('users').id('u1').set('user'); db.find('orders').where('userid', 'u1').set('orders'); var response = await db.promise($); ``` ### db.done($, fn) Type: `method` Calls fn on success and $.invalid() on error. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `$` | `Object` | yes | | The `$` of an action. | | `fn` | `Function` | no | | `function(response)`. | Returns: `Database` Ends a DB() chain inside an action: an error is passed to `$.invalid()`, a response to `fn(response)`. Example: Done ```js var db = DB(); db.read('users').id($.params.id).set('user'); db.done($, function(response) { $.callback(response.user); }); ``` ### builder.where(name, [comparer], value) Type: `method` Adds a comparison. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `name` | `String` | yes | | The column. | | `comparer` | `String` | no | `'='` | `=`, `<>`, `>`, `<`, `>=`, `<=`. | | `value` | `Object` | yes | | The value. | Returns: `QueryBuilder` The same QueryBuilder, for chaining. Without `comparer` the comparison is `=`. `==` becomes `=` and `!=` becomes `<>`. With only `name`, the argument is a raw condition, the same as `query()`. Example: Where ```js DATA.find('products').where('price', '>=', 10).where('ispublished', true).callback(console.log); ``` ### builder.id(value) Type: `method` Filters by the column id. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `value` | `String|Array` | yes | | An id or a list of ids. | Returns: `QueryBuilder` The same QueryBuilder, for chaining. `where('id', value)`, or `in('id', value)` when the value is an array. Example: Id ```js DATA.read('users').id('u1').callback(console.log); ``` ### builder.userid(value) Type: `method` Filters by the column userid. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `value` | `String|Array|Object` | yes | | An id, a list, a user or `$`. | Returns: `QueryBuilder` The same QueryBuilder, for chaining. Accepts 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`). Example: Rows of the current user ```js DATA.find('orders').userid($).callback($); ``` ### builder.equal(obj) Type: `method` Adds one equality per key. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `obj` | `Object` | yes | | Column names and values. | Returns: `QueryBuilder` The same QueryBuilder, for chaining. Calls `where(key, value)` for every key of the object. Example: Equal ```js DATA.find('users').equal({ role: 'admin', isremoved: false }).callback(console.log); ``` ### builder.in(name, value, [key]) Type: `method` The column is one of the values. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `name` | `String` | yes | | The column. | | `value` | `Array` | yes | | The values. | | `key` | `String` | no | | A property to read from each object of `value`. | Returns: `QueryBuilder` The same QueryBuilder, for chaining. A single value is wrapped in an array. With `key`, `value` is an array of objects and the values are taken from their property `key`. Example: In ```js DATA.find('users').in('id', orders, 'userid').callback(console.log); ``` ### builder.notin(name, value, [key]) Type: `method` The column is none of the values. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `name` | `String` | yes | | The column. | | `value` | `Array` | yes | | The values. | | `key` | `String` | no | | A property to read from each object of `value`. | Returns: `QueryBuilder` The same QueryBuilder, for chaining. The opposite of `in()`, with the same arguments. Example: Not in ```js DATA.find('users').notin('role', ['guest']).callback(console.log); ``` ### builder.between(name, a, b) Type: `method` The column is between two values. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `name` | `String` | yes | | The column. | | `a` | `Object` | yes | | The lower value. | | `b` | `Object` | yes | | The upper value. | Returns: `QueryBuilder` The same QueryBuilder, for chaining. Adds a `between` item with `a` and `b`. Example: Last week ```js DATA.find('orders').between('dtcreated', NOW.add('-7 days'), NOW).callback(console.log); ``` ### builder.search(name, value, [where]) Type: `method` Searches text in a column. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `name` | `String` | yes | | The column. | | `value` | `String` | yes | | The text. | | `where` | `String` | no | | `beg` or `end`. | Returns: `QueryBuilder` The same QueryBuilder, for chaining. The column contains `value`. With `where` set to `beg` the text must be at the beginning, with `end` at the end. Example: Search ```js DATA.find('products').search('name', 'phone').callback(console.log); ``` ### builder.or(fn) Type: `method` Joins a group of conditions with OR. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `fn` | `Function` | yes | | `function(builder)`. | Returns: `QueryBuilder` The same QueryBuilder, for chaining. The filters added inside `fn` form one group. `fn` is called with the builder as `this` and as the argument. An empty group is ignored. Example: Or ```js DATA.find('users').or(function(builder) { builder.where('role', 'admin'); builder.where('role', 'editor'); }).callback(console.log); ``` ### builder.contains(name) Type: `method` The column has a value. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `name` | `String` | yes | | The column. | Returns: `QueryBuilder` The same QueryBuilder, for chaining. Adds a `contains` item: the column is not empty (for arrays: it has items). `empty(name)` is the opposite: the column has no value. Example: Contains ```js DATA.find('users').contains('phone').callback(console.log); ``` ### builder.array(name, [comparer], value) Type: `method` A condition on an array column. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `name` | `String` | yes | | The column. | | `comparer` | `String` | no | `'&&'` | The comparer. | | `value` | `Array|String` | yes | | The values. | Returns: `QueryBuilder` The same QueryBuilder, for chaining. Adds an `array` item. The default comparer is `&&` (the arrays overlap); the adapter interprets it. Example: Tags ```js DATA.find('products').array('tags', ['sale', 'new']).callback(console.log); ``` ### builder.year(name, [comparer], value) Type: `method` Compares a part of a date. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `name` | `String` | yes | | The date column. | | `comparer` | `String` | no | `'='` | The comparer. | | `value` | `Number` | yes | | The value of the part. | Returns: `QueryBuilder` The same QueryBuilder, for chaining. Compares the year of a date column. `month()`, `day()`, `hour()` and `minute()` have the same arguments and compare that part. The default comparer is `=`. Example: Date parts ```js DATA.find('orders').year('dtcreated', 2024).month('dtcreated', '>=', 6).callback(console.log); ``` ### builder.query(value) Type: `method` Adds a raw condition. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `value` | `String` | yes | | The raw condition. | Returns: `QueryBuilder` The same QueryBuilder, for chaining. The text is passed to the adapter as it is, so it must be in the syntax of the engine. Example: Raw ```js DATA.find('users').query('age > 18').callback(console.log); ``` ### builder.join(name, table, type, a, b) Type: `method` Adds a join item for the adapter. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `name` | `String` | yes | | The name of the join. | | `table` | `String` | yes | | The joined table. | | `type` | `String` | yes | | The join type. | | `a` | `String` | yes | | The column of the main table. | | `b` | `String` | yes | | The column of the joined table. | Returns: `QueryBuilder` The same QueryBuilder, for chaining. Adds `{ type: 'join', name, table, join: type, on: [a, b] }` to the filter. Whether joins are supported is up to the adapter. Example: Join ```js DATA.find('orders').join('user', 'users', 'left', 'userid', 'id').callback(console.log); ``` ### builder.permit(name, type, value, [userid], [required]) Type: `method` Adds a permission condition for the adapter. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `name` | `String` | yes | | The column with permissions. | | `type` | `String` | yes | | The letters `R`, `W`, `D`. | | `value` | `Array` | yes | | Roles or groups. | | `userid` | `String` | no | | The id of the user. | | `required` | `Boolean` | no | `true` | The permission is required. | Returns: `QueryBuilder` The same QueryBuilder, for chaining. Each 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`). Example: Permit ```js DATA.find('documents').permit('permissions', 'R', $.user.roles, $.user.id).callback($); ``` ### builder.fields(fields) Type: `method` Selects the columns. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `fields` | `String` | yes | | For example `id,name,email`. | Returns: `QueryBuilder` The same QueryBuilder, for chaining. A comma-separated list of columns. Example: Fields ```js DATA.find('users').fields('id,name,email').callback(console.log); ``` ### builder.gridfields(fields, [allowed]) Type: `method` Selects the columns from an untrusted list. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `fields` | `String` | no | | The requested fields, for example `id,name`. Can be empty or `undefined`. | | `allowed` | `String` | no | | The fields that may be selected, for example `id,name,price`. | Returns: `QueryBuilder` The same QueryBuilder, for chaining. Takes 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. Example: Fields from the query string ```js DATA.find('products').gridfields($.query.fields, 'id,name,price').callback($); ``` ### builder.sort(name, [desc]) Type: `method` Adds a sort column. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `name` | `String` | yes | | The column. | | `desc` | `Boolean|String` | no | `false` | `true` or `desc` for descending. | Returns: `QueryBuilder` The same QueryBuilder, for chaining. `desc` can be `true` or `'desc'`; anything else sorts ascending. Several calls add more columns. Example: Sort ```js DATA.find('products').sort('price', true).sort('name').callback(console.log); ``` ### builder.gridsort(sort, [map]) Type: `method` Adds sort columns from a string. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `sort` | `String` | yes | | The sort string. | | `map` | `Object` | no | | Field names mapped to columns. | Returns: `QueryBuilder` The same QueryBuilder, for chaining. The string has the form `name_asc,dtcreated_desc`; a name without a suffix is ascending. `map` can rename the fields to columns. Example: Gridsort ```js DATA.find('products').gridsort('price_desc,name').callback(console.log); ``` ### builder.take(count) Type: `method` Sets the maximum number of rows. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `count` | `Number` | yes | | The number of rows. | Returns: `QueryBuilder` The same QueryBuilder, for chaining. Alias: `limit()`. `first()` sets `take` to 1 and returns only the first row. `skip(count)` sets the number of rows to skip. Example: Take ```js DATA.find('products').take(10).callback(console.log); ``` ### builder.page(page, [limit]) Type: `method` Selects a page. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `page` | `Number` | yes | | The page, from 1. | | `limit` | `Number` | no | | Rows per page. | Returns: `QueryBuilder` The same QueryBuilder, for chaining. Sets `skip` to `(page - 1) * take`. With `limit` it also sets `take` first. Example: Page ```js DATA.list('products').page(3, 20).callback(console.log); ``` ### builder.paginate(page, limit, [maxlimit]) Type: `method` Selects a page from untrusted values. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `page` | `Number|String` | yes | | The page. | | `limit` | `Number|String` | yes | | Rows per page. | | `maxlimit` | `Number` | no | | The highest allowed limit. | Returns: `QueryBuilder` The same QueryBuilder, for chaining. Converts `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. Example: From a query string ```js DATA.list('products').paginate($.query.page, $.query.limit, 100).callback($); ``` ### builder.autoquery(query, schema, [defsort], [maxlimit]) Type: `method` Builds fields, filters, sort and paging from a query string. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `query` | `Object` | yes | | The query string, usually `$.query`. | | `schema` | `String` | yes | | The allowed fields and types. | | `defsort` | `String` | no | | The default sort, for example `dtcreated_desc`. | | `maxlimit` | `Number` | no | | Enables paging with this highest limit. | Returns: `QueryBuilder` The same QueryBuilder, for chaining. `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. Example: A grid ```js DATA.list('products').autoquery($.query, 'id,name,price:number,dtcreated:date', 'dtcreated_desc', 100).callback($); ``` ### builder.autoqueryjson($, column, schema, [defsort], [maxlimit]) Type: `method` Builds fields, filters, sort and paging for properties of a JSON column. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `$` | `Object` | yes | | The `$` of an action, or the query string. | | `column` | `String` | yes | | The JSON column. | | `schema` | `String` | yes | | The allowed properties and types. | | `defsort` | `String` | no | | The default sort, for example `weight_desc`. | | `maxlimit` | `Number` | no | | Enables paging with this highest limit. | Returns: `QueryBuilder` The same QueryBuilder, for chaining. Works 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. Example: Columns and JSON properties ```js DATA.list('tbl_product').autoquery($.query, 'id,name,price:number', 'name_asc', 100).autoqueryjson($, 'data', 'color,weight:number,waterproof:boolean,released:date').callback($); ``` ### builder.gridfilter(name, query, [type], [column]) Type: `method` Adds a filter from a query string value. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `name` | `String` | yes | | The key in `query`. | | `query` | `Object` | yes | | The query string. | | `type` | `String` | no | `'string'` | The type of the value. | | `column` | `String` | no | | The column, when it differs from `name`. | Returns: `QueryBuilder` The same QueryBuilder, for chaining. Reads `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. Example: Gridfilter ```js DATA.find('orders').gridfilter('price', $.query, 'number').gridfilter('dtcreated', $.query, 'date').callback($); ``` ### builder.language(value, [prefix], [skip]) Type: `method` Sets the language for localized columns. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `value` | `String|Object` | yes | | The language or an object with `language`. | | `prefix` | `String` | no | | The prefix. | | `skip` | `String` | no | | A language that means "no language". | Returns: `QueryBuilder` The same QueryBuilder, for chaining. Sets 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. Example: Language ```js DATA.find('products').fields('id,name§').language($).callback($); ``` ### builder.returning(fields) Type: `method` Asks the adapter to return columns of the changed rows. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `fields` | `String` | yes | | For example `id,name`. | Returns: `QueryBuilder` The same QueryBuilder, for chaining. A comma-separated list stored in the option `returning`. With an upsert, an empty returned result means "nothing was updated". Example: Returning ```js DATA.update('users', { name: 'Lucia' }).id('u1').returning('id,name').callback(console.log); ``` ### builder.insert(fn, [param]) Type: `method` Prepares the payload of an upsert insert. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `fn` | `Function` | yes | | `function(payload, param)`. | | `param` | `Object` | no | | A value passed to `fn`. | Returns: `QueryBuilder` The same QueryBuilder, for chaining. With `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. Example: Upsert ```js DATA.update('stats', { dtupdated: NOW }, true).id('home').insert(function(doc) { doc.id = 'home'; doc.dtcreated = NOW; }).callback(console.log); ``` ### builder.error(message, [reverse]) Type: `method` Turns an empty result into an error. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `message` | `String` | yes | | The error, for example `@(User not found)`. | | `reverse` | `Boolean` | no | `false` | Fail when there is a result. | Returns: `QueryBuilder` The same QueryBuilder, for chaining. When 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()`. Example: Not found ```js DATA.read('users').id($.params.id).error('@(User not found)').callback($); ``` ### builder.callback(fn) Type: `method` Sets the callback of the query. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `fn` | `Function|$` | yes | | `function(err, response)` or `$`. | Returns: `QueryBuilder` The same QueryBuilder, for chaining. `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)`). Example: Callback ```js DATA.find('users').callback(function(err, response) { console.log(err, response); }); ``` ### builder.promise([$]) Type: `method` Returns a promise of the query. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `$` | `Object` | no | | The `$` of an action. | Returns: `Promise` Resolves 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()`. Example: Await ```js var user = await DATA.read('users').id('u1').promise($); ``` ### builder.done($, fn, [param]) Type: `method` Calls fn on success and $.invalid() on error. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `$` | `Object` | yes | | The `$` of an action. | | `fn` | `Function` | yes | | `function(response, param)`. | | `param` | `Object` | no | | A value passed to `fn`. | Returns: `QueryBuilder` The same QueryBuilder, for chaining. On success `fn(response, param)` is called; an error goes to `$.invalid()`. Example: Done ```js DATA.read('users').id($.params.id).done($, function(user) { $.callback({ id: user.id, name: user.name }); }); ``` ### builder.audit($, [message], [type]) Type: `method` Writes an audit record after success. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `$` | `Object` | yes | | The `$` of an action. | | `message` | `String` | no | | The message. | | `type` | `String` | no | | The type of the record. | Returns: `QueryBuilder` The same QueryBuilder, for chaining. After 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. Example: Audit ```js DATA.insert('products', model).audit($, 'Created product {data.name}').callback($); ``` ### builder.set(name) Type: `method` Stores the result under a key of the DB() response. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `name` | `String` | yes | | The key. | Returns: `QueryBuilder` The same QueryBuilder, for chaining. In 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. Example: Set ```js var db = DB(); db.read('users').id('u1').set('user'); db.count('orders').where('userid', 'u1').set('orders'); db.callback($); ``` ### builder.debug() Type: `method` Sets the debug option of the query. Returns: `QueryBuilder` The same QueryBuilder, for chaining. Sets `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. Example: Debug ```js DATA.find('users').debug().callback(console.log); ``` --- title: PostgreSQL project: Total.js V5 version: 0.0.20 section: reference language: en license: MIT url: https://totaljs.es/docs/total-js-v5/0-0-20/reference/postgresql/ updated: 2026-11-19T20:13:56.297Z --- # PostgreSQL > DATA.init(), the connection string, the SQL results and errors, and the PostgreSQL client. `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/). ## API ### DATA.init([name], [connection], [onerror]) Type: `method` Registers a PostgreSQL connection for the QueryBuilder. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `name` | `String` | no | `'default'` | The connection name. | | `connection` | `String` | no | | The connection string: `postgresql://user:password@host:port/database?options`. See the connection string. | | `onerror` | `Function` | no | | `function(message)` called for every failed query. | Registers 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. Example: In definitions/db.js ```js DATA.init('default', CONF.database + '?pooling=10'); ``` Example: A second connection ```js DATA.init('logs', CONF.database_logs); DATA.insert('logs/tbl_request', { url: '/', dtcreated: NOW }).callback(console.log); ``` Example: Own error handling ```js DATA.init('default', CONF.database + '?pooling=10', function(message) { console.log('SQL error:', message); }); ``` ### postgresql://user:password@host:port/database?options Type: `type` The URL of the database and its options. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `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. | | `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. | | `sslmode` | `String` | no | `'disable'` | `disable`, `prefer`, `allow`, `require`, `no-verify`, `verify-ca` or `verify-full`. | | `ssl` | `Boolean` | no | | `true` or `1` is the same as `sslmode=require`. | | `connect_timeout` | `Number` | no | | Seconds to wait for the connection. Then the query fails with `Connection timeout`. | | `application_name` | `String` | no | | The name of the connections in `pg_stat_activity`. | | `host` | `String` | no | | Replaces the host of the URL. A value that starts with `/` is the directory of a Unix socket. | | `port, user, password, dbname` | `String` | no | | Replace the parts of the URL. | The 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. The 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. The client signs in with a password in plain text, MD5 or SCRAM-SHA-256, as the server asks. Example: In the config file ```text database : postgresql://user:password@localhost:5432/eshop ``` Example: Options ```js DATA.init('default', CONF.database + '?schema=eshop&pooling=10&sslmode=require&connect_timeout=5'); ``` ### { '+stock': 5, '=dtupdated': 'NOW()' } Type: `type` Keys of the update() payload that change the value in the database. The first character of a key in the payload of `update()`: | Key | SQL | | --- | --- | | `+name`, `-name`, `*name`, `/name` | `"name"=COALESCE("name",0)+$1` (and `-`, `*`, `/`) | | `>name` | `"name"=GREATEST("name",$1)` | | `<name` | `"name"=LEAST("name",$1)` | | `!name` | `"name"=NOT "name"` | | `=name` | `"name"=value`, the value is raw SQL | | `#name` | The same as `=`, but `insert()` leaves the key out | In `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. Example: Stock ```js DATA.update('tbl_product', { '+stock': 5, '-reserved': 5, '=dtupdated': 'NOW()' }).id('p1').callback(console.log); ``` Example: A daily counter (upsert) ```js var id = NOW.format('yyyy-MM-dd'); DATA.update('tbl_visitor', { '+count': 1, '=dtupdated': 'NOW()' }, true).id(id).insert(doc => doc.id = id).callback(console.log); ``` ### callback(err, response) Type: `type` What each operation of the QueryBuilder returns on PostgreSQL. | Operation | Response | | --- | --- | | `find()` | An array of rows. | | `read()` | One row or `null`. | | `list()` | `{ items, count, page, limit, pages }`; the adapter runs the page and `SELECT COUNT(1)`. | | `check()` | `true` or `false`. | | `count()` | A number. | | `scalar()` | A number for `sum`, `avg`, `min`, `max` and `count`; rows `{ key, value }` for `group`. | | `insert()` | The number of inserted rows, the value of the `primarykey()` column, or the inserted row with `returning()`. | | `update()` | The number of changed rows, an array of rows with `returning()`, one row with `returning()` and `first()`. | | `remove()` | The number of removed rows, or an array of rows with `returning()`. | | `query()` | An array of rows; `undefined` for SQL with several statements. | | `truncate()`, `drop()` | Run `TRUNCATE TABLE … RESTART IDENTITY` and `DROP TABLE …`. | Values: `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. Example: Returning ```js DATA.insert('tbl_product', { id: 'p3', name: 'Watch', price: 80 }).returning('id,dtcreated').callback(console.log); // null { id: 'p3', dtcreated: 2026-11-16T16:22:26.950Z } ``` ### err Type: `type` The error of a failed query. An 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`. Example: A duplicate key ```js DATA.insert('tbl_order', { id: 'o1', productid: 'p2', count: 1 }).callback(function(err, response) { if (err) console.log(err.code, err.constraint, err.detail); // 23505 tbl_order_pkey Key (id)=(o1) already exists. }); ``` ### PG_ESCAPE(value) Type: `method` Escapes a value for a PostgreSQL query. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `value` | `Object` | yes | | The value. | Returns: `String` The SQL literal. Returns 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()`. Example: Escaping ```js DATA.query('SELECT id FROM eshop.tbl_product WHERE name=' + PG_ESCAPE("Kid's watch")).callback(console.log); ``` ### require('total5/client-postgresql') Type: `method` The PostgreSQL client without the QueryBuilder. Returns: `Object` The module. The 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. Example: Require ```js const PG = require('total5/client-postgresql'); ``` ### PG.connect(options, callback) Type: `method` Opens one connection. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `options` | `String|Object` | yes | | The connection string or the options. | | `callback` | `Function` | yes | | `function(err, client)`. | Returns: `Client` `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()`. Example: One connection ```js const PG = require('total5/client-postgresql'); PG.connect(CONF.database, async function(err, client) { var response = await client.query('SELECT $1::int + 1 AS value', [41]); console.log(response.rows); // [ { value: 42 } ] client.close(); }); ``` ### PG.pool(options, [max]) Type: `method` Creates a pool of connections. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `options` | `String|Object` | yes | | The connection string or the options of `PG.connect()`. | | `max` | `Number` | no | `10` | The maximum number of connections. | Returns: `Pool` The 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. Example: A pool ```js const PG = require('total5/client-postgresql'); const pool = PG.pool(CONF.database, 5); pool.query('SELECT id FROM eshop.tbl_product WHERE price>$1', [100], function(err, response) { console.log(response.rows); }); ``` ### pool.connect(callback) Type: `method` Borrows a connection from the pool. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `callback` | `Function` | yes | | `function(err, client, release)`. | The 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. Example: A transaction ```js pool.connect(async function(err, client, release) { if (err) { console.log(err); return; } try { await client.query('BEGIN'); await client.query('UPDATE eshop.tbl_product SET stock=stock-$1 WHERE id=$2', [2, 'p1']); await client.query('INSERT INTO eshop.tbl_order (id, productid, count) VALUES($1, $2, $3)', ['o2', 'p1', 2]); await client.query('COMMIT'); } catch (e) { await client.query('ROLLBACK'); } finally { release(); } }); ``` ### client.query(sql, [params], [callback]) Type: `method` Runs a query on the connection. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `sql` | `String` | yes | | The SQL. | | `params` | `Array` | no | | The values of the parameters. | | `callback` | `Function` | no | | `function(err, response)`. | Returns: `Promise` Without `callback`. The response is `{ command, rowCount, rows, fields }`. The 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. Example: Query ```js client.query('SELECT id, name FROM eshop.tbl_product WHERE price>$1', [100], function(err, response) { console.log(response.command, response.rowCount, response.rows); }); ``` ### client.close([callback]) Type: `method` Returns the connection to its pool or closes it. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `callback` | `Function` | no | | Called when it is done. | A connection of a pool goes back to the pool (alias `client.release()`). Other connections are closed after their pending queries, like `client.end([callback])`. Example: Close ```js client.close(); ``` ### pool.end([callback]) Type: `method` Closes all connections of the pool. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `callback` | `Function` | no | | Called when all connections are closed. | Idle connections close at once, busy ones when they are released. Waiting and later requests fail with `Pool is closed`. Example: End ```js pool.end(() => console.log('closed')); ``` ### PG.types Type: `property` The parsers of values by the OID of the type. Returns: `Object` An 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. Example: bigint as a number ```js const PG = require('total5/client-postgresql'); PG.types[20] = value => +value; ``` --- title: Localization project: Total.js V5 version: 0.0.20 section: reference language: en license: MIT url: https://totaljs.es/docs/total-js-v5/0-0-20/reference/localization/ updated: 2026-11-18T16:57:19.575Z --- # Localization > Resource files, @(...) texts, TRANSLATE(), LOCALIZE(), LOADRESOURCE() and the language of a request. Functions, 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. ## API ### /resources/{name}.resource Type: `type` A text file with a dictionary of translations. Every `.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. Each 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()`. Example: sk.resource ```text # Slovak T1bx8wg2 : Vitajte T1oapati : Pridať do košíka name : Meno January : január ``` ### /resources/default.resource Type: `type` The fallback dictionary. When 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. Example: Fallback ```js // /resources/default.resource contains: name : Name F.resource('de', 'name'); // 'Name' when de.resource has no "name" ``` ### 'T' + text.hash(true).toString(36) Type: `type` How the key of an `@(...)` text is created. The 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. Example: Compute a key ```js var key = 'T' + 'Welcome'.hash(true).toString(36); // 'T1bx8wg2' ``` ### @(text) Type: `command` Marks a text for translation. The 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. Example: In a view ```html <h1>@(Welcome)</h1> <p>@(Free delivery (over 50 EUR))</p> ``` Example: In code ```js $.invalid('@(The name is required)'); ``` ### LOADRESOURCE(name, [text]) Type: `method` Parses the text of a resource file and stores it as a dictionary. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `name` | `String` | yes | | The name of the dictionary, usually a language code. | | `text` | `String` | no | | The content in the resource format. | The 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()`. Example: Load a dictionary ```js LOADRESOURCE('sk', 'T1bx8wg2 : Vitajte\nname : Meno'); ``` Example: From a file of your own ```js LOADRESOURCE('de', F.Fs.readFileSync(PATH.root('lang/de.txt'), 'utf8')); ``` ### LOADRESOURCE(url) Type: `method` Downloads dictionaries from a URL. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `url` | `String` | yes | | The URL of a JSON response with dictionaries. | Without 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. Example: Remote dictionaries ```js // response: { "sk": "T1bx8wg2 : Vitajte", "de": "T1bx8wg2 : Willkommen" } LOADRESOURCE('https://example.com/translations.json'); ``` ### TRANSLATE(language, text) Type: `method` Translates all `@(...)` texts in a string. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `language` | `String` | yes | | The name of the dictionary. An empty string uses `default`. | | `text` | `String` | yes | | A string with `@(...)` texts. | Returns: `String` The translated string. Every `@(...)` 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()`. Example: Translate a string ```js TRANSLATE('sk', '<b>@(Welcome)</b>, Peter'); // '<b>Vitajte</b>, Peter' ``` Example: In a route ```js function detail($) { $.plain(TRANSLATE($.language, '@(Order) #' + $.params.id)); } ``` ### F.resource(language, key) Type: `method` Reads one key of a dictionary. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `language` | `String` | yes | | The name of the dictionary. | | `key` | `String` | yes | | The key. | Returns: `String` The value, or an empty string when the key does not exist. Reads the key from the dictionary of the language, then from `default`. Use it for keys with your own names, not for `@(...)` texts. Example: Read a key ```js // /resources/de.resource contains: currency : EUR var currency = F.resource('de', 'currency') || 'USD'; ``` ### F.resources Type: `property` All loaded dictionaries. Returns: `Object` An object with the dictionaries by their names. Each dictionary is a plain object of keys and values. Example: List the languages ```js var languages = Object.keys(F.resources); // ['default', 'sk', 'de'] ``` ### LOCALIZE(fn) Type: `method` Registers the delegate that chooses the language of a request. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `fn` | `Function` | yes | | `function($)` that returns the language as a string. | The 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`. Example: From the query string or the browser ```js LOCALIZE(function($) { var language = $.query.language || ($.headers['accept-language'] || '').substring(0, 2).toLowerCase(); return language === 'sk' || language === 'de' ? language : 'en'; }); ``` Example: From the user ```js LOCALIZE(function($) { return $.user ? $.user.language : 'en'; }); ``` ### DEF.onLocalize = function($) {} Type: `delegate` The delegate that `LOCALIZE()` sets. `LOCALIZE(fn)` stores the function here. You can also assign it directly; set it to `null` to stop choosing the language. Example: Assign directly ```js DEF.onLocalize = function($) { return $.cookie('language') || 'en'; }; ``` ### $.language Type: `property` The language of the request. Returns: `String` An 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. Example: Set the language in a route ```js exports.install = function() { ROUTE('GET /sk/', index_sk); }; function index_sk($) { $.language = 'sk'; $.view('index'); } ``` ### $.language Type: `property` The language of the request that called the action. Returns: `String` In 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. Example: Translate in an action ```js NEWACTION('Orders/read', { name: 'Read an order', action: function($) { $.callback({ title: TRANSLATE($.language, '@(Your order)') }); } }); ``` ### view.language Type: `property` The language of a view. Returns: `String` A 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. Example: Render a view in German ```js var html = F.view('mail/order', { id: 'A100' }, function(view) { view.language = 'de'; }); ``` ### @{language} Type: `command` Prints the language of the view. Prints 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. Example: HTML lang attribute ```html <html lang="@{language || 'en'}"> ``` ### /public/*.html Type: `type` Static HTML files are translated too. An `.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. Example: A static page ```html <!-- /public/about.html --> <h1>@(About us)</h1> ``` ### total5 translate [filename] Type: `command` Creates a resource file with all `@(...)` texts of a project. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `filename` | `String` | no | `translate.resource` | The output file. | Reads 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. Example: Create a dictionary ```bash cd my-app total5 translate resources/sk.resource ``` Example: The result ```text T1bx8wg2 : Welcome T1oapati : Add to cart ``` ### errorbuilder.output([language]) Type: `method` Returns the errors translated into a language. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `language` | `String` | no | `'default'` | The name of the dictionary. | Returns: `Array` Objects with `name`, `error`, `path` and `index`. A 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. Example: Translate errors ```js var err = new ErrorBuilder(); err.push('@(The name is required)'); err.output('sk'); // [{ error: 'Meno je povinné', ... }] ``` ### errorbuilder.toString([language], [divider]) Type: `method` Returns the translated messages as one string. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `language` | `String` | no | `'default'` | The name of the dictionary. | | `divider` | `String` | no | `'\n'` | The text between messages. | Returns: `String` Joins the messages of `output(language)` with the divider. Example: One line ```js var text = err.toString('sk', ', '); ``` ### {field} : message Type: `type` Translated messages for invalid fields. When 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`. Example: Messages for fields ```text # /resources/default.resource email : Enter a valid e-mail address name : Enter your name ``` ### MAIL(email, subject, view, model, [language], [callback]) Type: `method` Sends an e-mail rendered from a view in a language. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `email` | `String` | yes | | The recipient. | | `subject` | `String` | yes | | The subject; it can contain `@(...)`. | | `view` | `String` | yes | | The name of the view. | | `model` | `Object` | yes | | The model of the view. | | `language` | `String` | no | | The language. | | `callback` | `Function` | no | | `function(err)`. | With 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. Example: A localized e-mail ```js MAIL(user.email, '@(Your order)', 'mail/order', order, user.language); ``` ### HTMLMAIL(email, subject, body, [language], [callback]) Type: `method` Sends HTML as an e-mail, translated into a language. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `email` | `String` | yes | | The recipient. | | `subject` | `String` | yes | | The subject. | | `body` | `String` | yes | | The HTML body. | | `language` | `String` | no | | The language. | | `callback` | `Function` | no | | `function(err)`. | With a language, `@(...)` texts in the subject and the body are translated. Example: Translated body ```js HTMLMAIL(user.email, '@(Welcome)', '<p>@(Thank you for your registration)</p>', 'sk'); ``` ### TEMPLATE(body, [model], [$]) Type: `method` Renders a template translated into the language of `$`. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `body` | `String` | yes | | The template, its file name or a URL. | | `model` | `Object` | no | | The model. | | `$` | `Object` | no | | The controller or action options with the language. | Returns: `Promise` The rendered HTML. When you pass `$`, `@(...)` texts in the template are translated into `$.language` before the template is compiled, and the compiled template is cached per language. Example: In an action ```js NEWACTION('Orders/print', { name: 'Print an order', action: async function($) { var html = await TEMPLATE('invoice', { number: 'F001' }, $); $.callback(html); } }); ``` ### date.format(format, [dictionary]) Type: `method` Formats a date with month and day names from a dictionary. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `format` | `String` | yes | | The format, for example `dddd d. MMMM yyyy`. | | `dictionary` | `String` | no | | The name of the dictionary. | Returns: `String` `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. Example: Slovak names ```js // sk.resource: January : január, Monday : pondelok new Date(2024, 0, 1).format('dddd d. MMMM', 'sk'); // 'pondelok 1. január' ``` ### AUTH({ localize: function(data, $) {} }) Type: `config` Sets the language in the built-in session authorization. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `data` | `Object` | yes | | The session data, or `null`. | | `$` | `Controller` | yes | | The controller of the request. | The 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. Example: Language of the user ```js AUTH({ cookie: 'session', localize: function(data, $) { return data ? data.language : 'en'; } // other options }); ``` --- title: HTTP requests project: Total.js V5 version: 0.0.20 section: reference language: en license: MIT url: https://totaljs.es/docs/total-js-v5/0-0-20/reference/http-requests/ updated: 2026-11-18T16:57:29.576Z --- # HTTP requests > RESTBuilder, REQUEST(), AJAX(), DOWNLOAD() and Total.download(). The 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/). ## API ### REQUEST(options, [callback]) Type: `method` Sends an HTTP request with full control of the options. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `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. | | `options.method` | `String` | no | `'GET'` | The HTTP method in upper case. | | `options.headers` | `Object` | no | | Request headers. The object is copied, so your object is not changed. | | `options.type` | `String` | no | | Sets `Content-Type`: `'json'`, `'urlencoded'`, `'xml'`, `'html'`, `'plain'` or `'text'`, `'raw'` (`application/octet-stream`). | | `options.body` | `String|Buffer` | no | | The request body. A string is sent as UTF-8; `Content-Length` is set for you. | | `options.query` | `Object|String` | no | | Appended to the URL as a query string. | | `options.cookies` | `Object` | no | | Cookies to send, as `{ name: value }`. | | `options.cook` | `Boolean` | no | | Stores the cookies of the response into `options.cookies`, so the same options object sends them with the next request. | | `options.timeout` | `Number` | no | `8000` | Timeout in milliseconds; `0` disables it. | | `options.encoding` | `String` | no | `'utf8'` | Encoding of a text body. `'binary'` returns a `Buffer`. | | `options.xhr` | `Boolean` | no | | Adds `X-Requested-With: XMLHttpRequest`. | | `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. | | `options.compress` | `String` | no | | Compresses the body: `'gzip'` or `'deflate'`, and sets `Content-Encoding`. | | `options.encrypt` | `String` | no | | A key: the body is encrypted with it and the text response is decrypted with it. | | `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. | | `options.custom` | `Boolean` | no | | Returns `response.stream` instead of reading the body. | | `options.noredirect` | `Boolean` | no | | Does not follow redirects; the callback gets the `301`/`302` response. | | `options.keepalive` | `Boolean` | no | | Uses a shared keep-alive agent (one for HTTP, one for HTTPS). | | `options.resolve` | `Boolean` | no | | Resolves the hostname with a DNS cache. `options.dnscache` does the same. Skipped for `localhost` and IP addresses. | | `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`. | | `options.insecure` | `Boolean` | no | | Accepts invalid or self-signed TLS certificates. | | `options.key` | `Buffer` | no | | Client TLS key. | | `options.cert` | `Buffer` | no | | Client TLS certificate. | | `options.dhparam` | `Buffer` | no | | TLS Diffie-Hellman parameters. | | `options.unixsocket` | `Object` | no | | `{ socket, path }` to send the request through a Unix socket instead of `url`. | | `options.ondata` | `Function` | no | | `function(chunk, percentage)` for every received chunk. | | `options.onprogress` | `Function` | no | | `function(percentage)`; the percentage is known only with `Content-Length`. | | `options.callback` | `Function` | no | | `function(err, response)`, instead of the second argument. | | `callback` | `Function` | no | | `function(err, response)`. | Returns: `Promise` A promise when no callback is given; otherwise nothing. Sends 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`. The 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. With `custom: true` the callback runs as soon as the headers arrive and the response has `stream` (the Node.js response) instead of `body`. Errors: 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`. Redirects `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`. Example: POST JSON ```js REQUEST({ url: 'https://api.example.com/orders/', method: 'POST', type: 'json', body: JSON.stringify({ id: 'p100', count: 2 }) }, function(err, response) { if (err || response.status !== 200) return; var order = response.body.parseJSON(); }); ``` Example: With a promise ```js var response = await REQUEST({ url: 'https://example.com/robots.txt', timeout: 3000 }); console.log(response.status, response.body); ``` Example: Upload a file ```js REQUEST({ url: 'https://files.example.com/upload/', method: 'POST', files: [{ name: 'file', filename: 'report.pdf', path: PATH.databases('report.pdf') }], body: { folder: 'reports' } }, console.log); ``` Example: Read a stream ```js REQUEST({ url: 'https://cdn.example.com/video.mp4', custom: true }, function(err, response) { if (!err) response.stream.pipe(Total.Fs.createWriteStream(PATH.tmp('video.mp4'))); }); ``` Example: Write the body yourself ```js REQUEST({ url: 'https://api.example.com/import/', method: 'POST', type: 'plain', writer: function(req) { for (var line of lines) req.write(line + '\n'); req.end(); } }, console.log); ``` ### AJAX('METHOD url', [data], [callback]) Type: `method` Sends a JSON request and returns the parsed response. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `url` | `String` | yes | | `'METHOD url'`, for example `'POST https://example.com/api/'`. | | `data` | `Object` | no | | Data sent as JSON. | | `callback` | `Function` | no | | `function(err, response, meta)`. | Returns: `Promise` A promise when no callback is given. Sends 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. The 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`. For 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. Example: Callback ```js AJAX('POST https://api.example.com/login/', { email: 'peter@example.com' }, function(err, response, meta) { console.log(meta.status, response); }); ``` Example: Promise ```js var products = await AJAX('GET https://api.example.com/products/?page=1'); ``` Example: XML answer ```js // the service answers <order id="100"><name>Book</name><items><item>A</item><item>B</item></items></order> var order = await AJAX('GET https://api.example.com/orders/100/'); // { order__: { id: '100' }, order_name: 'Book', order_items_item: ['A', 'B'] } ``` ### DOWNLOAD(url, filename, [callback], [timeout]) Type: `method` Downloads a remote file to the disk. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `url` | `String|Object` | yes | | The URL, or `{ socket, path }` for a Unix socket. | | `filename` | `String` | yes | | The target file path. | | `callback` | `Function` | no | | `function(err, response)`. | | `timeout` | `Number` | no | `8000` | Timeout in milliseconds. | Returns: `Promise` A promise when no callback is given. 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`. `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`. Example: Download an image ```js DOWNLOAD('https://cdn.example.com/logo.png', PATH.public('img/logo.png'), function(err, response) { if (!err && response.status === 200) console.log('Saved', response.filename); }); ``` Example: Promise ```js var response = await DOWNLOAD('https://example.com/data.csv', PATH.tmp('data.csv')); ``` ### Total.download(url, filename, [callback], [timeout]) Type: `method` The framework method behind DOWNLOAD(). | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `url` | `String|Object` | yes | | The URL, or `{ socket, path }` for a Unix socket. | | `filename` | `String` | yes | | The target file path. | | `callback` | `Function` | no | | `function(err, response)`. | | `timeout` | `Number` | no | `8000` | Timeout in milliseconds. | Returns: `Promise` A promise when no callback is given. The 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`. `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`. Example: Download ```js Total.download('https://example.com/export.json', PATH.tmp('export.json'), function(err, response) { console.log(err, response.status); }); ``` ### new RESTBuilder([url]) Type: `class` A builder for requests to REST services. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `url` | `String` | no | | The URL of the request. | Returns: `RESTBuilder` A new builder. A 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()`. You 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)`. Example: Create a builder ```js var builder = RESTBuilder.url('https://api.example.com/users/'); builder.header('X-Token', CONF.apitoken); builder.callback(console.log); ``` ### RESTBuilder.make(fn) Type: `method` Creates a builder and passes it to a function. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `fn` | `Function` | yes | | `function(builder)`. | Returns: `RESTBuilder` The new builder. Creates 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. Example: Build a request ```js RESTBuilder.make(function(builder) { builder.url('https://api.example.com/users/'); builder.post({ name: 'Peter' }); builder.callback(console.log); }); ``` ### RESTBuilder.GET(url, [data]) Type: `method` Creates a GET request. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `url` | `String` | yes | | The URL. | | `data` | `Object` | no | | Sent as the query string. | Returns: `RESTBuilder` A new builder. Creates 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`. Example: Query string ```js RESTBuilder.GET('https://api.example.com/products/', { page: 2, limit: 20 }).callback(function(err, response) { console.log(response); }); ``` Example: HEAD ```js RESTBuilder.HEAD('https://example.com/').callback(function(err, response, output) { console.log(output.status, output.headers['last-modified']); }); ``` ### RESTBuilder.POST(url, [data]) Type: `method` Creates a POST request. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `url` | `String` | yes | | The URL. | | `data` | `Object` | no | | Sent as a JSON body. | Returns: `RESTBuilder` A new builder. Creates 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. Example: POST JSON ```js RESTBuilder.POST('https://api.example.com/orders/', { productid: 'p100', count: 2 }).promise().then(function(order) { console.log(order.id); }); ``` ### RESTBuilder.PUT(url, [data]) Type: `method` Creates a PUT request. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `url` | `String` | yes | | The URL. | | `data` | `Object` | no | | Sent as a JSON body. | Returns: `RESTBuilder` A new builder. Creates a builder with the method `PUT`; `data` is sent as JSON. Example: PUT ```js RESTBuilder.PUT('https://api.example.com/products/p100/', { price: 99 }).callback(console.log); ``` ### RESTBuilder.PATCH(url, [data]) Type: `method` Creates a PATCH request. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `url` | `String` | yes | | The URL. | | `data` | `Object` | no | | Sent as a JSON body. | Returns: `RESTBuilder` A new builder. Creates a builder with the method `PATCH`; `data` is sent as JSON. Example: PATCH ```js RESTBuilder.PATCH('https://api.example.com/products/p100/', { price: 99 }).callback(console.log); ``` ### RESTBuilder.DELETE(url, [data]) Type: `method` Creates a DELETE request. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `url` | `String` | yes | | The URL. | | `data` | `Object` | no | | Sent as a JSON body. | Returns: `RESTBuilder` A new builder. Creates a builder with the method `DELETE`; `data` is sent as JSON. Example: DELETE ```js RESTBuilder.DELETE('https://api.example.com/products/p100/').callback(console.log); ``` ### RESTBuilder.API(url, name, [data]) Type: `method` Calls an API endpoint of a Total.js application. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `url` | `String` | yes | | The URL of the API endpoint. | | `name` | `String` | yes | | The name of the API operation. | | `data` | `Object` | no | | The data of the operation. | Returns: `RESTBuilder` A new builder. Creates 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`. Example: Call an API ```js RESTBuilder.API('https://app.example.com/api/', 'products_list', { category: 'shoes' }).callback(function(err, response) { console.log(err, response); }); ``` Example: With a query ```js RESTBuilder.API('https://app.example.com/api/', 'products_list', { category: 'shoes' }).get({ page: 2 }).callback(console.log); // body: { data: { category: 'shoes' }, query: { page: 2 }, schema: 'products_list' } ``` ### builder.compress([value]) Type: `method` Leaves out empty values from the body of a RESTBuilder.API() request. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `value` | `Boolean` | no | `true` | `false` turns it off. | Returns: `RESTBuilder` The same builder, for chaining. Without 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. Example: Smaller body ```js RESTBuilder.API(CONF.erpapi, 'orders_save', { id: 'A1', note: null, total: 120 }).compress().callback(console.log); // data: { id: 'A1', total: 120 } ``` ### RESTBuilder.upgrade(fn) Type: `method` Registers a function that changes every builder before it is sent. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `fn` | `Function` | yes | | `function(builder)`. | The 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. Example: Add a token to one service ```js RESTBuilder.upgrade(function(builder) { if (builder.url().startsWith(CONF.shopapi)) builder.header('X-Token', CONF.shoptoken); }); ``` ### builder.url([url]) Type: `method` Sets or reads the URL. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `url` | `String` | no | | The new URL. | Returns: `RESTBuilder|String` The builder, or the URL when called without an argument. With an argument sets the URL and returns the builder; without one returns the current URL. Example: Read the URL ```js var url = builder.url(); ``` ### builder.method(method, [data]) Type: `method` Sets the HTTP method. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `method` | `String` | yes | | The HTTP method. | | `data` | `Object` | no | | Data sent as JSON. | Returns: `RESTBuilder` The same builder, for chaining. Sets the method (lower case is converted to upper case). `data` is sent as JSON. Shortcuts: `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. Example: Shortcuts ```js RESTBuilder.url('https://api.example.com/products/p100/').put({ price: 99 }).callback(console.log); ``` ### builder.json([data]) Type: `method` Sends data as JSON. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `data` | `Object` | no | | The data. | Returns: `RESTBuilder` The same builder, for chaining. Sets the type to JSON and the body to `data` (an object is serialized when the request is sent). A `GET` request becomes `POST`. Example: JSON body ```js RESTBuilder.url('https://api.example.com/users/').json({ name: 'Peter' }).callback(console.log); ``` ### builder.urlencoded([data]) Type: `method` Sends data as a URL-encoded form. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `data` | `Object` | no | | The form fields. | Returns: `RESTBuilder` The same builder, for chaining. Sets `Content-Type: application/x-www-form-urlencoded` and the body; an object is encoded when the request is sent. A `GET` request becomes `POST`. Example: Form ```js RESTBuilder.url('https://example.com/login/').urlencoded({ name: 'peter', password: 'x' }).callback(console.log); ``` ### builder.xml([data]) Type: `method` Sends an XML body. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `data` | `String` | no | | The XML. | Returns: `RESTBuilder` The same builder, for chaining. Sets `Content-Type: text/xml` and the body. Pass the XML as a string. A `GET` request becomes `POST`. Example: XML body ```js RESTBuilder.url('https://soap.example.com/').xml('<request><id>100</id></request>').callback(console.log); ``` ### builder.raw(value, [type]) Type: `method` Sets the body as it is. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `value` | `String|Buffer` | yes | | The body. | | `type` | `String` | no | | The short content type. | Returns: `RESTBuilder` The same builder, for chaining. Sets 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. Example: Binary body ```js RESTBuilder.url('https://api.example.com/images/').post().raw(buffer, 'raw').callback(console.log); ``` ### builder.text(value) Type: `method` Sends plain text and keeps the response unparsed. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `value` | `String` | yes | | The text. | Returns: `RESTBuilder` The same builder, for chaining. `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. Example: Plain text ```js RESTBuilder.url('https://api.example.com/echo/').post().text('Hello').callback(function(err, response) { // response is the raw body }); ``` ### builder.file(name, filename, [source]) Type: `method` Adds a file and sends a multipart request. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `name` | `String` | yes | | The form field name. | | `filename` | `String` | yes | | The file name sent to the service. | | `source` | `Buffer|String` | no | | A buffer, a path or a URL. | Returns: `RESTBuilder` The same builder, for chaining. The 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. Example: Upload two files ```js RESTBuilder.POST('https://files.example.com/upload/') .file('photo', 'photo.jpg', PATH.tmp('photo.jpg')) .file('logo', 'logo.png', 'https://cdn.example.com/logo.png') .callback(console.log); ``` ### builder.header(name, value) Type: `method` Sets a request header. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `name` | `String` | yes | | The header name. | | `value` | `String` | yes | | The value. | Returns: `RESTBuilder` The same builder, for chaining. Sets 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`. Example: Headers ```js builder.header('X-Token', CONF.apitoken).origin('https://www.example.com').xhr(); ``` ### builder.type(value) Type: `method` Sets the Content-Type header. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `value` | `String` | yes | | The MIME type. | Returns: `RESTBuilder` The same builder, for chaining. Sets `Content-Type` to a full MIME type. A type set by `json()`, `urlencoded()`, `xml()` or `text()` replaces it, so use it with `raw(value)`. Example: Custom type ```js builder.raw('{"id":1}').type('application/vnd.api+json'); ``` ### builder.accept(ext) Type: `method` Sets the Accept header. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `ext` | `String` | yes | | An extension or a MIME type. | Returns: `RESTBuilder` The same builder, for chaining. Takes a file extension (`'json'`, `'xml'`, `'html'`...) and converts it to its MIME type; a longer value is used as it is. Example: Accept XML ```js builder.accept('xml'); ``` ### builder.auth(user, [password]) Type: `method` Sets the Authorization header. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `user` | `String` | yes | | The user name or the whole header value. | | `password` | `String` | no | | The password. | Returns: `RESTBuilder` The same builder, for chaining. With `user` and `password` sets basic authentication (`Basic base64(user:password)`). With one argument the value is used as it is, for example `'Bearer TOKEN'`. Example: Basic and Bearer ```js builder.auth('admin', 'secret'); builder.auth('Bearer ' + CONF.apitoken); ``` ### builder.cookie(name, value) Type: `method` Adds a cookie to the request. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `name` | `String` | yes | | The cookie name. | | `value` | `String` | yes | | The value. | Returns: `RESTBuilder` The same builder, for chaining. Adds one cookie. `builder.cookies(obj)` replaces all cookies with an object `{ name: value }`. Example: Cookies ```js builder.cookie('session', token); builder.cookies({ lang: 'en', theme: 'dark' }); ``` ### builder.cook([value]) Type: `method` Keeps the response cookies in the builder. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `value` | `Boolean` | no | `true` | `false` turns it off. | Returns: `RESTBuilder` The same builder, for chaining. With `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. Example: Login, then read ```js RESTBuilder.url('https://example.com/login/').cook().urlencoded({ name: 'peter', password: 'x' }).callback(function(err, response, output) { RESTBuilder.GET('https://example.com/profile/').cookies(output.cookies).callback(console.log); }); ``` ### builder.timeout(ms) Type: `method` Sets the timeout. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `ms` | `Number` | yes | | Milliseconds. | Returns: `RESTBuilder` The same builder, for chaining. The timeout in milliseconds (10000 by default). `0` disables it. When it expires the error is `408: Request Timeout`. Example: Five seconds ```js builder.timeout(5000); ``` ### builder.keepalive([val]) Type: `method` Reuses connections with a keep-alive agent. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `val` | `Boolean` | no | `true` | Turns keep-alive on or off. | Returns: `RESTBuilder` The same builder, for chaining. Without 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. Example: Keep-alive ```js RESTBuilder.GET('https://api.example.com/ping/').keepalive().callback(console.log); ``` ### builder.proxy(url) Type: `method` Sends the request through a proxy. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `url` | `String` | yes | | The proxy. | Returns: `RESTBuilder` The same builder, for chaining. `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. Example: Proxy ```js builder.proxy('http://10.0.0.5:3128'); ``` Example: Proxy with a login ```js builder.proxy('http://user:secret@10.0.0.5:3128'); ``` ### builder.insecure() Type: `method` Accepts invalid TLS certificates. Returns: `RESTBuilder` The same builder, for chaining. Accepts self-signed or expired certificates of the service. Use it only for internal services. Example: Self-signed ```js RESTBuilder.GET('https://10.0.0.20/api/').insecure().callback(console.log); ``` ### builder.cert(key, cert, [dhparam]) Type: `method` Sets a client TLS certificate. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `key` | `Buffer` | yes | | The private key. | | `cert` | `Buffer` | yes | | The certificate. | | `dhparam` | `Buffer` | no | | Diffie-Hellman parameters. | Returns: `RESTBuilder` The same builder, for chaining. For services that require client certificates. Example: Client certificate ```js builder.cert(Total.Fs.readFileSync(PATH.root('client.key')), Total.Fs.readFileSync(PATH.root('client.crt'))); ``` ### builder.unixsocket(socket, path) Type: `method` Sends the request through a Unix socket. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `socket` | `String` | yes | | The socket file. | | `path` | `String` | yes | | The request path, for example `/api/`. | Returns: `RESTBuilder` The same builder, for chaining. Connects to the socket file instead of a host; `path` is the URL path of the request. Example: Docker API ```js RESTBuilder.make(function(builder) { builder.unixsocket('/var/run/docker.sock', '/containers/json'); builder.callback(console.log); }); ``` ### builder.nodnscache() Type: `method` Turns off the DNS cache for this request. Returns: `RESTBuilder` The same builder, for chaining. By default the builder resolves the hostname once and caches its addresses. With `nodnscache()` Node.js resolves it for every request. Example: No DNS cache ```js builder.nodnscache(); ``` ### builder.redirect(value) Type: `method` Turns following redirects on or off. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `value` | `Boolean` | yes | | `false` stops following redirects. | Returns: `RESTBuilder` The same builder, for chaining. `redirect(false)` returns the `301` or `302` response itself; read the target in `output.headers.location`. By default up to four redirects are followed. Example: Read the location ```js RESTBuilder.GET('https://example.com/short/abc').redirect(false).callback(function(err, response, output) { console.log(output.status, output.headers.location); }); ``` ### builder.encrypt(key) Type: `method` Encrypts the body and decrypts the response. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `key` | `String` | yes | | The encryption key. | Returns: `RESTBuilder` The same builder, for chaining. The 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. Example: Encrypted call ```js builder.encrypt(CONF.sharedkey); ``` ### builder.progress(fn) Type: `method` Reports the download progress. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `fn` | `Function` | yes | | `function(percentage)`. | Returns: `RESTBuilder` The same builder, for chaining. Calls `fn(percentage)` for every received chunk. The percentage is known only when the response has `Content-Length`, otherwise it is `0`. Example: Progress ```js builder.progress(function(percentage) { console.log(percentage.toFixed(1) + '%'); }); ``` ### builder.noparse() Type: `method` Returns the raw response body. Returns: `RESTBuilder` The same builder, for chaining. The callback receives the body as a string (or a `Buffer` for binary types) instead of a parsed value. Example: Raw HTML ```js RESTBuilder.GET('https://example.com/').noparse().callback(function(err, html) { console.log(html.length); }); ``` ### builder.base64() Type: `method` Returns the response body as base64. Returns: `RESTBuilder` The same builder, for chaining. The callback receives the body encoded in base64, for example to embed an image as a data URI. Example: Data URI ```js RESTBuilder.GET('https://cdn.example.com/logo.png').base64().callback(function(err, data) { var uri = 'data:image/png;base64,' + data; }); ``` ### builder.debug() Type: `method` Prints the request and the response to the console. Returns: `RESTBuilder` The same builder, for chaining. After the response arrives prints the status, the method, the URL with the query, the error and the raw body. Example: Debug ```js RESTBuilder.GET('https://api.example.com/products/').debug().callback(NOOP); ``` ### builder.callback([fn]) Type: `method` Sends the request and receives the parsed response. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `fn` | `Function|Object` | no | | `function(err, response, output)` or the `$` of an action. | Returns: `RESTBuilder|Promise` The builder, or a promise when called without an argument. Sends the request on the next tick and passes the result to `fn(err, response, output)`: - `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`. - `output`: `status`, `headers`, `response` (the raw body), `hostname`, `origin`, `cookies` (with `cook()`) and `output.cookie(name)`, which reads a cookie of the response. - `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. `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`. Example: Callback ```js RESTBuilder.GET('https://api.example.com/products/').callback(function(err, response, output) { if (err) return console.log(err); console.log(output.status, response.length); }); ``` Example: In an action ```js NEWACTION('Products/sync', { name: 'Sync products', action: function($) { RESTBuilder.GET(CONF.shopapi + '/products/').callback($); } }); ``` ### builder.promise([$]) Type: `method` Sends the request and returns a promise. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `$` | `Object` | no | | The `$` of an action. | Returns: `Promise` Resolves with the parsed response. The 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. Example: await ```js var user = await RESTBuilder.GET('https://api.example.com/users/100/').promise(); ``` Example: With $ ```js var order = await RESTBuilder.POST(CONF.shopapi + '/orders/', model).promise($); ``` ### builder.exec([callback]) Type: `method` Sends the request at once. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `callback` | `Function` | no | | `function(err, response, output)`. | Returns: `RESTBuilder` The same builder, for chaining. Sends 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. Example: Exec ```js RESTBuilder.GET('https://api.example.com/ping/').exec(function(err, response) { console.log(err, response); }); ``` ### builder.stream(callback) Type: `method` Returns the response as a stream. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `callback` | `Function` | yes | | `function(err, response)`. | Returns: `RESTBuilder` The same builder, for chaining. Sends 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. Example: Save a large file ```js RESTBuilder.GET('https://cdn.example.com/backup.zip').stream(function(err, response) { if (!err && response.status === 200) response.stream.pipe(Total.Fs.createWriteStream(PATH.tmp('backup.zip'))); }); ``` ### builder.error(value) Type: `method` · Since: `0.0.16` Replaces any error with your own value. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `value` | `Object|String` | yes | | The error to return, for example a message or an `ErrorBuilder`. | Returns: `RESTBuilder` The same builder, for chaining. When 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. Example: Own error ```js RESTBuilder.GET(CONF.stockapi).error('The stock service is not available').callback($); ``` ### builder.logerror() Type: `method` · Since: `0.0.16` Prints errors to the console. Returns: `RESTBuilder` The same builder, for chaining. When 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. Example: Log errors ```js RESTBuilder.POST(CONF.crmapi + '/contacts/', model).logerror().callback($); ``` --- title: OpenClient project: Total.js V5 version: 0.0.20 section: reference language: en license: MIT url: https://totaljs.es/docs/total-js-v5/0-0-20/reference/openclient/ updated: 2026-11-18T16:56:49.572Z --- # OpenClient > OPENCLIENT() and the methods of a client. ## API ### OPENCLIENT(url, [id]) Type: `method` Opens a WebSocket client for request-response messages. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `url` | `String` | yes | | The WebSocket URL (`ws://`, `wss://`, `http://` or `https://`). | | `id` | `String` | no | | A client identifier; a random one is generated when omitted. | Returns: `Object` The client. Connects 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. When 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. Example: Connect ```js var client = OPENCLIENT('wss://service.example.com/$client/', 'myservice'); client.online(function(meta) { console.log(meta ? 'Connected to ' + meta.id : 'Offline'); }); client.message(function(msg) { console.log(msg); }); ``` ### client.send(msg, [callback], [timeout]) Type: `method` Sends a message to the server. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `msg` | `Object` | yes | | The message. | | `callback` | `Function` | no | | `function(err, response)`. | | `timeout` | `Number` | no | | Milliseconds to wait for the answer. | Returns: `Object` The client, for chaining. Sends `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. `client.cmd(msg)` sends a message without waiting for an answer. Example: Send and wait ```js client.send({ type: 'users' }, function(err, response) { console.log(err, response); }, 5000); ``` Example: Command ```js client.cmd({ type: 'refresh' }); ``` ### client.rpc(msg, [callback], [timeout]) Type: `method` Sends a message and waits for the answer. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `msg` | `Object` | yes | | The message. | | `callback` | `Function` | no | | `function(err, response)`. | | `timeout` | `Number` | no | | Milliseconds to wait. | Returns: `Promise|Object` A promise without a callback. The 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). Example: await ```js var users = await client.rpc({ type: 'users', page: 1 }, 5000); ``` ### client.message(fn) Type: `method` Sets the handler of incoming messages. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `fn` | `Function` | yes | | `function(msg)`. | Returns: `Object` The client, for chaining. Runs for every message from the server that is not an answer to `send()` or `rpc()` and is not the `init` message. Example: Messages ```js client.message(function(msg) { if (msg.type === 'notify') console.log(msg.body); }); ``` ### client.online(fn) Type: `method` Sets the handler of online and offline changes. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `fn` | `Function` | yes | | `function(meta)`. | Returns: `Object` The client, for chaining. Runs with the `init` message of the server when the service is ready, and with `null` when the connection closes. Example: Online state ```js client.online(function(meta) { console.log(meta ? 'online' : 'offline'); }); ``` ### client.error(fn) Type: `method` Sets the handler of connection errors. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `fn` | `Function` | yes | | `function(err)`. | Returns: `Object` The client, for chaining. Runs 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. Example: Errors ```js client.error(function(err) { console.log('OPENCLIENT error', err); }); ``` ### client.close() Type: `method` Removes the client. `client.remove()` is an alias. Pending callbacks of this client receive `'offline'`. The shared connection is closed when it has no other clients. Example: Close ```js client.close(); ``` --- title: Sending email project: Total.js V5 version: 0.0.20 section: reference language: en license: MIT url: https://totaljs.es/docs/total-js-v5/0-0-20/reference/mail/ updated: 2026-11-18T16:57:29.576Z --- # Sending email > MAIL(), HTMLMAIL(), LOGMAIL(), the Mail module, the message object and the SMTP keys. This 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. ## API ### MAIL() Type: `method` Renders a view and sends it as an e-mail. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `email` | `String|Array` | yes | | One address, comma-separated addresses, or an array of addresses. Each becomes a `To:` recipient. | | `subject` | `String` | yes | | The subject. | | `view` | `String` | yes | | The name of the view, e.g. `mail/welcome`. | | `model` | `Object` | no | | The model of the view. | | `language` | `String` | no | | The language for the view and the subject. | | `callback` | `Function` | no | | `function(err, message)`, the same as `message.callback()`. | Returns: `Message` The message that will be sent. Renders 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. Example: Welcome e-mail ```js MAIL(user.email, '@(Welcome)', 'mail/welcome', user, user.language, function(err) { err && console.log('Not sent', err); }); ``` ### HTMLMAIL() Type: `method` Sends an e-mail with an HTML body. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `email` | `String|Array` | yes | | One address, comma-separated addresses, or an array of addresses. Each becomes a `To:` recipient. | | `subject` | `String` | yes | | The subject. | | `body` | `String` | yes | | The HTML. | | `language` | `String` | no | | The language for translating the subject and the body. | | `callback` | `Function` | no | | `function(err, message)`, the same as `message.callback()`. | Returns: `Message` The message that will be sent. Sends `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. Example: Send HTML ```js HTMLMAIL('user@example.com', 'Password reset', '<p>Your code is <b>' + code + '</b>.</p>'); ``` ### LOGMAIL() Type: `method` Sends a short report as preformatted text. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `email` | `String|Array` | yes | | One address, comma-separated addresses, or an array of addresses. Each becomes a `To:` recipient. | | `subject` | `String` | no | | The subject (default `CONF.name`). | | `body` | `String|Object` | yes | | The text, or an object to serialize. | | `callback` | `Function` | no | | `function(err, message)`, the same as `message.callback()`. | Returns: `Message` The message that will be sent. Wraps `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()`. Example: Report ```js LOGMAIL('admin@example.com', 'Nightly import', { imported: 120, failed: 2 }); LOGMAIL('admin@example.com', 'The backup has finished.'); ``` ### DEF.onMail Type: `delegate` The function that builds and sends the messages of MAIL(), HTMLMAIL() and LOGMAIL(). | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `email` | `String|Array` | yes | | One address, comma-separated addresses, or an array of addresses. Each becomes a `To:` recipient. | | `subject` | `String` | yes | | The subject. | | `body` | `String` | yes | | The HTML body. | | `callback` | `Function` | no | | The callback. | | `reply` | `String` | no | | A reply address instead of `mail_reply`. | Returns: `Message` The message. Called 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`. Example: Add a header to every message ```js var onmail = DEF.onMail; DEF.onMail = function(email, subject, body, callback, reply) { var msg = onmail(email, subject, body, callback, reply); msg.headers = { 'X-Application': CONF.name }; return msg; }; ``` ### Mail Type: `class` The global SMTP client. Returns: `Object` `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. Example: Create and send ```js var msg = Mail.create('Hello', '<p>Hello</p>'); msg.from('info@example.com').to('user@example.com').send2(); ``` ### Mail.create() Type: `method` Creates a new message. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `subject` | `String` | yes | | The subject. | | `body` | `String` | yes | | The body (HTML by default). | Returns: `Message` A new message. Returns 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()`. Example: Create ```js var msg = Mail.create('Hello', '<p>Hello from Total.js</p>'); msg.from('info@example.com', 'My application'); msg.to('user@example.com'); msg.send2(); ``` ### Mail.send() Type: `method` Sends one or more messages with the given SMTP options. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `options` | `Object` | yes | | The SMTP options. | | `messages` | `Message|Array` | yes | | A message or an array of messages. | | `callback` | `Function` | no | | `function(err)`. | Opens 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. Example: Two messages, one connection ```js var a = Mail.create('A', '<p>A</p>').from('info@example.com').to('a@example.com'); var b = Mail.create('B', '<p>B</p>').from('info@example.com').to('b@example.com'); Mail.send(CONF.smtp, [a, b]); ``` ### Mail.send2() Type: `method` Sends messages with CONF.smtp. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `messages` | `Message|Array` | yes | | A message or an array of messages. | | `callback` | `Function` | no | | `function(err)`. | The same as `Mail.send(CONF.smtp, messages, callback)`. Example: Send ```js Mail.send2([msg1, msg2]); ``` ### Mail.try() Type: `method` Tests the connection and the login to an SMTP server. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `options` | `Object` | yes | | The SMTP options. | | `callback` | `Function` | no | | `function(err)`. | Returns: `Promise` Without a callback. Connects with `options`, logs in and quits without sending anything. Without a callback it returns a promise. Example: Check the settings ```js Mail.try(CONF.smtp).then(function() { console.log('SMTP works'); }).catch(function(err) { console.log('SMTP error:', err); }); ``` ### Mail.debug Type: `property` Prints the SMTP conversation to the console. Returns: `Boolean` Default `false`. With `true`, every line sent to and received from the server is printed. Default `false`. Example: Debug ```js Mail.debug = true; ``` ### Mail.on('send') Type: `event` Emitted when a connection is ready to send. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `connection` | `Object` | yes | | The internal connection object. | `Mail.on('send', function(connection) {})`. Emitted when the client starts the SMTP conversation of a connection. Example: Listen ```js Mail.on('send', function() { console.log('SMTP connection ready'); }); ``` ### Mail.on('error') Type: `event` Emitted on SMTP errors. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `err` | `Error|String` | yes | | The error. | | `connection` | `Object` | yes | | The internal connection object. | `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. Example: Log SMTP errors ```js Mail.on('error', function(err) { console.log('SMTP error', err); }); ``` ### ON('$mail') Type: `event` Emitted for every message that is being sent. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `message` | `Message` | yes | | The message. | `ON('$mail', function(message) {})`. Emitted just before the message is written to the SMTP server. Example: Log every e-mail ```js ON('$mail', function(message) { console.log('Sending', message.subject, 'to', message.email_to); }); ``` ### Mail.Message Type: `class` The message object. Returns: `Object` A 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`. Example: Chain ```js Mail.create('Hi', '<p>Hi</p>').from('info@example.com').to('a@example.com').cc('b@example.com').send2(); ``` ### message.to() Type: `method` Adds a recipient. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `email` | `String` | yes | | One address. | | `clear` | `Boolean` | no | `false` | Remove the current recipients first. | Returns: `Message` The message, for chaining. Adds one address to the `To:` header. With `clear`, the current recipients are removed first. Example: Recipients ```js msg.to('a@example.com').to('b@example.com'); ``` ### message.cc() Type: `method` Adds a copy recipient. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `email` | `String` | yes | | One address. | | `clear` | `Boolean` | no | `false` | Remove the current copies first. | Returns: `Message` The message, for chaining. Adds one address to the `Cc:` header. With `clear`, the current copies are removed first. Example: Copy ```js msg.cc('boss@example.com'); ``` ### message.bcc() Type: `method` Adds a blind copy recipient. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `email` | `String` | yes | | One address. | | `clear` | `Boolean` | no | `false` | Remove the current blind copies first. | Returns: `Message` The message, for chaining. Adds one address that receives the message without being listed in the headers. With `clear`, the current blind copies are removed first. Example: Blind copy ```js msg.bcc('archive@example.com'); ``` ### message.reply() Type: `method` Adds a reply address. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `email` | `String` | yes | | One address. | | `clear` | `Boolean` | no | `false` | Remove the current reply addresses first. | Returns: `Message` The message, for chaining. Adds one address to the `Reply-To:` header. With `clear`, the current reply addresses are removed first. Example: Reply to support ```js msg.reply('support@example.com'); ``` ### message.from() Type: `method` Sets the sender. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `email` | `String` | yes | | The address. | | `name` | `String` | no | | The display name. | Returns: `Message` The message, for chaining. Sets the `From:` address and, optionally, the display name. `message.sender()` is the same method. Example: Sender ```js msg.from('info@example.com', 'My application'); ``` ### message.sender() Type: `method` An alias of message.from(). | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `email` | `String` | yes | | The address. | | `name` | `String` | no | | The display name. | Returns: `Message` The message, for chaining. The same as `message.from(email, [name])`. Example: Sender ```js msg.sender('info@example.com'); ``` ### message.attachment() Type: `method` Attaches a file from the disk or a Buffer. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `filename` | `String|Buffer` | yes | | The path to the file, or a `Buffer` with the content. | | `name` | `String` | yes | | The file name for the recipient, with its extension. | | `contentid` | `String` | no | | The content ID for an inline file. | Returns: `Message` The message, for chaining. Adds 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. Example: Attach a PDF ```js msg.attachment(PATH.databases('invoices/2025-001.pdf'), 'invoice.pdf'); ``` Example: Inline image ```js var msg = HTMLMAIL('user@example.com', 'News', '<img src="cid:logo" />'); msg.attachment(PATH.public('img/logo.png'), 'logo.png', 'logo'); ``` Example: From a Buffer ```js var pdf = Buffer.from('%PDF-1.4 ...'); var msg = HTMLMAIL('user@example.com', 'Invoice', '<p>Your invoice is attached.</p>'); msg.attachment(pdf, 'invoice.pdf'); ``` ### message.attachmentfs(storage, id, [name], [contentid]) Type: `method` Attaches a file from a file storage. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `storage` | `String` | yes | | The name of the file storage. | | `id` | `String` | yes | | The id of the file in the storage. | | `name` | `String` | no | | The file name for the recipient, with its extension. Default: the name stored with the file. | | `contentid` | `String` | no | | The content ID for an inline file. | Returns: `Message` The message, for chaining. Adds 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>`. The 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. Example: Attach a stored file ```js var id = UID(); await FILESTORAGE('documents').save(id, 'contract.pdf', Buffer.from('%PDF-1.4 ...')); var msg = HTMLMAIL('user@example.com', 'Contract', '<p>The contract is attached.</p>'); msg.attachmentfs('documents', id); ``` Example: Another name ```js msg.attachmentfs('documents', id, 'contract-2025.pdf'); ``` ### message.unsubscribe() Type: `method` Adds the List-Unsubscribe headers. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `url` | `String` | yes | | The unsubscribe URL or e-mail address. | Returns: `Message` The message, for chaining. Adds `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:`). Example: Newsletter ```js msg.unsubscribe('https://example.com/unsubscribe/?id=' + user.id); ``` ### message.callback() Type: `method` Sets the function called with the result of the message. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `fn` | `Function` | yes | | `function(err, message)`. | Returns: `Message` The message, for chaining. `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. Example: Result ```js msg.callback(function(err, message) { if (err) console.log('Not sent:', message.subject, err); }); ``` ### message.manually() Type: `method` Stops the automatic sending. Returns: `Message` The message, for chaining. `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()`. Example: Send later ```js var msg = MAIL('user@example.com', 'Report', 'mail/report', data); msg.manually(); // ... msg.send2(); ``` ### message.send2() Type: `method` Sends the message with CONF.smtp. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `callback` | `Function` | no | | `function(err)`. | Sends the message with the configured SMTP server (`CONF.smtp`). Example: Send ```js Mail.create('Hello', '<p>Hello</p>').from('info@example.com').to('user@example.com').send2(function(err) { err && console.log(err); }); ``` ### message.send(options) Type: `method` Sends the message with other SMTP options. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `options` | `Object` | yes | | The SMTP options. | Returns: `Message` The message, for chaining. Sends the message over a new connection with `options` (the same keys as `CONF.smtp`). Use `message.callback()` for the result. Example: Another server ```js msg.callback(function(err) { err && console.log(err); }); msg.send({ server: 'smtp.other.com', port: 587, user: 'me@other.com', password: 'secret' }); ``` ### message.subject Type: `property` The subject. Returns: `String` The subject of the message. Non-ASCII characters are encoded for you. Example: Change ```js msg.subject = 'Updated subject'; ``` ### message.body Type: `property` The body. Returns: `String` The body of the message: HTML, or plain text when `type` is `plain`. Example: Change ```js msg.body = '<p>New text</p>'; ``` ### message.type Type: `property` The type of the body. Returns: `String` Default `html`. `html` (default) or `plain`. It becomes the `Content-Type` of the body (`text/html` or `text/plain`). Example: Plain text ```js var msg = Mail.create('Hello', 'Hello in plain text'); msg.type = 'plain'; ``` ### message.headers Type: `property` Extra headers of the message. Returns: `Object` An object of header names and values written into the message as they are. It is not set by default. Example: Custom header ```js msg.headers = { 'X-Campaign': 'spring-2025' }; ``` ### message.high() Type: `method` Marks the message as high priority. Returns: `Message` The same message. Adds the header `X-Priority: 1`. Returns the message. Example: Urgent ```js HTMLMAIL('admin@example.com', 'Disk full', '<p>The disk is full.</p>').high(); ``` ### message.low() Type: `method` Marks the message as low priority. Returns: `Message` The same message. Adds the header `X-Priority: 5`. Returns the message. Example: Weekly digest ```js MAIL(user.email, 'Your week', 'mail/digest', model).low(); ``` ### message.confidential() Type: `method` Marks the message as confidential. Returns: `Message` The same message. Adds the header `Sensitivity: Company-Confidential`. Returns the message. Example: Confidential report ```js HTMLMAIL('board@example.com', 'Salaries', html).confidential().high(); ``` ### CONF.smtp Type: `config` The SMTP server and its options. Returns: `Object` An 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. Before 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. Example: /config ```text smtp (json) : {"server":"smtp.example.com","port":465,"secure":true,"user":"info@example.com","password":"secret"} ``` Example: STARTTLS on port 587 ```text smtp (json) : {"server":"smtp.example.com","port":587,"user":"info@example.com","password":"secret"} ``` ### CONF.mail_smtp Type: `config` The SMTP server name. Returns: `String` Sets `CONF.smtp.server`. Use it with `mail_smtp_options` instead of one `smtp` object. Example: /config ```text mail_smtp : smtp.example.com ``` ### CONF.mail_smtp_options Type: `config` The SMTP options without the server. Returns: `Object` An object whose keys are copied into `CONF.smtp` (`port`, `secure`, `user`, `password`...). Example: /config ```text mail_smtp_options : {"port":587,"user":"info@example.com","password":"secret"} ``` ### CONF.mail_from Type: `config` The default sender address. Returns: `String` The `From:` address of `MAIL()`, `HTMLMAIL()` and `LOGMAIL()`. Without it, `CONF.smtp.from` or `CONF.smtp.user` is used. Example: /config ```text mail_from : info@example.com ``` ### CONF.mail_from_name Type: `config` The default sender name. Returns: `String` The display name of the sender of `MAIL()`, `HTMLMAIL()` and `LOGMAIL()`. Without it, `CONF.smtp.name` is used. Example: /config ```text mail_from_name : My application ``` ### CONF.mail_reply Type: `config` The default reply address. Returns: `String` One address added as `Reply-To:` to the messages of `MAIL()`, `HTMLMAIL()` and `LOGMAIL()`. Example: /config ```text mail_reply : support@example.com ``` ### CONF.mail_cc Type: `config` A default copy recipient. Returns: `String` One address added as `Cc:` to the messages of `MAIL()`, `HTMLMAIL()` and `LOGMAIL()`. Example: /config ```text mail_cc : office@example.com ``` ### CONF.mail_bcc Type: `config` A default blind copy recipient. Returns: `String` One address added as a blind copy to the messages of `MAIL()`, `HTMLMAIL()` and `LOGMAIL()`. Example: /config ```text mail_bcc : archive@example.com ``` ### $tapimail : true Type: `config` Sends the messages through the Total.js API instead of SMTP. Returns: `Boolean` Default `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. Example: /config ```text $tapimail : true secret_totalapi : your-totalapi-token ``` --- title: Scheduling and events project: Total.js V5 version: 0.0.20 section: reference language: en license: MIT url: https://totaljs.es/docs/total-js-v5/0-0-20/reference/scheduling-and-events/ updated: 2026-11-18T16:57:29.576Z --- # Scheduling and events > CRON(), ON(), ONCE(), OFF(), EMIT(), the built-in events, setTimeout2(), CLEANUP() and PAUSESERVER(). Global 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. The guide [Scheduling and events](../../guides/scheduling-and-events/) explains how they work together. ## API ### CRON(line, fn) Type: `method` Runs a function when the date matches a cron line. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `line` | `String` | yes | | The cron line, e.g. `0 3 * * *`. | | `fn` | `Function` | yes | | `function(date)`, called when the line matches. | Returns: `Object` The cron, with `check(date)`, `exec(date)` and `remove()`. The 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`). Example: Every day at 03:00 ```js CRON('0 3 * * *', function(date) { NOSQL('logs').remove().where('date', '<', date.add('-30 days')); }); ``` Example: Working days ```js CRON('30 8 * * mo-fr', function() { MAIL(CONF.mail_report, 'Daily report', 'mail/report', {}); }); ``` Example: Every 15 minutes ```js CRON('*/15 * * * *', function() { // at minutes 0, 15, 30 and 45 }); ``` ### cron.remove() Type: `method` Stops a cron. Removes the cron returned by `CRON()` from `F.crons`, so it does not run any more. Example: Run once ```js var cron = CRON('0 12 * * *', function() { sendreport(); cron.remove(); }); ``` ### F.crons Type: `property` The registered crons. Returns: `Array` An 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()`. Example: Count ```js console.log(F.crons.length + ' crons'); ``` ### ON(name, fn) Type: `method` Adds a listener of a global event. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `name` | `String` | yes | | The name of the event, or several names joined with `+`. | | `fn` | `Function` | yes | | The listener; it gets the arguments of `EMIT()`. | Join 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. Example: Own event ```js ON('order.created', function(order) { console.log('New order', order.id); }); ``` Example: Several events ```js ON('ready + service', function() { refreshcache(); }); ``` ### ONCE(name, fn) Type: `method` Adds a listener that runs only once. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `name` | `String` | yes | | The name of the event. | | `fn` | `Function` | yes | | The listener. | The 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. Example: First minute ```js ONCE('service', function() { console.log('The first minute has passed'); }); ``` ### OFF(name, [fn]) Type: `method` Removes a listener of a global event. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `name` | `String` | yes | | The name of the event. | | `fn` | `Function` | no | | The listener to remove. | With `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. Example: Remove a listener ```js function onservice(counter) { if (counter === 60) OFF('service', onservice); } ON('service', onservice); ``` ### EMIT(name, [a], [b], [c], [d], [e], [f], [g]) Type: `method` Emits a global event. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `name` | `String` | yes | | The name of the event. | | `a...g` | `Object` | no | | Up to seven arguments for the listeners. | Calls 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. Example: Emit ```js EMIT('order.created', { id: 123, email: 'buyer@example.com' }); ``` ### setTimeout2(id, callback, timeout, [limit]) Type: `method` A named timer that restarts on every call (a debounce). | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `id` | `String` | yes | | The name of the timer. | | `callback` | `Function` | yes | | The function to run. | | `timeout` | `Number` | yes | | The delay in milliseconds. | | `limit` | `Number` | no | `0` | How many times the timer can be postponed before a call runs the callback at once. `0` means no limit. | If 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`. With `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. Example: Save once after changes ```js function changed(doc) { setTimeout2('save' + doc.id, function() { NOSQL('docs').modify(doc).where('id', doc.id); }, 2000); } ``` Example: With a limit ```js function onkey(text) { // searches after a pause of 300 ms, or at once when the timer has been postponed 10 times setTimeout2('search', function() { search(text); }, 300, 10); } ``` ### clearTimeout2(id) Type: `method` Cancels a named timer of setTimeout2(). | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `id` | `String` | yes | | The name of the timer. | Returns: `Boolean` `true` when a timer was waiting. The callback of the timer does not run. Example: Cancel ```js if (clearTimeout2('save' + doc.id)) console.log('The pending save was canceled'); ``` ### CLEANUP(stream, [callback]) Type: `method` Calls a function when a stream is done and destroys the stream. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `stream` | `Stream` | yes | | A readable or writable stream. | | `callback` | `Function` | no | | Called when the stream is done. | Returns: `Promise` Without a callback. The 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. Example: Wait for a file ```js var writer = F.Fs.createWriteStream(PATH.temp('export.csv')); writer.end('id;name\n'); CLEANUP(writer, function() { console.log('Written'); }); ``` Example: With await ```js await CLEANUP(writer); ``` ### PAUSESERVER(name, [enable]) Type: `method` Pauses all incoming traffic under a name. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `name` | `String` | yes | | A name of the reason, shown on the page. | | `enable` | `Boolean` | no | | `true` to pause, `false` to resume; toggles when omitted. | Returns: `Boolean` `true` when the name is paused after the call. While 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. Example: During a migration ```js PAUSESERVER('Database migration', true); migrate(function() { PAUSESERVER('Database migration', false); }); ``` ### F.paused Type: `property` The names paused with PAUSESERVER(). Returns: `Array` An array of strings. The server answers with `503` while it is not empty. Example: Check ```js if (F.paused.length) console.log('Paused:', F.paused.join(', ')); ``` ### ON('ready', function() {}) Type: `event` The application is loaded. Emitted 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. Example: Start ```js ON('ready', function() { console.log('Ready on port', CONF.$port); }); ``` ### ON('load', function() {}) Type: `event` Emitted right after ready. Emitted once after `ready`, when the load of the application is complete. Unlike `ready`, a listener added later is not called. Example: Load ```js ON('load', function() { console.log('Loaded'); }); ``` ### ON('service', function(counter) {}) Type: `event` Emitted once a minute by the service timer. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `counter` | `Number` | yes | | Minutes since the start. | Emitted 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. Example: Every 10 minutes ```js ON('service', function(counter) { if (counter % 10 === 0) refresh(); }); ``` ### ON('exit', function(signal) {}) Type: `event` The process is stopping. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `signal` | `Number` | yes | | The signal passed to `F.exit()`; `15` by default. | Emitted 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. Example: Last log ```js ON('exit', function(signal) { console.log('Exit', signal); }); ``` ### ON('error', function(obj) {}) Type: `event` The framework logged an error. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `obj` | `Object` | yes | | `{ error: String, name: String, url: String, date: Date }`. | Emitted 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`. Example: Send errors elsewhere ```js ON('error', function(obj) { console.log(obj.date, obj.name, obj.error, obj.url); }); ``` ### ON('request', function(ctrl) {}) Type: `event` An HTTP request arrived. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `ctrl` | `Controller` | yes | | The controller of the request. | Emitted 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. Example: Health check ```js ON('request', function(ctrl) { if (ctrl.url === '/health/') { ctrl.cancel(); ctrl.text('OK'); } }); ``` ### ON('controller', function(ctrl) {}) Type: `event` A route was found for an HTTP request. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `ctrl` | `Controller` | yes | | The controller of the request. | Emitted 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. Example: Log routes ```js ON('controller', function(ctrl) { console.log(ctrl.method, ctrl.url); }); ``` ### ON('componentator', function(meta) {}) Type: `event` COMPONENTATOR() is about to download components. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `meta` | `Object` | yes | | `{ name: String, components: String }`. | `meta` is `{ name, components }`. Change `meta.components` to change the list of components that is downloaded. Example: Add a component ```js ON('componentator', function(meta) { meta.components += ',exec'; }); ``` ### ON('flowstream_error', function(meta) {}) Type: `event` A component of a FlowStream failed. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `meta` | `Object` | yes | | `{ id, name, error, source, instanceid, componentid }`. | Emitted 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. Example: Log ```js ON('flowstream_error', function(meta) { console.log(meta.name, meta.componentid, meta.error); }); ``` ### ON('flowstream', function(instance) {}) Type: `event` · Since: `0.0.16` A FlowStream instance was created. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `instance` | `Object` | yes | | The FlowStream instance. | Emitted 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/). Example: Log ```js ON('flowstream', function(instance) { console.log('FlowStream', instance.id); }); ``` ### ON('$mail', function(message) {}) Type: `event` An e-mail is being sent. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `message` | `Object` | yes | | The mail message. | Emitted 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/). Example: Log ```js ON('$mail', function(message) { console.log('Mail', message.subject, message.email_to); }); ``` ### ON('$stats', function(stats) {}) Type: `event` The usage statistics of the process were updated. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `stats` | `Object` | yes | | The statistics of the process. | Emitted 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. The 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. Example: Watch memory ```js ON('$stats', function(stats) { if (stats.memory > 500) console.log('High memory', stats.memory, 'MB'); }); ``` ### ON('$message', function(msg, handle) {}) Type: `event` The process received a message from its parent. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `msg` | `Object` | yes | | The message. | | `handle` | `Object` | yes | | The handle sent with the message, if any. | Emitted 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. Example: Command ```js ON('$message', function(msg) { if (msg && msg.type === 'reload') reload(); }); ``` ### ON('$update', function() {}) Type: `event` Another process of the cluster asked for an update. Emitted 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. Example: Keep a cluster in sync ```js // the process that changed the data process.send && process.send('total:update'); // all other processes ON('$update', function() { reloadsettings(); }); ``` --- title: File storage project: Total.js V5 version: 0.0.20 section: reference language: en license: MIT url: https://totaljs.es/docs/total-js-v5/0-0-20/reference/file-storage/ updated: 2026-11-19T16:17:02.153Z --- # File storage > FILESTORAGE() and its methods, the file metadata, the @upload flag and file.fs(). Methods 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/). ## API ### FILESTORAGE(name) Type: `method` Returns a file storage by its name. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `name` | `String` | yes | | The name of the storage. | Returns: `FileStorage` The file storage. Creates 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)`. Example: Save and read a file ```js var fs = FILESTORAGE('files'); fs.save('readme', 'readme.txt', Buffer.from('Hello'), function(err, meta) { fs.readbuffer('readme', function(err, buffer) { console.log(buffer.toString('utf8')); }); }); ``` ### fs.name Type: `property` The name of the storage. Returns: `String` The name given to `FILESTORAGE(name)`. ### fs.directory Type: `property` The directory of the storage. Returns: `String` The absolute path of the directory with the files, by default `/databases/fs-{name}/`. Set it with `fs.storage(path)`. ### fs.storage(path) Type: `method` Changes the directory of the storage. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `path` | `String` | yes | | An absolute path of the directory. | Returns: `FileStorage` The storage itself. Sets `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. Example: Another disk ```js FILESTORAGE('videos').storage('/mnt/media/videos/'); ``` ### fs.save(id, name, source, [custom], [callback], [expire], [headers]) Type: `method` Saves a file into the storage. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `id` | `String` | yes | | Your identifier of the file, for example from `UID()`. | | `name` | `String` | yes | | The file name with its extension. | | `source` | `String|Buffer|Stream` | yes | | A path, a `Buffer`, a readable stream or an `https://` URL. | | `custom` | `Object` | no | `null` | Custom data stored with the file. | | `callback` | `Function` | no | | Called as `callback(err, meta)`. Without it the method returns a `Promise`. | | `expire` | `String` | no | | A time after which the file can no longer be read, such as `'1 day'`. | | `headers` | `Object` | no | | HTTP headers for downloading a URL. | Returns: `FileStorage|Promise` The storage, or a `Promise` with the metadata without a callback. `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. The callback receives the metadata: `id`, `name`, `ext`, `type`, `size`, `width`, `height`, `custom`, `date` and `expire`. Example: From a file on the disk ```js FILESTORAGE('files').save(UID(), 'report.pdf', PATH.root('report.pdf'), function(err, meta) { console.log(meta.id, meta.size); }); ``` Example: With custom data and expiration ```js var meta = await FILESTORAGE('exports').save(UID(), 'export.csv', Buffer.from(csv), { userid: $.user.id }, null, '1 day'); ``` ### fs.insert(id, name, source, [custom], [callback], [expire], [headers]) Type: `method` An alias of fs.save(). Returns: `FileStorage|Promise` Works exactly as `fs.save()`. ### fs.savejson(id, value, [callback]) Type: `method` Saves a value as a JSON file. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `id` | `String` | yes | | The id of the file. | | `value` | `Object` | yes | | A value to serialize. | | `callback` | `Function` | no | | Called as `callback(err, meta)`. Without it the method returns a `Promise`. | Returns: `FileStorage|Promise` Serializes `value` with `JSON.stringify()` and saves it as `{id}.json` (content type `application/json`). Read it back with `fs.readjson()`. Example: Store settings ```js FILESTORAGE('data').savejson('settings', { theme: 'dark' }, function(err, meta) {}); ``` ### fs.read(id, [callback], [nostream]) Type: `method` Reads a file as a stream. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `id` | `String` | yes | | The id of the file. | | `callback` | `Function` | no | | Called as `callback(err, meta)`. Without it the method returns a `Promise`. | | `nostream` | `Boolean` | no | `false` | `true` returns only the metadata. | Returns: `FileStorage|Promise` The 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. Example: Pipe into a file ```js FILESTORAGE('files').read('readme', function(err, meta) { if (!err) meta.stream.pipe(F.Fs.createWriteStream(PATH.tmp(meta.name))); }); ``` ### fs.readmeta(id, [callback], [keepfd]) Type: `method` Reads only the metadata of a file. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `id` | `String` | yes | | The id of the file. | | `callback` | `Function` | no | | Called as `callback(err, meta, filename, fd)`. Without it the method returns a `Promise`. | | `keepfd` | `Boolean` | no | `false` | `true` keeps the file descriptor open and passes it to the callback. | Returns: `FileStorage|Promise` Reads 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. Example: Check a file ```js var meta = await FILESTORAGE('files').readmeta('readme'); console.log(meta.name, meta.size, meta.date); ``` ### fs.readbuffer(id, [callback]) Type: `method` Reads the whole content into a Buffer. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `id` | `String` | yes | | The id of the file. | | `callback` | `Function` | no | | Called as `callback(err, buffer, meta)`. Without it the method returns a `Promise`. | Returns: `FileStorage|Promise` Use it for small files; stream big files with `fs.read()`. The promise resolves with the buffer only. Example: Read a file ```js var buffer = await FILESTORAGE('files').readbuffer('readme'); ``` ### fs.readbase64(id, [callback]) Type: `method` Reads the content as a base64 string. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `id` | `String` | yes | | The id of the file. | | `callback` | `Function` | no | | Called as `callback(err, base64, meta)`. Without it the method returns a `Promise`. | Returns: `FileStorage|Promise` Handy for data URIs and JSON APIs. The promise resolves with the string only. Example: A data URI ```js FILESTORAGE('photos').readbase64('avatar', function(err, base64, meta) { var uri = 'data:' + meta.type + ';base64,' + base64; }); ``` ### fs.readjson(id, callback) Type: `method` Reads a JSON file. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `id` | `String` | yes | | The id of the file. | | `callback` | `Function` | yes | | Called as `callback(err, value, meta)`. | Returns: `FileStorage` Reads the content and parses it as JSON (dates included). The callback is required. Example: Read settings ```js FILESTORAGE('data').readjson('settings', function(err, value) { console.log(value.theme); }); ``` ### fs.readfilename(id) Type: `method` Returns the path of the stored file. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `id` | `String` | yes | | The id of the file. | Returns: `String` The path. Returns the absolute path of `{group}/{id}.file`. The file starts with a 2000-byte header, so do not serve it directly. ### fs.makedirectory(id) Type: `method` Returns the directory for an id. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `id` | `String` | yes | | The id of the file. | Returns: `String` The path. Returns the path of the four-digit group directory where the file with this id is stored. It does not create the directory. ### fs.image(id, [callback]) Type: `method` Loads a stored file as an image. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `id` | `String` | yes | | The id of the file. | | `callback` | `Function` | no | | Called as `callback(err, image, meta)`. Without it the method returns a `Promise`. | Returns: `FileStorage|Promise` Returns an image object of [Images](../../guides/images/) that reads the content of the file. Transform it and save or pipe it. Example: Create a thumbnail ```js FILESTORAGE('photos').image('avatar', function(err, image) { image.resize(100, 100); image.save(PATH.public('thumbs/avatar.jpg'), function(err) {}); }); ``` ### fs.http($, opt) Type: `method` Sends a stored file as an HTTP response. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `$` | `Controller` | yes | | The controller of the request. | | `opt` | `Object` | yes | | The options: `id`, `download`, `check`, `image`, `cache`. | Returns: `undefined` Sets 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. Options: `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. Example: Serve and download ```js exports.install = function() { ROUTE('GET /files/{id}/', function($) { FILESTORAGE('files').http($, { id: $.params.id }); }); ROUTE('GET /download/{id}/', function($) { FILESTORAGE('files').http($, { id: $.params.id, download: true }); }); }; ``` Example: A resized image ```js ROUTE('GET /thumbs/{id}/', function($) { FILESTORAGE('photos').http($, { id: $.params.id, cache: 'thumb-' + $.params.id, image: image => image.resize(200, 200) }); }); ``` ### fs.remove(id, [callback]) Type: `method` Removes a file. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `id` | `String` | yes | | The id of the file. | | `callback` | `Function` | no | | Called as `callback(err)`. Without it the method returns a `Promise`. | Returns: `FileStorage|Promise` Deletes the `.file` and its line in the index. The callback receives an error of the file system when the file does not exist. Example: Remove a file ```js FILESTORAGE('files').remove($.params.id, function(err) { $.success(); }); ``` ### fs.rename(id, newname, [callback]) Type: `method` Changes the stored name of a file. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `id` | `String` | yes | | The id of the file. | | `newname` | `String` | yes | | The new file name. | | `callback` | `Function` | no | | Called as `callback(err, meta)`. Without it the method returns a `Promise`. | Returns: `FileStorage|Promise` Writes 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. Example: Rename ```js await FILESTORAGE('files').rename('readme', 'README.md'); ``` ### fs.copy(id, path, [callback]) Type: `method` Copies the content of a file out of the storage. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `id` | `String` | yes | | The id of the file. | | `path` | `String` | yes | | A target file name or a directory. | | `callback` | `Function` | no | | Called as `callback(err, meta)`. Without it the method returns a `Promise`. | Returns: `Promise|undefined` Writes 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. Example: Export a file ```js FILESTORAGE('files').copy('readme', PATH.tmp(), function(err, meta) { console.log(PATH.tmp(meta.name)); }); ``` ### fs.clone(id, [newid], [callback]) Type: `method` Duplicates a file under a new id. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `id` | `String` | yes | | The id of the source file. | | `newid` | `String` | no | `UID()` | The new id. | | `callback` | `Function` | no | | Called as `callback(err, meta)`. Without it the method returns a `Promise`. | Returns: `Promise|undefined` Copies 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. Example: Clone ```js FILESTORAGE('files').clone('template', function(err, meta) { console.log(meta.id); }); ``` Example: Promise ```js var meta = await FILESTORAGE('files').clone('template'); console.log(meta.id); // a new UID ``` ### fs.browse([callback]) Type: `method` Lists files from the index. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `callback` | `Function` | no | | Called as `callback(err, files)`. | Returns: `QueryBuilder` A NoSQL query builder. Returns 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. Example: Latest PDF files ```js FILESTORAGE('files').browse().where('ext', 'pdf').sort('date', true).take(10).callback(function(err, files) { console.log(files); }); ``` ### fs.browse2([callback]) Type: `method` Lists files from the disk. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `callback` | `Function` | no | | Called as `callback(err, files)`. Without it the method returns a `Promise`. | Returns: `FileStorage|Promise` Reads 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. Example: All files ```js var files = await FILESTORAGE('files').browse2(); console.log(files.length); ``` ### fs.stream(onfile, [callback], [workers]) Type: `method` Walks all files of the storage. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `onfile` | `Function` | yes | | Called as `onfile(meta, next)`. | | `callback` | `Function` | no | | Called when all files were processed. | | `workers` | `Number` | no | `2` | Parallel files. | Returns: `FileStorage` Calls `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. Example: Total size ```js var size = 0; FILESTORAGE('files').stream(function(meta, next) { size += meta.size; next(); }, () => console.log(size)); ``` ### fs.count2([callback]) Type: `method` Counts the files on the disk. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `callback` | `Function` | no | | Called as `callback(err, count)`. Without it the method returns a `Promise`. | Returns: `FileStorage|Promise` Counts the files in the group directories of the storage. Example: Count ```js var count = await FILESTORAGE('files').count2(); ``` ### fs.rebuild([callback]) Type: `method` Rebuilds the index from the disk. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `callback` | `Function` | no | | Called as `callback()`. Without it the method returns a `Promise`. | Returns: `FileStorage|Promise` Reads 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. Example: Rebuild ```js await FILESTORAGE('files').rebuild(); ``` ### fs.clear([callback]) Type: `method` Removes all files of the storage. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `callback` | `Function` | no | | Called as `callback(err, count)`. Without it the method returns a `Promise`. | Returns: `FileStorage|Promise` Deletes 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. Example: Clear ```js FILESTORAGE('tmp').clear(function(err, count) { console.log('Removed', count); }); ``` ### fs.drop([callback]) Type: `method` An alias of fs.clear(). | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `callback` | `Function` | no | | Called as `callback(err, count)`. Without it the method returns a `Promise`. | Returns: `FileStorage|Promise` Works exactly as `fs.clear()`. ### fs.backup(filename, [callback]) Type: `method` Backs up the whole storage into one file. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `filename` | `String|Stream` | yes | | A target file name or a writable stream. | | `callback` | `Function` | no | | Called as `callback(err, result)`. Without it the method returns a `Promise`. | Returns: `Promise|undefined` Writes 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 }`. Example: Backup ```js var result = await FILESTORAGE('files').backup(PATH.root('files.backup')); console.log(result.files, result.size); ``` ### fs.restore(filename, [callback]) Type: `method` Restores a backup. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `filename` | `String|Stream` | yes | | A backup file name or a readable stream. | | `callback` | `Function` | no | | Called as `callback(err, meta)`. Without it the method returns a `Promise`. | Returns: `Promise|undefined` Removes 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. Example: Restore and index ```js var fs = FILESTORAGE('files'); fs.restore(PATH.root('files.backup'), function(err) { !err && fs.rebuild(); }); ``` ### meta Type: `type` The metadata of a stored file. Returned by `save()`, `read()`, `readmeta()` and the other methods and stored in the header of each file: - `id` {String}: the id, - `name` {String}: the file name, - `ext` {String}: the extension without the dot, - `type` {String}: the content type, - `size` {Number}: the size of the content in bytes, - `width`, `height` {Number}: dimensions of JPEG, PNG, GIF and SVG images, - `custom` {Object}: your custom data or `null`, - `date` {Date}: when the file was saved, - `expire` {Date}: when the file expires (only when set). `read()` adds `stream`, and `stream()` and `browse2()` add `index`. ### ROUTE('POST /url/ @upload') Type: `type` A route flag for multipart uploads. A 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`. Example: An upload route ```js exports.install = function() { ROUTE('POST /api/upload/ @upload <10MB', function($) { var file = $.files[0]; file.fs('files', UID(), $.callback()); }); }; ``` ### file.fs(storage, id, [callback]) Type: `method` Saves an uploaded file into a file storage. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `storage` | `String` | yes | | The name of the storage. | | `id` | `String` | yes | | The id of the file. | | `callback` | `Function` | no | | Called as `callback(err, meta)`. Without it the method returns a `Promise`. | Returns: `FileStorage|Promise` A method of `HttpFile` (the items of `$.files`). Saves the temporary file into `FILESTORAGE(storage)` with its original file name and returns the metadata. Example: Save all uploads ```js function upload($) { $.files.wait(function(file, next) { file.fs('files', UID(), next); }, () => $.success()); } ``` ### Utils.filestreamer(filename, onbuffer, [onend], [size], [offset]) Type: `method` Reads a file in chunks, with progress. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `filename` | `String` | yes | | The path of the file. | | `onbuffer` | `Function` | yes | | Called as `onbuffer(buffer, next, percentage)`; `next(true)` stops reading. | | `onend` | `Function` | no | | Called as `onend(err)` at the end, after a stop or on an error. | | `size` | `Number` | no | `16384` | The size of a chunk in bytes. | | `offset` | `Number` | no | `0` | The position in bytes where reading starts. | Returns: `undefined` Reads 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. Example: Hash a file ```js var hash = F.Crypto.createHash('sha1'); Utils.filestreamer(PATH.root('big.iso'), function(buffer, next) { hash.update(buffer); next(); }, function(err) { console.log(hash.digest('hex')); }); ``` --- title: Plugins and components project: Total.js V5 version: 0.0.20 section: reference language: en license: MIT url: https://totaljs.es/docs/total-js-v5/0-0-20/reference/plugins-and-components/ updated: 2026-11-18T16:57:29.576Z --- # Plugins and components > The plugin definition, PLUGINS, COMPONENTATOR(), NEWCOMPONENT() with its Component, Instance and Message objects, NPMINSTALL(), REQUIRE() and IMPORT(). Properties 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/). ## API ### plugins/{id}/index.js Type: `type` A folder in plugins/ with an index.js file, loaded at start. Every 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. Example: A minimal plugin ```js // plugins/contacts/index.js exports.name = 'Contacts'; exports.icon = 'ti ti-address-book'; exports.permissions = ['contacts']; exports.install = function() { ROUTE('+API ? contacts_list --> Contacts/list'); }; ``` ### exports.install = function() {} Type: `delegate` Called once when the plugin is loaded. Register 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. Example: Routes and a ready handler ```js exports.install = function() { ROUTE('+GET /admin/contacts/', function($) { $.view('#contacts/views/index'); }); ON('ready', function() { // all plugins are loaded }); }; ``` ### exports.id Type: `property` The id of the plugin. Returns: `String` When `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. ### exports.name Type: `property` A human readable name of the plugin. Returns: `String` Total.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. Example: Name ```js exports.name = 'Orders'; ``` ### exports.permissions Type: `property` The permissions the plugin defines. Returns: `Array` An 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/)). Example: Permissions ```js exports.permissions = [ { id: 'orders', name: 'Orders' }, { id: 'orders_remove', name: 'Remove orders' } ]; ``` ### exports.icon, exports.visible, exports.position, ... Type: `property` Your own properties of a plugin. Total.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`. Example: Menu data ```js exports.icon = 'ti ti-truck'; exports.position = 5; exports.visible = function(user) { return user.sa || user.permissions.includes('orders'); }; ``` ### PLUGINS Type: `property` All loaded plugins by id. Returns: `Object` id: exports An 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. Example: List plugins ```js ON('ready', function() { for (var id in PLUGINS) console.log(id, PLUGINS[id].name); }); ``` ### plugins/{id}/config Type: `config` · Since: `0.0.16` Configuration file of a plugin. A `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. Example: Defaults of a plugin ```text shop_currency : EUR shop_pagesize : 20 ``` ### plugins/{id}/index.flow Type: `type` · Since: `0.0.19` A FlowStream loaded with the plugin. An `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/). ### PLUGINS[id].flowstream Type: `property` · Since: `0.0.19` The FlowStream instance loaded from index.flow. Returns: `FlowStream` Set when the `index.flow` file of the plugin has been loaded. ### PATH.plugins([path]) Type: `method` Returns a path in the plugins folder. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `path` | `String` | no | | A relative path such as "shop/data.json" | Returns: `String` Absolute path Without 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. Example: Read a file of a plugin ```js var filename = PATH.plugins('shop/data/countries.json'); F.Fs.readFile(filename, 'utf8', function(err, data) { // ... }); ``` ### controller.view('#{id}/path') Type: `type` Renders a view from a plugin folder. A 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. Example: A view of a plugin ```js exports.install = function() { ROUTE('+GET /admin/shop/', function($) { $.view('#shop/views/index'); }); }; ``` ### COMPONENTATOR(name, components, [removeprev], [attrs]) Type: `method` Downloads a bundle of UI components from Componentator. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `name` | `String` | yes | | Name of the bundle; used in the file name and as the key in REPO | | `components` | `String` | yes | | Comma separated component names | | `removeprev` | `Boolean` | no | `true` | Delete older bundles with the same name | | `attrs` | `String` | no | `''` | Extra URL-encoded fields sent with the download request | Downloads 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`. Example: A UI bundle ```js // definitions/ui.js COMPONENTATOR('ui', 'exec,locale,input,box,validate,loading,notify,datagrid', true); ``` Example: In the layout ```html <script src="@{REPO.ui}"></script> ``` ### ON('componentator', function(meta) {}) Type: `event` Emitted before COMPONENTATOR() builds the file name. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `meta` | `Object` | yes | | { name, components } | `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. Example: Add a component everywhere ```js ON('componentator', function(meta) { meta.components += ',errorhandler'; }); ``` ### NEWCOMPONENT(html, [callback]) Type: `method` Compiles a server component. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `html` | `String` | yes | | File name, HTML or URL | | `callback` | `Function` | no | | function(err, component) | Returns: `Promise<Component>` When callback is not set `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. Example: From the components folder ```js NEWCOMPONENT('uppercase', function(err, com) { if (err) { console.error(err); return; } var instance = com.create(); }); ``` Example: Inline ```js var html = '<script total>exports.make = function(instance) { instance.message = msg => msg.send(\'output\', msg.data * 2); };</script>'; var com = await NEWCOMPONENT(html); ``` ### components/{name}.html Type: `type` The format of a server component. An 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`). Example: A complete file ```html <script total> exports.name = 'Counter'; exports.config = { step: 1 }; exports.inputs = [{ id: 'input', name: 'Value' }]; exports.outputs = [{ id: 'output', name: 'Sum' }]; exports.make = function(instance, config) { var sum = 0; instance.message = function(msg) { sum += config.step; msg.send('output', sum); }; }; </script> <readme> Counts incoming messages. </readme> <settings> <div>Step of the counter</div> </settings> ``` ### Component Type: `class` A compiled server component. The 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`. ### exports.make = function(instance, config, status) {} Type: `delegate` Sets up a new instance. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `instance` | `Instance` | yes | | The new instance | | `config` | `Object` | yes | | Its configuration | | `status` | `Object` | yes | | The second argument of create() | Called 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. Example: Handlers ```js exports.make = function(instance, config) { instance.message = function(msg) { msg.send('output', msg.data); }; instance.configure = function() { // config has changed }; }; ``` ### exports.config Type: `property` Default configuration of instances. Returns: `Object` Each instance gets a clone of this object, extended with the options passed to `component.create()`. ### exports.inputs / exports.outputs Type: `property` Inputs and outputs of the component. Returns: `Array` Arrays 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`. Example: With a schema ```js exports.inputs = [{ id: 'user', name: 'User', schema: 'name:String, email:Email' }]; exports.outputs = [{ id: 'ok', name: 'Valid' }, { id: 'error', name: 'Invalid' }]; exports.make = function(instance) { instance.message = function(msg) { if (msg.error) msg.send('error', msg.error.toString()); else msg.send('ok', msg.data); }; }; ``` ### exports.npm Type: `property` NPM packages the component needs. Returns: `String[]` An 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. Example: Dependencies ```js exports.npm = ['mqtt']; exports.make = function(instance, config) { var mqtt = require('mqtt'); // ... }; ``` ### exports.install = function(component) {} Type: `delegate` Called once after the component is compiled. Runs with the component as `this` and as the argument, after NPM packages are installed and schemas are compiled. ### exports.onextend = function(instance) {} Type: `delegate` Extends each new instance before make(). Called in `component.create()` after the configuration is set and before `make()`. ### exports.oncreate = function(instance) {} Type: `delegate` Called after an instance is created. Runs asynchronously (in `setImmediate`) after `make()`. ### exports.onremove = function(instance) {} Type: `delegate` Called when an instance is removed. Called by `instance.remove()` after the `close` and `destroy` handlers of the instance. ### component.ui Type: `property` The UI parts of the component file. Returns: `Object` An object with `readme`, `settings`, `css`, `js`, `html`, `schema` and `template` (only the parts found in the file). ### component.instances Type: `property` All instances of the component. Returns: `Instance[]` `create()` adds an instance and `instance.remove()` removes it. ### component.debugger Type: `property` Prints status, debug, error and output messages to the console. Returns: `Boolean` `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. ### component.output = function(instance, msg) {} Type: `delegate` Receives every message sent to an output. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `instance` | `Instance` | yes | | The sender | | `msg` | `Message` | yes | | msg.output and msg.data | Called 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. Example: Collect results ```js var com = await NEWCOMPONENT('uppercase'); com.output = function(instance, msg) { console.log(instance.id, msg.output, msg.data); }; ``` ### component.create([options], [status]) Type: `method` Creates an instance. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `options` | `Object` | no | | Configuration of the instance | | `status` | `Object` | no | | Passed to make() as the third argument | Returns: `Instance` The 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. Example: Two instances ```js var a = com.create({ prefix: 'A: ' }); var b = com.create({ prefix: 'B: ' }); ``` ### component.service(counter) Type: `method` Calls instance.service(counter) on all instances. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `counter` | `Number` | yes | | Any value passed to the instances | Total.js does not call it for you. Call it from `ON('service')` when your instances need a periodic tick. Example: Every minute ```js ON('service', function(counter) { com.service(counter); }); ``` ### Instance Type: `class` An instance of a server component. Returned 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`. ### instance.message = function(msg) {} Type: `delegate` Handles data that comes to an input. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `msg` | `Message` | yes | | The incoming message | Called 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. Example: Per input ```js exports.make = function(instance) { instance.message = NOOP; instance.message_reset = function(msg) { // only for input "reset" }; }; ``` ### instance.input(input, data, [callback]) Type: `method` Sends data to an input of the instance. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `input` | `String` | yes | | Input id | | `data` | `Object` | yes | | The data | | `callback` | `Function` | no | | function(msg) | Creates 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()`. Example: Call and read the result ```js instance.input('input', 'hello', function(msg) { console.log(msg.output, msg.data); }); ``` ### instance.send(output, data) Type: `method` · Since: `0.0.17` Sends new data to an output. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `output` | `String` | yes | | Output id | | `data` | `Object` | yes | | The data | Creates 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). Example: A timer ```js exports.make = function(instance) { var timer = setInterval(() => instance.send('output', new Date()), 5000); instance.close = () => clearInterval(timer); }; ``` ### instance.status(value) / debug(value) / throw(err) / dashboard(value) Type: `method` Reports a state of the instance. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `value` | `Object` | yes | | Any value | Each 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. Example: Report ```js instance.status({ connected: true }); instance.throw(new Error('Connection refused')); ``` ### instance.activity(key, name, value) Type: `method` · Since: `0.0.19` Reports an activity of the instance. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `key` | `String` | yes | | Identifier of the activity | | `name` | `String` | yes | | Label | | `value` | `Object` | yes | | For example a progress | Calls `component.activity(instance, { key, name, value })`, which prints `ACTIVITY` to the console when `component.debugger` is on. Replace `component.activity` to process it. ### instance.reconfigure(options) Type: `method` Changes the configuration of an instance. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `options` | `Object` | yes | | New values | Copies the keys of `options` to `instance.config` and calls `instance.configure(config)` when it is defined. Example: Change a value ```js instance.reconfigure({ prefix: '>> ' }); ``` ### instance.remove() Type: `method` Removes the instance. Calls `instance.close(true)` and `instance.destroy()` when defined, then `component.onremove(instance)`, and removes the instance from `component.instances`. Example: Remove ```js instance.remove(); ``` ### instance.replace(str, [data], [encoding]) Type: `method` Replaces {key} placeholders in a string. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `str` | `String|Object` | yes | | Template | | `data` | `Object` | no | | Values | | `encoding` | `String|Function` | no | | Encoding of the values | Returns: `String|Object` Each `{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. Example: A URL ```js com.variables.api = 'https://api.example.com'; var url = instance.replace('{api}/users/{id}/', { id: 15 }); ``` ### Message Type: `class` Data that flows through a component instance. Created 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). ### msg.send(output, [data]) Type: `method` Sends the message to an output. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `output` | `String` | yes | | Output id | | `data` | `Object` | no | | New data | Sets `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()`. Example: Forward ```js instance.message = function(msg) { msg.send('output', { received: msg.data }); }; ``` ### msg.end() / msg.destroy() Type: `method` Releases the message. Clears `data`, `vars`, `repo` and the instance, so later `msg.send()` calls do nothing. ### NPMINSTALL(name, [callback]) Type: `method` Installs an NPM package. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `name` | `String` | yes | | Package name, optionally with @version | | `callback` | `Function` | no | | function(err) | Returns: `Promise` When callback is not set Runs `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. Example: Install and load ```js NPMINSTALL('qrcode@1.5.4', function(err) { if (err) { console.error(err); return; } var QR = REQUIRE('qrcode'); }); ``` ### REQUIRE(name) Type: `method` Loads a Node.js or NPM module. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `name` | `String` | yes | | Module name | Returns: `Object` The module Names 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. Example: Load ```js var Fs = REQUIRE('fs'); var mqtt = REQUIRE('mqtt'); ``` ### IMPORT(url, [callback]) Type: `method` Downloads and loads a remote JavaScript module. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `url` | `String` | yes | | URL of a .js file | | `callback` | `Function` | no | | function(err, module, response) | Returns: `Promise` When callback is not set The 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. Example: Promise ```js var helpers = await IMPORT('https://cdn.example.com/helpers.js'); helpers.hello(); ``` --- title: FlowStream project: Total.js V5 version: 0.0.20 section: reference language: en license: MIT url: https://totaljs.es/docs/total-js-v5/0-0-20/reference/flowstream/ updated: 2026-11-18T16:57:29.576Z --- # FlowStream > The Flow global, running FlowStreams, components, instances, messages and the flow5 command. Methods, 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/). ## API ### Flow / FlowStream Type: `class` The global object of the FlowStream engine. `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`. Example: List running flows ```js for (var id in Flow.instances) console.log(id, Flow.instances[id].stats); ``` ### Flow.load(schema, [callback]) Type: `method` Starts a FlowStream from its schema. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `schema` | `Object` | yes | | The FlowStream schema | | `callback` | `Function` | no | | `function(err, flowstream)` | Missing 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. Example: Load a file ```js var schema = (await F.readfile(PATH.root('orders.json'), 'utf8')).parseJSON(); Flow.load(schema, function(err, flowstream) { err && console.error(err); }); ``` Example: Run in a worker thread ```js Flow.load({ id: 'import', worker: 'worker', components: {}, design: {} }); ``` ### Flow.init([directory], [callback]) Type: `method` Loads all .flow files of a directory. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `directory` | `String` | no | `PATH.root('flowstreams')` | Directory with .flow files | | `callback` | `Function` | no | | Called when all files are loaded | Reads 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. Example: Another directory ```js Flow.init(PATH.root('data/flows'), function() { console.log('Loaded:', Object.keys(Flow.instances)); }); ``` ### Flow.reload(schema, [restart]) Type: `method` Applies a new schema to a running FlowStream. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `schema` | `Object` | yes | | The new schema | | `restart` | `Boolean` | no | `false` | Restart the worker | Returns: `Boolean` `true` when the FlowStream exists The 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. ### Flow.remove(id) Type: `method` Stops and removes a FlowStream. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `id` | `String` | yes | | FlowStream id | Closes all instances, ends the worker, removes the FlowStream from `Flow.instances` and emits `remove`. Example: Remove ```js Flow.remove('orders'); ``` ### Flow.restart(id) Type: `method` Restarts a FlowStream that runs in a worker. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `id` | `String` | yes | | FlowStream id | Returns: `Boolean` `true` when found Ends 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. ### Flow.socket(id, websocket, [verify], [check]) Type: `method` Connects the Total.js Flow editor to a FlowStream. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `id` | `String` | yes | | FlowStream id | | `websocket` | `WebSocket` | yes | | The WebSocket of the route | | `verify` | `Function` | no | | `function(client, next)` | | `check` | `Function` | no | | `function(client, message)` returns `true` or an error | Pass 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. Example: Route for the editor ```js exports.install = function() { ROUTE('+SOCKET /flowstreams/{id}/ <8MB', function($) { $.autodestroy(); Flow.socket($.params.id, $, null, function(client, msg) { return client.user.sa ? true : 'Only for admins'; }); }); }; ``` ### Flow.notify($, id) Type: `method` Passes an HTTP request to the notify delegate of an instance. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `$` | `Controller` | yes | | The controller of the route | | `id` | `String` | yes | | `flowid-instanceid` | `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. Example: Routes ```js ROUTE('GET /notify/{id}/', $ => Flow.notify($, $.params.id)); ROUTE('POST /notify/{id}/ <1MB', $ => Flow.notify($, $.params.id)); ``` Example: In a component ```js instance.notify = function(data) { instance.send('output', data.body); }; ``` ### Flow.test(name, source, [config], init) Type: `method` Loads one component in a test flow. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `name` | `String` | yes | | Component id | | `source` | `String` | yes | | Source of the component | | `config` | `Object` | no | `{}` | Configuration of the instance | | `init` | `Function` | yes | | `function(test)` | Creates 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: | Member | Use | | --- | --- | | `test.send(input, data)` | Sends data to an input of the component (alias `input`) | | `test.message = function($, data)` | Receives what the component sends to its outputs | | `test.status = function(status)` | Receives the status of the component | | `test.debug = function(...)` | Receives `instance.debug()` calls | | `test.configure = function(config)` | Called after a reconfiguration | | `test.trigger(data)` | Runs the `trigger` delegate | | `test.reconfigure(config)` | Changes the configuration | | `test.variables(obj)` | Sets the variables | | `test.assert(ok, text)`, `test.ok(text)`, `test.fail(text)` | Print the result; `fail` throws | An error in the flow ends the process. Example: Test ```js var source = await F.readfile(PATH.root('components/uppercase.html'), 'utf8'); Flow.test('uppercase', source, { field: 'name' }, function(test) { test.message = function($, data) { test.assert(data.name === 'PETER'); }; test.send('input', { name: 'Peter' }); }); ``` ### Flow.instances Type: `property` The running FlowStreams by id. Returns: `Object` An object: FlowStream id → `flowstream` object. `Flow.db` holds the last schema of each FlowStream (updated on every save). Example: Get one ```js var flowstream = Flow.instances.orders; ``` ### Flow.on('load', function(flowstream, schema) {}) Type: `event` A FlowStream is loaded. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `flowstream` | `Object` | yes | | The running FlowStream | | `schema` | `Object` | yes | | The schema | Emitted after `Flow.load()` has loaded the components and the design. ### Flow.on('save', function(schema) {}) Type: `event` The schema of a FlowStream has changed. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `schema` | `Object` | yes | | The whole schema | Emitted 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. Example: Save to a file ```js Flow.on('save', function(schema) { F.Fs.writeFile(PATH.root('flowstreams/' + schema.id + '.flow'), JSON.stringify(schema, null, '\t'), NOOP); }); ``` ### Flow.on('remove', function(schema) {}) Type: `event` A FlowStream was removed. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `schema` | `Object` | yes | | The schema | Emitted by `Flow.remove()` with the last schema of the removed FlowStream. ### Flow.on('stats', function(id, stats) {}) Type: `event` Counters of a FlowStream that runs in a worker. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `id` | `String` | yes | | FlowStream id | | `stats` | `Object` | yes | | Counters | Emitted every 15 seconds for each FlowStream in a worker thread or child process. `stats` has `paused`, `messages`, `pending`, `memory`, `minutes`, `errors`, `mm` and `pid`. ### ON('flowstream', function(flowstream) {}) Type: `event` · Since: `0.0.16` A FlowStream has started. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `flowstream` | `Object` | yes | | The running FlowStream | Global framework event emitted when a FlowStream is created, also after the automatic restart of a worker. Example: Log ```js ON('flowstream', function(flowstream) { console.log('FlowStream', flowstream.id); }); ``` ### ON('flowstream_error', function(meta) {}) Type: `event` An error occurred in a FlowStream. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `meta` | `Object` | yes | | Error details | Errors are printed to the console and emitted as this global event. `meta` has `id` and `name` (of the FlowStream), `error`, `source`, `instanceid` and `componentid`. Example: Audit errors ```js ON('flowstream_error', function(meta) { console.log(meta.name, meta.componentid, meta.error); }); ``` ### { id, name, components, design, variables, ... } Type: `type` The object that describes a FlowStream. `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. Example: Two connected instances ```json { "id": "demo", "name": "Demo", "components": { "uppercase": "<script total>...</script>", "print": "<script total>...</script>" }, "design": { "a1": { "component": "uppercase", "config": { "field": "name" }, "connections": { "output": [{ "id": "b1", "index": "input" }] } }, "b1": { "component": "print", "config": {} } }, "variables": {} } ``` ### schema.proxytimeout Type: `config` · Since: `0.0.18` Timeout of the proxy of a worker with proxypath. Returns: `Number` Milliseconds 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()`). Example: Reload with a timeout ```js Flow.reload({ id: 'api', worker: 'worker', proxypath: '/api/', proxytimeout: 10000, components: components, design: design }); ``` ### flowstream.stats Type: `property` Counters of the FlowStream. Returns: `Object` `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. ### flowstream.trigger(id, [data]) Type: `method` Runs the trigger delegate of instances. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `id` | `String` | yes | | Instance id, `@componentid` or `#name` | | `data` | `Object` | no | | Passed to the delegate | Returns: `Object` The flowstream Calls `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. Example: Start all timers ```js Flow.instances.orders.trigger('@timer'); ``` ### flowstream.send(id, data, [callback]) Type: `method` Sends data into an instance and waits for the result. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `id` | `String` | yes | | Target, optionally with `/input` | | `data` | `Object` | yes | | Payload | | `callback` | `Function` | no | | `function(err, response)` | Creates 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 } }`. Example: Call a flow from an API ```js NEWACTION('Orders/process', { action: function($, model) { Flow.instances.orders.send('@order/input', model, function(err, response) { if (err) $.invalid(err); else $.callback(response.data); }); } }); ``` ### flowstream.exec(opt, [callback]) Type: `method` Sends a message to all matching instances. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `opt` | `Object` | yes | | Options | | `callback` | `Function` | no | | `function(err, response)` | Like `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. Example: Exec with a timeout ```js Flow.instances.orders.exec({ id: '#Validate', data: model, timeout: 5000, uid: model.id }, function(err, response) { console.log(response.uid, response.data); }); ``` ### flowstream.pause([is]) Type: `method` Pauses or resumes the FlowStream. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `is` | `Boolean` | no | | `true` pauses, `false` resumes | Returns: `Object` The flowstream A paused flow does not deliver messages. Without the argument the state is toggled. The `pause` delegate of each instance is called. ### flowstream.variables(obj) Type: `method` Replaces the variables of the FlowStream. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `obj` | `Object` | yes | | New variables | Returns: `Object` The flowstream Calls 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. Example: Rotate a token ```js Flow.instances.orders.variables({ token: newtoken }); ``` ### flowstream.reconfigure(id, config) Type: `method` Changes the configuration of an instance. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `id` | `String` | yes | | Instance id | | `config` | `Object` | yes | | Values to merge | Returns: `Object` The flowstream The values are merged into `instance.config`, the `configure` delegate is called, the editor is updated and the flow is saved. ### flowstream.export(callback) Type: `method` Reads the current schema. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `callback` | `Function` | yes | | `function(err, schema)` | The callback gets the whole schema, the same object as the `save` event. Example: Backup ```js Flow.instances.orders.export(function(err, schema) { F.Fs.writeFile(PATH.root('backup.flow'), JSON.stringify(schema), NOOP); }); ``` ### flowstream.restart() Type: `method` Restarts a FlowStream that runs in a worker. Closes the editor connections and ends the worker; it starts again automatically with the current schema. ### flowstream.remove() Type: `method` Removes the FlowStream. The same as `Flow.remove(flowstream.id)`. ### flowstream.edit([url]) Type: `method` · Since: `0.0.16` Connects the FlowStream to a remote editing proxy. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `url` | `String` | no | `'wss://flow.totaljs.com/{0}/'` | Proxy WebSocket URL | Returns: `WebSocketClient` The client Opens 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. Example: Remote editing ```js Flow.instances.orders.edit(); ``` ### exports.* in <script total> Type: `type` The definition of a FlowStream component. The server part of the component sets properties of `exports`: | Property | Meaning | | --- | --- | | `name`, `icon`, `color`, `group`, `version`, `author` | Shown in the editor | | `type` | For example `input`, `output` or `config`; these appear in `io()` listings | | `inputs`, `outputs` | Arrays of `{ id, name }` | | `config` | Default configuration of new instances | | `npm` | NPM packages installed before registering | | `permissions`, `meta` | Custom data passed to the editor | | `make` | `function(instance, config)` for each instance | | `install`, `uninstall` | `function(component)` when the component is registered and removed | | `call` | `function(data, callback)` called by the editor with `@componentid` | The other parts of the file: `<settings>` (the configuration form), `<body>`, `<style>`, `<script>` (editor code), `<readme>`, `<template>` and `<schema>`. Example: Minimal component ```html <script total> exports.name = 'Print'; exports.inputs = [{ id: 'input', name: 'Input' }]; exports.make = function(instance) { instance.message = function($) { console.log($.data); $.end(); }; }; </script> ``` ### exports.make = function(instance, config) {} Type: `method` Creates an instance of the component. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `instance` | `Object` | yes | | The instance | | `config` | `Object` | yes | | Its configuration | Runs 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. Example: Interval ```js exports.make = function(instance, config) { var timer; instance.configure = function() { clearInterval(timer); timer = setInterval(() => instance.send('output', { ts: NOW }), (instance.config.interval || 10) * 1000); }; instance.close = () => clearInterval(timer); instance.configure(); }; ``` ### exports.inputs / exports.outputs Type: `property` The inputs and outputs of a component. Returns: `Array` Arrays 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`. Example: Two outputs ```js exports.inputs = [{ id: 'input', name: 'Input' }]; exports.outputs = [{ id: 'ok', name: 'OK' }, { id: 'error', name: 'Error' }]; ``` ### instance Type: `type` One placed instance of a component. The 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`. Delegates 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)`. ### instance.message = function($) {} Type: `delegate` Receives a message on an input. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `$` | `Message` | yes | | The message | `$.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()`. Example: Route by input ```js instance.message = function($) { if ($.input === 'reset') { count = 0; $.end(); } else { count++; $.send('output', { count: count }); } }; ``` ### instance.configure = function(config) {} Type: `delegate` The configuration has changed. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `config` | `Object` | yes | | The configuration | Called after a change in the editor or a call of `reconfigure()`. `instance.config` already contains the new values. ### instance.close = function() {} Type: `delegate` The instance is being removed. Called when the instance is removed from the design, the component is unregistered or the flow ends. Clear timers and close connections here. ### instance.send(output, [data]) Type: `method` Starts a new message from an output or from all outputs. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `output` | `String` | yes | | Output id, or `null` for all outputs | | `data` | `Object` | no | | Payload | Returns: `Number` Count of sent messages Sends `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. Example: From a timer ```js setInterval(() => instance.send('output', { ts: NOW }), 1000); ``` Example: All outputs ```js instance.send(null, { ts: NOW }); ``` ### instance.newmessage([data]) Type: `method` Creates a message without sending it. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `data` | `Object` | no | | Payload | Returns: `Message` A new message The message belongs to the instance; set `$.repo`, listen to `end` and then call `$.send(output)`. Example: Wait for the end ```js var msg = instance.newmessage({ id: 1 }); msg.on('end', function($) { console.log('Done', $.data); }); msg.send('output'); ``` ### instance.status([data], [delay]) Type: `method` Sets the status shown under the instance. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `data` | `Object` | no | | Any JSON value | | `delay` | `Number` | no | | Throttle in ms | The 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. Example: Counter ```js instance.status({ count: count }, 1000); ``` ### instance.dashboard([data]) Type: `method` Sends data to the dashboard of the editor. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `data` | `Object` | no | | Any JSON value | The data are kept and sent to the editor; without arguments the last data are sent again. ### instance.throw(error) Type: `method` Reports an error of the instance. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `error` | `Error|String` | yes | | The error | The 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`. Example: In a callback ```js RESTBuilder.GET(config.url).callback(function(err, response) { if (err) { instance.throw(err); $.end(); } else $.send('output', response); }); ``` ### instance.debug(a, [b], [c], [d]) Type: `method` Emits a debug event. Emits `debug` on `instance.main` with the instance and the arguments. `Flow.test()` passes it to `test.debug`. ### instance.save([redraw]) Type: `method` Saves the instance after a change from code. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `redraw` | `Boolean` | no | `true` | Redraw the instance in the editor | Use 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. Example: Remember a value ```js instance.config.lastid = $.data.id; instance.save(); ``` Example: Without redraw ```js instance.config.counter++; instance.save(false); ``` ### instance.reconfigure(config) Type: `method` Changes the configuration of this instance. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `config` | `Object` | yes | | Values to merge | The same as `flowstream.reconfigure(instance.id, config)` called from the component. ### instance.replace(text, [data], [encoding]) Type: `method` Replaces {variables} in a text. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `text` | `String|Object` | yes | | Text with placeholders | | `data` | `Object` | no | | Extra values | | `encoding` | `String|Function` | no | | Encoding of the values | Returns: `String` The text A `{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. Example: URL ```js var url = instance.replace('https://api.example.com/{token}/orders/?id={id}', { id: 5 }, 'url'); ``` ### instance.cache Type: `property` An in-memory object for runtime data of the instance. Returns: `Object` A 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. Example: Last value ```js instance.message = function($) { instance.cache.last = $.data; $.send('output'); }; ``` ### instance.repo Type: `property` · Since: `0.0.17` Persistent data of the instance stored in the design. Returns: `Object` An 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. Example: Keep a cursor ```js instance.repo.lastid = $.data.id; instance.save(); ``` ### instance.activity(key, name, [progress]) Type: `method` · Since: `0.0.19` Reports a running activity of the instance. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `key` | `String` | yes | | Activity id | | `name` | `String` | yes | | Description | | `progress` | `Number` | no | | Percent | Creates 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. Example: Progress ```js instance.activity('sync', 'Synchronizing', 40); // ... instance.activity('sync', 'Synchronizing', 100); ``` ### instance.main Type: `property` The flow engine of the instance. Returns: `FlowStream` Useful 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. Example: Send to another instance ```js instance.main.trigger('b1__input', { id: 1 }); ``` ### instance.main.on('reset', function() {}) Type: `event` The errors of the flow were reset. Emitted 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`. Example: Reset a counter ```js exports.make = function(instance) { instance.cache.count = 0; var onreset = function() { instance.cache.count = 0; instance.status({ count: 0 }); }; instance.main.on('reset', onreset); instance.close = function() { instance.main.off('reset', onreset); }; }; ``` ### $ Type: `class` A message travelling through the flow. Properties: `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`. Methods: `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`. ### $.send(output, [data], [clone], [check]) Type: `method` Sends the message to an output or to all outputs. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `output` | `String` | yes | | Output id, or `null` for all outputs | | `data` | `Object` | no | | New payload | | `clone` | `Boolean` | no | `the `cloning` of the flow` | Clone the data | | `check` | `Function` | no | | `function(from, to, output, input)` returns a Boolean | Returns: `Number` Count of targets Sends 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. Example: Pass on ```js instance.message = function($) { $.data.checked = true; $.send('output'); }; ``` Example: Skip some targets ```js $.send('output', null, null, function(from, to, output, input) { return to.component !== 'debug'; }); ``` Example: All outputs ```js instance.message = function($) { $.send(null); }; ``` ### $.end() Type: `method` Ends the message. Call 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()`). Example: Stop here ```js instance.message = function($) { save($.data); $.end(); }; ``` ### $.timeout([callback], time) Type: `method` Sets a timeout for the next instances. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `callback` | `Function` | no | | `function($)` | | `time` | `Number` | yes | | Milliseconds | Returns: `Message` Each 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. Example: Timeout ```js $.timeout(function($) { instance.throw('Timeout'); }, 5000); $.send('output'); ``` ### flow5 [path or URL ...] [port] Type: `command` Runs FlowStream schemas from the command line. Loads 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. Example: Two flows on port 8001 ```bash flow5 orders.json import.json 8001 ``` --- title: Message Service (TMS) project: Total.js V5 version: 0.0.20 section: reference language: en license: MIT url: https://totaljs.es/docs/total-js-v5/0-0-20/reference/message-service-and-apis/ updated: 2026-11-19T16:17:07.153Z --- # Message Service (TMS) > TMS functions, the TMS client and their configuration keys. The 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. Named APIs and the Total.js API service have their own page: [APIs](../apis/). ## API ### $tms : true Type: `config` Opens the TMS WebSocket endpoint. Returns: `Boolean` Default `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. Example: Enable TMS ```js // /config $tms : true secret_tms : a-long-random-token ``` ### $tmsurl : /$tms/ Type: `config` The path of the TMS endpoint. Returns: `String` Default `/$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. ### $tmsmaxsize : 256 Type: `config` The maximum size of one TMS message in kB. Returns: `Number` Default `256`. The value is used when the TMS route is registered. ### secret_tms : token Type: `config` The token TMS clients must send. Returns: `String` Default 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. ### $tmsclearblocked : 60 Type: `config` How often, in minutes, the list of blocked TMS clients is cleared. Returns: `Number` Default `60`. IP addresses blocked for wrong tokens can connect again after the list is cleared. ### NEWPUBLISH(name, schema) Type: `method` Declares an event that the app publishes to TMS clients. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `name` | `String` | yes | | The name of the event. | | `schema` | `String|Object` | yes | | An inline schema (`'id:UID, name:String'`), `'@name'` of a registered JSON schema, or `null` to remove the event. | The 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. Example: Declare and publish ```js NEWPUBLISH('orders_created', 'id:UID, email:Email, total:Number'); PUBLISH('orders_created', { id: UID(), email: 'a@b.com', total: 100 }); ``` ### PUBLISH(name, data) Type: `method` Sends data of a declared event to subscribed TMS clients. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `name` | `String` | yes | | The name of an event declared with `NEWPUBLISH()`. | | `data` | `Object` | yes | | The data to send. | The 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`. Example: Publish after a change ```js NEWACTION('orders_create', { input: '*email:Email, *total:Number', action: function($, model) { model.id = UID(); PUBLISH('orders_created', model); $.success(model.id); } }); ``` ### NEWSUBSCRIBE(name, schema, [callback]) Type: `method` Declares a message that TMS clients may send to the app. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `name` | `String` | yes | | The name of the message. | | `schema` | `String|Object` | yes | | An inline schema, `'@name'` of a registered JSON schema, or `null`. | | `callback` | `Function` | no | | `function(msg, client)`, the same as a `SUBSCRIBE()` handler. | A 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. Example: Accept a message ```js NEWSUBSCRIBE('users_updated', 'id:UID, *name:String', function(msg, client) { console.log(msg.response.name); }); ``` ### SUBSCRIBE(name, callback) Type: `method` Adds a handler for a message sent by TMS clients. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `name` | `String` | yes | | The name of the message. | | `callback` | `Function` | yes | | `function(msg, client)`. | The 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. Example: Handle a message ```js SUBSCRIBE('users_updated', function(msg, client) { var user = msg.response; console.log('User', user.id, 'is now', user.name); }); ``` ### UNSUBSCRIBE(name, [callback]) Type: `method` Removes handlers added with SUBSCRIBE(). | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `name` | `String` | yes | | The name of the message. | | `callback` | `Function` | no | | The handler to remove. | Returns: `Boolean` `true` when something was removed. With `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. Example: Remove one handler ```js function onuser(msg) { console.log(msg.response); } SUBSCRIBE('users_updated', onuser); // later UNSUBSCRIBE('users_updated', onuser); ``` ### NEWCALL(name, schema, callback) Type: `method` Declares a procedure that TMS clients can call. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `name` | `String` | yes | | The name of the call. | | `schema` | `String|Object` | yes | | An inline schema, `'@name'` of a registered JSON schema, or `null` to remove the call. | | `callback` | `Function` | yes | | `function(data, next, client)`. | The 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. Example: Answer a call ```js NEWCALL('products_detail', 'id:UID', function(data, next, client) { if (data.id === '404') next('Product not found'); else next(null, { id: data.id, name: 'Keyboard' }); }); ``` ### TMSCLIENT(url, [token], [callback]) Type: `method` Connects the app to a TMS endpoint. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `url` | `String` | yes | | The address of the endpoint, e.g. `https://app.example.com/$tms/`. | | `token` | `String` | no | | The `secret_tms` of the server. | | `callback` | `Function` | no | | `function(err, client, meta)`. | Returns: `WebSocketClient` The client, with the TMS methods below. Connects 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. Example: Connect ```js TMSCLIENT('https://orders.example.com/$tms/', CONF.orders_token, function(err, client, meta) { client.subscribe('orders_created', function(order) { console.log(order); }); }); ``` ### client.subscribe(name, callback) Type: `method` Receives events that the server publishes with PUBLISH(). | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `name` | `String` | yes | | The name of the event. | | `callback` | `Function` | yes | | `function(data)`. | The 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. Example: Listen to an event ```js var client = TMSCLIENT('https://orders.example.com/$tms/', CONF.orders_token); client.subscribe('orders_created', function(order) { console.log(order.id, order.total); }); ``` ### client.publish(name, data) Type: `method` Sends a message to a NEWSUBSCRIBE() of the server. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `name` | `String` | yes | | The name declared with `NEWSUBSCRIBE()` on the server. | | `data` | `Object` | yes | | The data. | The message is sent only while the client is connected; otherwise it is dropped. The server validates it with its schema. Example: Send a message ```js client.publish('users_updated', { id: user.id, name: user.name }); ``` ### client.call(name, data, [callback], [timeout]) Type: `method` Calls a NEWCALL() procedure of the server. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `name` | `String` | yes | | The name declared with `NEWCALL()`. | | `data` | `Object` | yes | | The data of the call. | | `callback` | `Function` | no | | `function(err, response)`. | | `timeout` | `Number` | no | `10000` | The timeout in milliseconds. | Returns: `Promise` Only when the callback is omitted. Without 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. Example: Call with a promise ```js var product = await client.call('products_detail', { id: '123' }); ``` ### client.destroy() Type: `method` Closes the TMS client for good. Stops the reconnecting and fails every pending `client.call()` with `TMS has been destroyed`. Example: Close ```js client.destroy(); ``` ### client.ready Type: `property` `true` while the TMS client is connected and has the meta of the server. Returns: `Boolean` It becomes `true` when a `meta` message arrives and `false` when the connection closes. Example: Check ```js if (client.ready) client.publish('users_updated', user); ``` ### client.meta Type: `property` The last meta message received from the server. Returns: `Object` An object with `name` (the `CONF.name` of the server), `publish`, `subscribe` and `call` (arrays of `{ id, schema }`) and `subscribers` (the names with `SUBSCRIBE()` handlers). Example: List the calls ```js client.meta.call.forEach(function(item) { console.log(item.id); }); ``` ### client.on('ready', callback) Type: `event` Fires every time the TMS client is connected and ready. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `callback` | `Function` | yes | | `function()`. | Fires after each `meta` message, so also after a reconnection. Example: Ready ```js client.on('ready', function() { console.log('TMS ready'); }); ``` ### client.on('meta', callback) Type: `event` Fires when the server sends its meta message. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `callback` | `Function` | yes | | `function(meta)`. | Fires after each connection and whenever the server changes its publishers, subscribers or calls. Example: Meta ```js client.on('meta', function(meta) { console.log(meta.name, meta.publish.length); }); ``` --- title: APIs project: Total.js V5 version: 0.0.20 section: reference language: en license: MIT url: https://totaljs.es/docs/total-js-v5/0-0-20/reference/apis/ updated: 2026-11-18T16:57:19.575Z --- # APIs > NEWAPI(), API() and its methods, TotalAPI() and their configuration keys. The 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. ## API ### NEWAPI(name, [config], callback) Type: `method` Registers the code that calls one API service. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `name` | `String` | yes | | The name, or names separated by commas. | | `config` | `Object` | no | | Default settings copied into `opt.config`. | | `callback` | `Function` | yes | | `function(opt, next)`; `next(err, response)` ends the call. | Registers 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. Example: Register a service ```js NEWAPI('Weather', { region: 'eu' }, function(opt, next) { REQUEST({ url: 'https://' + opt.config.region + '.weather.example/' + opt.schema + '/', method: 'POST', type: 'json', body: JSON.stringify(opt.data), callback: function(err, response) { next(err, response && response.body.parseJSON()); }}); }); ``` ### function(opt, next) Type: `type` The options a NEWAPI() handler receives. The 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`. Example: Retry ```js NEWAPI('Weather', function(opt, next) { callservice(opt.schema, opt.data, function(err, response) { if (err && opt.retries < 3) opt.retry(); else next(err, response); }); }); ``` ### API(name, schema, data, [$]) Type: `method` Calls a service registered with NEWAPI(). | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `name` | `String` | yes | | The name of the service. | | `schema` | `String` | yes | | The operation, passed as `opt.schema`. | | `data` | `Object` | yes | | The payload, passed as `opt.data`. | | `$` | `Object` | no | | The `$` of an action or a controller. | Returns: `APICall` The call with the methods below. Creates 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. Example: Inside an action ```js NEWACTION('weather_read', { input: '*city:String', action: function($, model) { API('Weather', 'current', model).callback($); } }); ``` ### API().callback(fn) Type: `method` Sets the callback of the call. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `fn` | `Function|Object` | yes | | A callback, or `$`. | Returns: `APICall` `fn` is `function(err, response)`, or the `$` of an action, whose `$.callback()` receives the result. `.pipe()` is an alias. Example: Callback ```js API('Weather', 'current', { city: 'Oslo' }).callback(function(err, response) { console.log(err, response); }); ``` ### API().promise([$]) Type: `method` Returns a promise of the call. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `$` | `Object` | no | | The `$` of an action. | Returns: `Promise` The promise resolves with the response. On an error it rejects with an `Error`; when `$` is given, the error goes to `$.invalid()` instead. Example: Await ```js var weather = await API('Weather', 'current', { city: 'Oslo' }).promise($); ``` ### API().data(fn) Type: `method` Runs a function with the response of a successful call. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `fn` | `Function` | yes | | `function(response)`. | Returns: `APICall` `fn(response)` runs before the callback. Example: Data ```js API('Weather', 'current', { city: 'Oslo' }).data(function(response) { MAIN.weather = response; }); ``` ### API().fail(fn) Type: `method` Runs a function with the error of a failed call. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `fn` | `Function` | yes | | `function(err)`. | Returns: `APICall` `fn(err)` runs before the callback. Example: Fail ```js API('Weather', 'current', { city: 'Oslo' }).fail(function(err) { console.error(err); }); ``` ### API().error(message, [reverse]) Type: `method` Turns an empty response into an error. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `message` | `String` | yes | | The error. | | `reverse` | `Boolean` | no | `false` | Fail on a non-empty response. | Returns: `APICall` When 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. Example: Not found ```js API('Weather', 'current', model).error('City not found').callback($); ``` ### API().output(type) Type: `method` Sets the output format of the call. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `type` | `String` | yes | | The format, e.g. `json`, `base64`, `stream`. | Returns: `APICall` The value is stored in `opt.output` for the handler. See `TotalAPI()` for the formats of the `TAPI` service. Example: Base64 ```js API('Weather', 'map', { city: 'Oslo' }).output('base64').callback(console.log); ``` ### API().file(filename, path, [name]) Type: `method` Adds a file to the call. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `filename` | `String` | yes | | The name of the file. | | `path` | `String` | yes | | The path of the file on the disk. | | `name` | `String` | no | `file + index` | The field name. | Returns: `APICall` The file is added to `opt.files` as `{ name, filename, path }`. The default name is `file0`, `file1`, ... Example: Upload ```js API('Storage', 'upload', { folder: 'invoices' }).file('invoice.png', PATH.public('invoice.png')).callback(console.log); ``` ### API().controller($) Type: `method` Sets the controller of the call. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `$` | `Object` | yes | | The `$` of an action or a controller. | Returns: `APICall` Stores `$.controller` (or `$` itself when it has none) in `opt.controller`. Example: Controller ```js API('Weather', 'current', model).controller($).callback($); ``` ### API().audit($, message, [type]) Type: `method` Writes an audit log after a successful call. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `$` | `Object` | yes | | The `$` of an action. | | `message` | `String` | yes | | The message. | | `type` | `String` | no | | The type of the log. | Returns: `APICall` Calls `$.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 `$`. Example: Audit ```js API('Billing', 'invoice_create', model).audit($, 'Invoice for {data.email}').callback($); ``` ### API().debug() Type: `method` Prints the result of the call to the console. Returns: `APICall` Prints the name, the operation, the error and the response. Example: Debug ```js API('Weather', 'current', { city: 'Oslo' }).debug().callback(NOOP); ``` ### API().configure(obj) Type: `method` · Since: `0.0.16` Sets configuration keys of the call. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `obj` | `Object` | yes | | The keys to set. | Returns: `APICall` Copies the keys of `obj` into `opt.config`. They override the config given to `NEWAPI()`. The `TAPI` service reads `token` from it. Example: Another token ```js API('TAPI', 'check', {}).configure({ token: CONF.customer_token }).callback(console.log); ``` ### TotalAPI(schema, data, [callback]) Type: `method` Calls an operation of Total.js API. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `schema` | `String` | yes | | The operation, e.g. `check`. | | `data` | `Object` | yes | | The payload. | | `callback` | `Function` | no | | `function(err, response)`. | Returns: `APICall` Configure it like any `API()` call. The 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. Example: Check the token ```js TotalAPI('check', {}, function(err, response) { console.log(err, response); }); ``` Example: Save into FileStorage ```js // operation: a Total API operation that returns a file API('TAPI', operation, data).output('#files').callback(console.log); ``` ### totalapi : token Type: `config` The token of Total.js API. Returns: `String` A 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`. Example: Config ```js // /config totalapi : your-totalapi-token ``` ### $tapi : true Type: `config` Allows calls of the TAPI service. Returns: `Boolean` Default `true`. When `false`, every `TAPI` operation except `check` fails with `totalapi_inactive`. ### $tapiurl : eu Type: `config` The region of Total.js API. Returns: `String` Default `eu`. Requests go to `https://<$tapiurl>.api.totaljs.com/`. --- title: Workers, threads and cluster project: Total.js V5 version: 0.0.20 section: reference language: en license: MIT url: https://totaljs.es/docs/total-js-v5/0-0-20/reference/workers-and-threads/ updated: 2026-11-18T16:57:29.576Z --- # Workers, threads and cluster > NEWTHREAD(), NEWFORK(), NEWTHREADPOOL(), F.worker, the cluster options, SHELL(), F.python(), F.pipinstall() and PYPELINE(). Methods, 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/). ## API ### NEWTHREAD(name, [data]) Type: `method` Starts a worker thread from the workers/ folder. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `name` | `String` | yes | | The file name in `workers/` without `.js`, or `~` and an absolute path | | `data` | `Object` | no | | Data copied into the thread as `F.worker.data` | Returns: `Worker` The Node.js worker thread Runs `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`. The 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()`. Example: Start a thread ```js var thread = NEWTHREAD('calc', { user: 'Peter' }); thread.on('message', function(msg) { console.log(msg.sum); thread.kill(); }); thread.postMessage({ a: 1, b: 2 }); ``` ### NEWTHREAD() Type: `method` Inside a worker script: returns the worker object F.worker. Returns: `Object` F.worker Called 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. Example: workers/calc.js ```js require('total5'); var worker = NEWTHREAD(); worker.message = function(msg) { worker.send({ sum: msg.a + msg.b }); }; ``` ### F.worker Type: `property` The worker object of a script that runs as a worker. Returns: `Object` Created 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`. Example: Check the data ```js var worker = NEWTHREAD(); console.log(F.worker === worker); // true console.log(worker.data); ``` ### F.worker.data Type: `property` The data passed to NEWTHREAD(name, data). Returns: `Object` A 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. Example: Read the data ```js var worker = NEWTHREAD(); var user = worker.data.user; ``` ### F.worker.is Type: `property` true when the script runs as a worker. Returns: `Boolean` `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`. Example: Run as a worker or alone ```js var worker = NEWTHREAD(); if (!worker.is) console.log('Started directly with node, not as a worker'); ``` ### F.worker.isfork Type: `property` true in a forked process, false in a worker thread. Returns: `Boolean` `true` when the worker is a process from `NEWFORK()` (messages go through `process.send()`), `false` in a worker thread. Example: Thread or process ```js var worker = NEWTHREAD(); console.log(worker.isfork ? 'process ' + process.pid : 'thread'); ``` ### F.worker.message = function(msg) {} Type: `delegate` Receives the messages from the parent. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `msg` | `Object` | yes | | The message from the parent | Assign a function. It is called with every message the parent sends with `postMessage()`. The default does nothing. Example: Answer messages ```js var worker = NEWTHREAD(); worker.message = function(msg) { if (msg.type === 'ping') worker.send({ type: 'pong' }); }; ``` ### F.worker.send(msg) Type: `method` Sends a message to the parent. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `msg` | `Object` | yes | | The message; it is copied, functions are not allowed | Sends 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')`. Example: Send a result ```js worker.send({ id: msg.id, result: result }); ``` ### F.worker.exit([code]) Type: `method` Ends the worker. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `code` | `Number` | no | `0` | The exit code | Calls `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. Example: End after the job ```js worker.message = function(msg) { work(msg); worker.exit(); }; ``` ### F.worker.setTimeout(timeout) Type: `method` Ends the worker with code 1 after a timeout. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `timeout` | `Number` | yes | | Milliseconds | Starts 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. Example: Watchdog ```js worker.message = function(msg) { worker.setTimeout(10000); job(msg, function(response) { worker.send(response); }); }; ``` ### thread.kill() Type: `method` Stops a thread started with NEWTHREAD(). Calls `terminate()` of the Node.js `Worker`. `thread.exit()` is the same method. Example: Stop a thread ```js var thread = NEWTHREAD('calc'); setTimeout(() => thread.kill(), 5000); ``` ### NEWFORK(name) Type: `method` · Since: `0.0.16` Runs a script from the workers/ folder in a new Node.js process. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `name` | `String` | yes | | The file name in `workers/` without `.js`, or `~` and an absolute path | Returns: `ChildProcess` The forked process Starts `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. The 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. Example: Main application ```js var fork = NEWFORK('report'); fork.on('message', function(msg) { if (typeof(msg) === 'string') return; console.log(msg); fork.terminate(); }); fork.postMessage({ id: 100 }); ``` Example: workers/report.js ```js require('total5'); var worker = NEWFORK(); worker.message = function(msg) { worker.send({ id: msg.id, done: true }); }; ``` ### fork.terminate() Type: `method` · Since: `0.0.16` Kills a process started with NEWFORK(). Sends `SIGKILL` to the process. The process ends at once, without running its exit handlers. Example: Kill a fork ```js var fork = NEWFORK('report'); setTimeout(() => fork.terminate(), 60000); ``` ### fork.postMessage(msg) Type: `method` · Since: `0.0.16` Sends a message to a process started with NEWFORK(). | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `msg` | `Object` | yes | | The message; it is serialized as JSON | The 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`. Example: Send a job ```js fork.postMessage({ id: 100, type: 'pdf' }); ``` ### NEWTHREADPOOL(name, count, [isfork]) Type: `method` Starts a pool of worker threads or forks and lends them to jobs. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `name` | `String` | yes | | The file name in `workers/` without `.js` | | `count` | `Number` | yes | | The number of workers | | `isfork` | `Boolean` | no | `false` | Start the workers with `NEWFORK()` instead of threads | Returns: `Object` The pool Starts `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]`. Example: Pool of four threads ```js var pool = NEWTHREADPOOL('calc', 4); pool.exec(function(worker, release) { worker.on('message', function(msg) { console.log(msg.sum); release(); }); worker.postMessage({ a: 5, b: 5 }); }); ``` Example: Pool of forks ```js var pool = NEWTHREADPOOL('report', 2, true); ``` ### pool.exec([fn]) Type: `method` Runs a job on the next free worker of the pool. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `fn` | `Function` | no | | `function(worker, release)` | Returns: `Promise` Only without `fn`: resolves with the worker Adds 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()`. Before a worker starts a job, the pool removes all its `message` listeners, so each job attaches its own. Example: With a callback ```js pool.exec(function(worker, release) { worker.on('message', function(msg) { release(); }); worker.postMessage({ a: 1, b: 2 }); }); ``` Example: With a promise ```js var worker = await pool.exec(); worker.on('message', function(msg) { worker.release(); }); worker.postMessage({ a: 1, b: 2 }); ``` ### worker.release() Type: `method` Returns a worker of a pool back to the pool. Every 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)`. Example: Release ```js var worker = await pool.exec(); worker.on('message', () => worker.release()); worker.postMessage({}); ``` ### pool.workers Type: `property` The workers of the pool. Returns: `Array` An array of the `Worker` objects that the pool started. Example: Send to all ```js pool.workers.forEach(w => w.postMessage({ type: 'reload' })); ``` ### pool.pending Type: `property` The jobs that wait for a free worker. Returns: `Array` An array of the functions passed to `pool.exec()` that have not started yet. Its length tells how busy the pool is. Example: Queue length ```js console.log('Waiting jobs:', pool.pending.length); ``` ### pool.count Type: `property` The number of workers of the pool. Returns: `Number` The `count` given to `NEWTHREADPOOL()`. The pool keeps this number of workers: a worker that exits is replaced. Example: Size ```js var pool = NEWTHREADPOOL('calc', 4); console.log(pool.count); // 4 ``` ### F.workers Type: `property` The thread pools of the application by name. Returns: `Object` `NEWTHREADPOOL(name, count)` stores the pool here under its name. Example: Get a pool ```js var pool = F.workers.calc; ``` ### options.cluster = 4 Type: `config` Start option: runs the application in a cluster of processes. A 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. With `'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. Example: Start script ```js require('total5'); const options = {}; options.port = 8000; options.release = true; options.cluster = 4; Total.run(options); ``` ### options.limit = 10 Type: `config` Start option: the maximum number of processes of an 'auto' cluster. Used only with `cluster: 'auto'`. Without it the master can add processes without a limit. Example: Auto cluster ```js require('total5'); Total.run({ release: true, port: 8000, cluster: 'auto', limit: 8 }); ``` ### options.tz = 'utc' Type: `config` Start option of a cluster: the time zone of the processes. In cluster mode the framework sets `process.env.TZ` to this value before it starts the processes. The default is `'utc'`. Example: Time zone ```js require('total5'); Total.run({ release: true, cluster: 4, tz: 'Europe/Madrid' }); ``` ### options.logs = 'isolated' Type: `config` Start option of a cluster: always print the cluster header. The 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'`. Example: Header ```js require('total5'); Total.run({ release: true, cluster: 2, logs: 'isolated' }); ``` ### options.callback = function(forks) {} Type: `delegate` Start option of a cluster: called after all processes have started. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `forks` | `Array` | yes | | The cluster workers | Runs in the master once every process of the cluster has started. `forks` is the array of the `cluster.Worker` objects. Example: After start ```js require('total5'); Total.run({ release: true, cluster: 2, callback: function(forks) { console.log('Started', forks.length, 'processes'); } }); ``` ### F.isCluster Type: `property` true in a process of a cluster. Returns: `Boolean` The framework sets it when the master sends the start options to the process. In other cases it is `undefined`. Example: Check ```js if (F.isCluster) process.send({ type: 'clearcache' }); ``` ### F.isWorker Type: `property` true when the process is a worker of the Node.js cluster. Returns: `Boolean` The 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. Example: Check ```js console.log(F.isWorker); ``` ### F.clusterid Type: `property` The identifier of the process in a cluster. Returns: `String` A 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. Example: Per-process file ```js var filename = PATH.tmp('export' + F.clusterid + '.csv'); ``` ### F.id Type: `property` The identifier of the process in a cluster. Returns: `String` The same value as `F.clusterid`: a string with the number of the process, or an empty string outside a cluster. Example: Log ```js console.log('Process', F.id); ``` ### ON('$message', function(msg, handle) {}) Type: `event` Every message the process receives through its IPC channel. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `msg` | `Object` | yes | | The message | | `handle` | `Object` | yes | | The handle sent with the message, if any | Emitted 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. Example: Sync caches ```js ON('$message', function(msg) { if (msg && msg.type === 'clearcache') MAIN.products = null; }); // in any process process.send({ type: 'clearcache' }); ``` ### restart (file) Type: `command` A file that restarts all processes of a cluster. The 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. Example: Restart from the shell ```bash $ touch restart ``` ### SHELL(cmd, [callback], [cwd]) Type: `method` Runs a shell command. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `cmd` | `String` | yes | | The command | | `callback` | `Function` | no | | `function(err, stdout)`; or the working directory as a string | | `cwd` | `String` | no | `the application root` | The working directory | Returns: `Promise` Only without a callback: resolves with the standard output Runs 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. Example: Callback ```js SHELL('git rev-parse HEAD', function(err, stdout) { console.log(stdout.trim()); }); ``` Example: Promise and directory ```js var list = await SHELL('ls -1', PATH.public()); ``` ### $shell : /bin/bash Type: `config` The shell that SHELL() uses. The 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). Example: config ```text $shell : /bin/bash ``` ### F.python(filename, [callback]) Type: `method` Runs a Python script and returns its output. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `filename` | `String` | yes | | The absolute path to the `.py` file. | | `callback` | `Function` | no | | `function(err, stdout, stderr)`. | Returns: `Promise` Only without a callback: resolves with the standard output. Runs `$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). Example: Promise ```js var output = await F.python(PATH.root('scripts/report.py')); ``` Example: Callback ```js F.python(PATH.root('scripts/report.py'), function(err, stdout, stderr) { if (err) console.log(stderr); else console.log(stdout); }); ``` ### PYPELINE(name, [options]) Type: `method` Starts a Python script and exchanges messages with it. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `name` | `String` | yes | | The file name in `pypelines/` without `.py`, `~` and an absolute path, or inline code | | `options` | `Object` | no | | `{ autorestart, type, socket }` | Returns: `Pypeline` An object with events and the methods below Runs `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. The 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. The 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). Example: Start a pipeline ```js var py = PYPELINE('upper'); py.on('data', function(msg) { console.log(msg.text); }); py.send({ text: 'hello' }); ``` Example: Text messages ```js var py = PYPELINE('tokenizer', { type: 'text' }); ``` ### F.pipinstall(name, [callback]) Type: `method` Installs a Python package with pip. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `name` | `String` | yes | | The package, optionally with a version (`requests==2.32.3`). | | `callback` | `Function` | no | | `function(err)`. | Returns: `Promise` Only without a callback. Runs `$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. Example: Install before use ```js await F.pipinstall('requests'); var output = await F.python(PATH.root('scripts/download.py')); ``` ### pypeline.send(data) Type: `method` Sends a message to the Python script. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `data` | `Object|Buffer|String` | yes | | The message | Returns: `Pypeline` The pipeline (only when the script is connected) An 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. Example: Send ```js py.send({ text: 'hello' }); ``` ### pypeline.close() Type: `method` Stops the Python script for good. Returns: `Pypeline` Turns `autorestart` off, closes the socket server and kills the Python process. Example: Stop ```js py.close(); ``` ### pypeline.restart() Type: `method` Kills the Python process and starts it again. Kills the current process and starts the script again. `pypeline.run()` is the same method. Example: Reload ```js py.restart(); ``` ### pypeline.on('data', function(msg) {}) Type: `event` A message from the Python script. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `msg` | `Object|String|Buffer` | yes | | The message | Emitted for every complete message. With `type: 'json'` the message is parsed, with `'text'` it is a string, otherwise a `Buffer`. Example: Read ```js py.on('data', function(msg) { console.log(msg); }); ``` ### pypeline.on('open', function() {}) Type: `event` The Python script connected to the socket. Emitted each time the script connects, after the waiting messages have been sent. Example: Connected ```js py.on('open', function() { console.log('Python is ready'); }); ``` ### pypeline.on('restart', function() {}) Type: `event` The Python script ended and was started again. Emitted with `autorestart: true` after the framework has started the script again. Example: Log restarts ```js py.on('restart', function() { console.log('Python restarted'); }); ``` ### pypeline.name Type: `property` The name of the pipeline. Returns: `String` The `name` passed to `PYPELINE()`, or `Inline Python Code` for inline code. Example: Log ```js console.log(py.name); ``` --- title: MCP server project: Total.js V5 version: 0.0.20 section: reference language: en license: MIT url: https://totaljs.es/docs/total-js-v5/0-0-20/reference/mcp-server/ updated: 2026-11-19T16:17:07.153Z --- # MCP server > 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. The `$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. ## API ### $mcp : Boolean Type: `config` Turns on the MCP server. Returns: `Boolean` `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. Default: `false`. Example: In the config file ```text $mcp : true ``` ### mcp: Boolean Type: `config` Makes an action a tool. Returns: `Boolean` An 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. Example: A tool ```js NEWACTION('Tasks|list', { summary: 'Lists the tasks, 20 per page', mcp: true, query: 'page:Number // The page number', action: function($) { NOSQL('tasks').find().paginate($.query.page || 1, 20).callback($); } }); // the tool Tasks_list ``` ### POST /$mcp/ Type: `type` The endpoint of the MCP server. A 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`. Example: A request ```js await fetch('http://localhost:8000/$mcp/', { method: 'POST', headers: { 'Content-Type': 'application/json', Authorization: 'Bearer 6f1d2c' }, body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'tools/list' }) }); ``` ### GET /$mcp/client.js[?q=words] Type: `type` The tools as a JavaScript client, for code mode. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `q` | `String` | no | | Words that the name or the description of a tool must contain. | Returns: `String` The JavaScript source. Returns 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. `?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. Example: Download and use ```js // curl -H 'Authorization: Bearer TOKEN' 'https://app.example.com/$mcp/client.js?q=tasks' > client.js const api = require('./client.js')('TOKEN'); const task = await api.Tasks_create({ input: { name: 'Call Peter' } }); console.log(task.id); ``` Example: A function of the file ```js /** * Creates a task and returns its ID * @param {Object} args * @param {Object} args.input Payload (request body) passed to this action. * @param {String} args.input.name The name of the task * @param {String} [args.input.due] When the task must be done (ISO date) * @returns {Promise<{ id: ?String }>} */ api.Tasks_create = args => call("Tasks_create", args); ``` ### { method: 'initialize', params: { protocolVersion } } Type: `method` Starts a session of the client. Returns: `Object` The result. Returns `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. Example: Answer ```json { "jsonrpc": "2.0", "id": 1, "result": { "protocolVersion": "2025-06-18", "capabilities": { "tools": {} }, "serverInfo": { "name": "Tasks", "version": "1.0" } } } ``` ### { method: 'ping' } Type: `method` Checks the connection. Returns: `Object` An empty object. Returns an empty result `{}`. ### { method: 'tools/list' } Type: `method` Lists the tools. Returns: `Object` The result. Returns `{ 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`. ### { method: 'tools/call', params: { name, arguments: { input, query, params } } } Type: `method` Runs a tool. Returns: `Object` The result. Runs 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`. Example: Call ```json { "jsonrpc": "2.0", "id": 5, "method": "tools/call", "params": { "name": "Tasks_remove", "arguments": { "params": { "id": "JafvB11cV61f" } } } } ``` Example: Answer ```json { "jsonrpc": "2.0", "id": 5, "result": { "resultType": "complete", "content": [{ "type": "text", "text": "{\"success\":true}" }], "structuredContent": { "success": true } } } ``` ### { method: 'server/discover' } Type: `method` Describes the server. Returns: `Object` The result. Returns `resultType: 'complete'`, `supportedVersions: ['2026-07-28']`, `capabilities: { tools: {} }` and the server info (`CONF.name`, `CONF.version`) in `_meta['io.modelcontextprotocol/serverInfo']`. ### Total.mcp.auth = function($) Type: `delegate` Decides who may use the endpoint. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `$` | `Options` | yes | | The request; call `$.success()` or `$.invalid()`. | Runs 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/`. Example: Tokens from the config ```js Total.mcp.auth = function($) { if ($.token && $.token === CONF.mcp_admin) $.success({ id: 'admin', name: 'Admin', sa: true }); else if ($.token && $.token === CONF.mcp_reader) $.success({ id: 'reader', name: 'Reader', permissions: ['tasks_read'] }); else $.invalid(); }; ``` ### Total.mcp.filter = function(tool, $) Type: `delegate` Decides which tools a caller sees and may run. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `tool` | `Object` | yes | | The definition of the tool: `name`, `description`, `inputSchema`, `outputSchema`. | | `$` | `Options` | yes | | The request; `$.user` is the caller. | Returns: `Boolean` `true` when the caller may use the tool. Optional, `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. Example: Admin tools only for admins ```js Total.mcp.filter = function(tool, $) { return !tool.name.startsWith('Admin_') || $.user.sa; }; ``` ### Total.mcp.tools Type: `property` The definitions of the tools. Returns: `Array` An 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()`. Example: Names ```js console.log(Total.mcp.tools.map(tool => tool.name)); // ['Tasks_create', 'Tasks_list', 'Tasks_remove'] ``` ### Total.mcp.versions Type: `property` The supported protocol versions. Returns: `Array` An 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. ### F.actions[name].toAITool() Type: `method` Returns the tool definition of an action. Returns: `Object` The tool definition. Returns `{ 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. Example: One tool ```js var tool = F.actions['Tasks|remove'].toAITool(); // { name: 'Tasks_remove', description: 'Removes a task', inputSchema: { type: 'object', properties: { params: {...} }, required: ['params'] } } ``` --- title: Utilities project: Total.js V5 version: 0.0.20 section: reference language: en license: MIT url: https://totaljs.es/docs/total-js-v5/0-0-20/reference/utilities/ updated: 2026-11-18T16:57:29.576Z --- # Utilities > U/Utils functions, global helpers (UID, GUID, HASH, CLONE, COPY, DIFFARR, QUERIFY, PROMISIFY), shared objects, CACHE, MEMORIZE, BACKUP, RESTORE and PATH. This page lists the global helpers, the shared global objects, the in-memory `CACHE`, the `PATH` functions and the functions of the `U` (`Utils`) module that applications use. The guide [Utilities](../../guides/utilities/) explains how they fit together, with examples. The methods added to `String`, `Number`, `Date` and `Array` are in [Prototypes](../prototypes/). ## API ### U Type: `property` The Utils module as a global object. Returns: `Object` The Utils module. All functions of `utils.js` are available through `U` and its alias `Utils` (both point to the same object). This page documents the functions that applications use; the others are used by the framework itself. Example: Use a helper ```js var ext = U.getExtension('photo.JPG'); // 'jpg' var same = Utils === U; // true ``` ### UID() Type: `method` Returns a new unique identifier. Returns: `String` For example `JacVuE1cn61f`. The identifier is a short string of letters and digits: a base-62 time stamp (in tenths of a second), an internal counter, a random character chosen at start-up (changed every minute), the length of the time part, a parity digit and the letter `f`. Identifiers created later sort after earlier ones in most cases. The `uid` validator of the framework (`DEF.validators.uid`) accepts them. Example: A new record ```js var model = {}; model.id = UID(); model.dtcreated = NOW; NOSQL('products').insert(model); ``` ### GUID([length]) Type: `method` Returns a UUID-like string, or a random string of a given length. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `length` | `Number` | no | | The number of characters. Omit it for the UUID-like format. | Returns: `String` Without `length`, it returns a string in the shape `xxxxxxxx-xxxx-Nxxx-Yxxx-xxxxxxxxxxxx` (36 characters) built from the current time and random hexadecimal digits. With `length`, it returns that many random characters from `0-9` and `a-z`. Example: Tokens ```js var guid = GUID(); // '1a1e0561-0561-4c86-8eaf-d9a327a65943' var token = GUID(30); // 30 random characters ``` ### HASH(value, [type]) Type: `method` Hashes a string. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `value` | `String` | yes | | The text to hash. | | `type` | `String` | no | | `md5`, `sha1`, `sha256`, `sha512`, `crc32` or `crc32unsigned`. | Returns: `Number|String` A number without a type, a hexadecimal string for md5/sha types. Without `type`, it returns an unsigned 32-bit number computed from the string (fast, not cryptographic). With a type it returns the hash as a hexadecimal string (`md5`, `sha1`, `sha256`, `sha512`) or a CRC32 number (`crc32`, `crc32unsigned`). `value` must be a string; convert numbers with `+ ''` first. Example: Hashes ```js HASH('abc'); // 96354 HASH('abc', 'md5'); // '900150983cd24fb0d6963f7d28e17f72' HASH(email, 'sha256'); ``` ### CLONE(obj, [skip], [nofunctions]) Type: `method` Makes a deep copy of an object or an array. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `obj` | `Object|Array` | yes | | The value to copy. Other values are returned unchanged. | | `skip` | `Object` | no | | Keys to leave out, e.g. `{ password: 1 }`. | | `nofunctions` | `Boolean` | no | `false` | `true` leaves out functions. | Returns: `Object|Array` The copy. Nested objects and arrays are copied, buffers in object properties are duplicated, and dates, errors and other non-object values are kept as they are. `skip` is an object whose keys are left out of the copy at every level. With `nofunctions`, properties that contain functions are left out too. Example: Copy without a key ```js var user = { id: 'abc', name: 'Peter', password: 'secret', address: { city: 'Bratislava' } }; var safe = CLONE(user, { password: 1 }); safe.address.city = 'Prague'; // user.address.city is still 'Bratislava' ``` ### COPY(source, [target], [all]) Type: `method` Copies the keys of one object into another. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `source` | `Object` | yes | | The object to read. | | `target` | `Object` | no | | The object to write into. | | `all` | `Boolean` | no | `true` | `false` writes only the keys that `target` already has. | Returns: `Object` The target (or the new copy). Each value of `source` is cloned and written into `target`. With `all` set to `false`, only keys that are already defined in `target` are written, so `target` works as a list of allowed fields. Without `target`, it returns a deep copy of `source`. Example: Allowed fields ```js var allowed = { name: '', email: '' }; COPY(this.body, allowed, false); // allowed contains only name and email from the body ``` ### DIFFARR(prop, db, form) Type: `method` Compares two arrays of objects by one property. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `prop` | `String` | yes | | The key that identifies an item, e.g. `id`. | | `db` | `Array` | yes | | The current items (for example from the database). | | `form` | `Array` | yes | | The new items (for example from a form). | Returns: `Object` `{ add: Array, upd: Array, rem: Array }`. Items are matched when their `prop` values are equal (`==`). The result has three arrays: `add` holds the items of `form` that are not in `db`, `upd` holds pairs `{ db, form }` of matched items, and `rem` holds the `prop` values of the `db` items that are not in `form`. Example: Synchronize items ```js var diff = DIFFARR('id', current, model.items); for (var item of diff.add) NOSQL('items').insert(item); for (var pair of diff.upd) NOSQL('items').modify(pair.form).where('id', pair.db.id); for (var id of diff.rem) NOSQL('items').remove().where('id', id); ``` ### QUERIFY([url], obj) Type: `method` Builds a query string from an object. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `url` | `String` | no | | A URL, optionally with a method in front. | | `obj` | `Object` | yes | | The values. | Returns: `String` Keys and values are URL-encoded. `null`, `undefined` and empty values are skipped, dates are written as ISO strings and arrays are joined with commas. Without `url`, the result starts with `?` (or is an empty string when nothing is left). With `url`, the query string is appended with `?` or `&`; the URL may start with an HTTP method (`GET`, `POST`, `PUT`, `PATCH`, `DELETE`, `API`) followed by a space, as `REQUEST()` and `AJAX()` take it. The function is also `U.querify()`. Example: Query strings ```js QUERIFY({ q: 'red shoes', page: 2 }); // '?q=red%20shoes&page=2' QUERIFY('/api/?lang=en', { page: 2 }); // '/api/?lang=en&page=2' QUERIFY('GET https://example.com/', { id: 5 }); // 'GET https://example.com/?id=5' ``` ### PROMISIFY(fn, [a], [b], [c]) Type: `method` Calls a callback-style function and returns a promise. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `fn` | `Function` | yes | | A function whose last argument is a callback. | | `a` | `Object` | no | | The first argument. | | `b` | `Object` | no | | The second argument. | | `c` | `Object` | no | | The third argument. | Returns: `Promise` `fn` is called with the arguments you pass (up to three) and a callback `function(err, response)`. The promise rejects with `err` or resolves with `response`. Pass only the arguments you need: an argument that is `undefined` ends the list. Example: Read a file ```js var Fs = require('fs'); var buffer = await PROMISIFY(Fs.readFile, PATH.root('README.md')); ``` ### ERROR([name]) Type: `method` Returns a callback that logs errors. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `name` | `String` | no | | The name shown with the error, e.g. the function that failed. | Returns: `Function` `function(err)`. The returned function takes `err` as its first argument and, when it is set, passes it to the error handler of the framework (`DEF.onError`, which prints it and keeps it in the stats) with `name` as the source. Use it for callbacks whose result you do not need but whose errors you want to see. Example: Log a failed write ```js Fs.writeFile(PATH.databases('cache.json'), JSON.stringify(data), ERROR('cache.save')); ``` ### print(...values) Type: `method` Writes values to the console. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `values` | `Object` | yes | | The values to print. | `print` is `console.log`. The framework uses it for its start-up information. Example: Print ```js print('Imported', count, 'products'); ``` ### NOW Type: `property` A Date with the current time, refreshed every 5 seconds. Returns: `Date` The framework assigns `new Date()` to `NOW` every 5 seconds once it is loaded, and also when it writes an error, an audit log or a cache item. Use it where a precision of a few seconds is enough: expirations, log lines, `dtcreated` fields. Do not change the object; assign a new date instead. Example: Expiration ```js var expire = NOW.add('1 hour'); if (session.expire < NOW) delete sessions[session.id]; ``` ### NOOP Type: `property` An empty function. Returns: `Function` Use it where a callback is required but you do not need the result. It is the same function as `U.noop`. Example: Ignore the result ```js Fs.unlink(filename, NOOP); ``` ### EMPTYOBJECT Type: `property` A frozen empty object; EMPTYARRAY is a frozen empty array. Returns: `Object` `EMPTYOBJECT` (`{}`) and `EMPTYARRAY` (`[]`) are created once and frozen with `Object.freeze()`, so they cannot be changed. Use them as default values instead of creating new objects, for example `var opt = options || EMPTYOBJECT;`. Never write into them: in strict mode a write throws. Example: Defaults ```js function find(filter) { var opt = filter || EMPTYOBJECT; var tags = opt.tags || EMPTYARRAY; return tags.length; } ``` ### MAIN Type: `property` A global object for the shared state of the application. Returns: `Object` The framework creates `MAIN` as an empty object and does not use it. Store there what several files of your application share: settings loaded at start, open connections, counters. It is readable in views as `MAIN`. Example: Shared settings ```js // definitions/settings.js MAIN.settings = MEMORIZE('settings'); // a controller or an action var title = MAIN.settings.title; ``` ### REPO Type: `property` A global object for shared data, also available in views. Returns: `Object` An empty object that the framework creates at start (it is also `F.repo`). Views can read it as `REPO`, which makes it a good place for data that layouts need, for example a menu or the contact information. Example: Data for the layout ```js REPO.menu = [{ name: 'Home', url: '/' }, { name: 'Contact', url: '/contact/' }]; // views/layout.html // @{foreach m in REPO.menu}<a href="@{m.url}">@{m.name}</a>@{end} ``` ### FUNC Type: `property` A global object for your shared functions. Returns: `Object` An empty object for functions that several parts of the application use. Define them in `/definitions/` so they exist before the first request. Views can read `FUNC` too. Example: A shared function ```js // definitions/func.js FUNC.price = function(value) { return value.format(2) + ' EUR'; }; // anywhere var text = FUNC.price(12.5); ``` ### TEMP Type: `property` A global object for short-lived data, cleared every 5 minutes. Returns: `Object` Every 5 minutes the framework replaces `TEMP` with a new empty object. Use it for small temporary data that may disappear at any time, such as one-time tokens or throttling counters. Always read it through the global (`TEMP.key`), not through a saved reference, because the object changes. Example: A short-lived token ```js var token = GUID(20); TEMP[token] = { userid: user.id }; // later var data = TEMP[token]; if (!data) $.invalid('The token has expired'); ``` ### MODS Type: `property` The loaded modules by their id. Returns: `Object` Each `.js` file in `/modules/` is loaded at start and stored in `MODS` under its `exports.id`, or under the file name when it does not set one. Its `install()` function, if any, is called after loading. `MODS` is the same object as `F.modules` and can be read in views. Example: A module ```js // modules/pricing.js exports.id = 'pricing'; exports.vat = function(price) { return price * 1.2; }; // anywhere var total = MODS.pricing.vat(100); ``` ### CACHE.set(key, value, [expire]) Type: `method` Stores a value in the in-memory cache. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `key` | `String` | yes | | The key. | | `value` | `Object` | yes | | Any value. | | `expire` | `String` | no | `'5 minutes'` | How long the value is valid. | The value is kept in the memory of the process until it expires. `expire` is a duration in the form that `Date.add()` accepts (`'30 seconds'`, `'5 minutes'`, `'1 hour'`, `'2 days'`). The value is stored as it is, not copied: change it and the cached value changes too. Expired items are removed every minute. Example: Cache a result ```js CACHE.set('products', items, '2 minutes'); ``` ### CACHE.get(key, [def]) Type: `method` Reads a value from the in-memory cache. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `key` | `String` | yes | | The key. | | `def` | `Object` | no | | The value returned when the key is missing or expired. | Returns: `Object` Returns the value when it exists and has not expired; otherwise `def`. `CACHE.read()` is an alias. Example: Read or load ```js var items = CACHE.get('products'); if (!items) { items = await DATA.find('nosql/products').promise($); CACHE.set('products', items, '2 minutes'); } ``` ### CACHE.remove(key) Type: `method` Removes one value from the in-memory cache. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `key` | `String` | yes | | The key. | Call it when the cached data changes, so the next read loads fresh data. Example: Invalidate ```js NOSQL('products').insert(model).callback(function() { CACHE.remove('products'); }); ``` ### CACHE.reset([search]) Type: `method` Removes many values, or all of them. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `search` | `String|RegExp` | no | | A part of the keys, or a pattern. | Returns: `Number` The number of removed keys. Without `search`, the whole cache is cleared. With a string, every key that contains it is removed; with a regular expression, every key that matches it. Returns the number of removed keys (0 when the whole cache is cleared). Example: Remove a group ```js CACHE.set('products_1', a); CACHE.set('products_2', b); CACHE.reset('products_'); // 2 CACHE.reset(/^user_/); CACHE.reset(); // everything ``` ### MEMORIZE([name], [delay], [skip]) Type: `method` Returns an object that is saved to a JSON file. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `name` | `String` | no | | The name of the file. | | `delay` | `Number` | no | `10000` | Milliseconds between the last change and the write. | | `skip` | `String|Array` | no | | Keys not written to the file, as an array or a comma-separated string. | Returns: `Object` The data with `save()` and `set(key, value)`. Reads `databases/memorize_{name}.json` (or `databases/memorize.json` without a name) and returns its content as an object (an empty object when the file does not exist). The object gets two functions: `save()` schedules a write of the whole object, and `set(key, value)` assigns a value and calls `save()`. The write happens `delay` milliseconds after the last call, so many changes produce one write. `skip` lists keys that are not written. The arguments `delay` and `skip` may be swapped. Call `MEMORIZE()` once per name and keep the object; every call reads the file again. Example: Settings that survive restarts ```js var settings = MEMORIZE('settings', 'cache'); settings.set('title', 'My shop'); settings.counter = (settings.counter || 0) + 1; settings.cache = {}; // not written settings.save(); ``` ### BACKUP(filename, files, [callback], [filter]) Type: `method` Packs files and directories into one archive file. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `filename` | `String|Stream` | yes | | The archive file to create (an existing file is replaced). | | `files` | `String|Array` | yes | | A directory, or paths relative to the root. | | `callback` | `Function` | no | | `function(err, meta)`. | | `filter` | `Function` | no | | `function(path, isdirectory)`; return `true` to pack the path. | Returns: `Promise` When `callback` is omitted. Writes a text archive: one line per directory and one line per file, with the path and the gzip-compressed content in base64. `files` is a directory (everything in it is packed with paths relative to it) or an array of paths relative to the application root (files and whole directories). Names that contain `.git`, `.gitignore`, `.npmignore` or `.ds_store` are skipped. `filter(path, isdirectory)` gets each path (starting with `/`) and leaves it out when it returns a falsy value. `filename` can also be a writable stream. The callback gets `{ filename, files, size }`; without a callback, the function returns a promise. Example: Back up the uploads ```js var meta = await BACKUP(PATH.temp('uploads.backup'), PATH.public('uploads'), null, function(path, isdir) { return isdir || !path.endsWith('.tmp'); }); print(meta.files, 'files', meta.size, 'bytes'); ``` Example: Selected paths ```js await BACKUP(PATH.temp('app.backup'), ['config', 'databases', 'public/uploads']); ``` ### RESTORE(filename, target, [callback], [filter]) Type: `method` Unpacks an archive made by BACKUP(). | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `filename` | `String|Stream` | yes | | The archive. | | `target` | `String` | yes | | The directory to unpack into. | | `callback` | `Function` | no | | `function(err, meta)`. | | `filter` | `Function` | no | | `function(path, isdirectory)`. | Returns: `Promise` When `callback` is omitted. Creates the directories and files of the archive inside `target`. `filename` can also be a readable stream. `filter(path, isdirectory)` is called for each item: for a directory, `false` skips creating it; for a file, return `false` to skip it, a string to write it under that path (relative to `target`), or nothing to keep its path. The callback gets `{ files, size, path }`; without a callback, the function returns a promise. Example: Restore ```js var meta = await RESTORE(PATH.temp('uploads.backup'), PATH.public('uploads')); print('Restored', meta.files, 'files'); ``` Example: Skip files on the way ```js RESTORE(PATH.temp('app.backup'), PATH.root(), function(err) { err && print(err); }, function(path, isdir) { if (!isdir && path.startsWith('/config')) return false; }); ``` ### PATH.root([path]) Type: `method` Returns the root directory of the application, or a path inside it. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `path` | `String` | no | | A relative path. | Returns: `String` An absolute path. The root is the directory of the application (where the start script runs). With `path`, it returns the root joined with it. Like the other directory functions of `PATH`, it creates the directory the first time it is called with a path. `PATH.public()`, `PATH.private()`, `PATH.logs()`, `PATH.plugins()`, `PATH.modules()`, `PATH.templates()`, `PATH.flowstreams()` and `PATH.scripts()` work the same for their directories. Example: Paths ```js PATH.root(); // '/www/app' PATH.root('config'); // '/www/app/config' PATH.private('report.pdf'); // '/www/app/private/report.pdf' ``` ### PATH.databases([path]) Type: `method` Returns the databases directory, or a path inside it. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `path` | `String` | no | | A relative path. | Returns: `String` An absolute path. The directory `/databases/` holds the files of NoSQL databases, `MEMORIZE()` files and other data of the application. It is created when you first ask for a path inside it. Example: A data file ```js var filename = PATH.databases('import.json'); Fs.writeFile(filename, JSON.stringify(data), NOOP); ``` ### PATH.temp([path]) Type: `method` Returns the temporary directory, or a path inside it. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `path` | `String` | no | | A relative path. | Returns: `String` An absolute path. The directory `/tmp/` holds uploads, cached files and compiled assets. `PATH.tmp()` is an alias. When the application starts, the framework deletes its own temporary files there (`.js`, `.css`, `.html`, `.htm`, `.tmp` and `.upload` files). Keep data that must last in `/databases/`. Example: A temporary file ```js var filename = PATH.temp(UID() + '.csv'); ``` ### PATH.exists(path, [callback]) Type: `method` Checks whether a file or a directory exists. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `path` | `String` | yes | | An absolute path. | | `callback` | `Function` | no | | `function(exists, size, isfile)`. | Returns: `Promise<Boolean>` When `callback` is omitted. The callback gets three arguments: `exists`, the size in bytes and `isfile` (`true` for a file, `false` for a directory). Without a callback, the function returns a promise that resolves with `exists`. Example: Check a file ```js if (await PATH.exists(PATH.databases('settings.json'))) print('Settings found'); PATH.exists(PATH.public('robots.txt'), function(exists, size, isfile) { print(exists, size, isfile); }); ``` ### PATH.unlink(files, [callback]) Type: `method` Deletes one or more files. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `files` | `String|Array` | yes | | An absolute path, or an array of paths. | | `callback` | `Function` | no | | `function()`. | Deletes the files one after another and then calls the callback. Errors (for example a missing file) are ignored. Example: Delete files ```js PATH.unlink([PATH.temp('a.csv'), PATH.temp('b.csv')], function() { print('Removed'); }); ``` ### PATH.rmdir(directories, [callback]) Type: `method` Deletes directories with everything in them. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `directories` | `String|Array` | yes | | An absolute path, or an array of paths. | | `callback` | `Function` | no | | `function()`. | For each directory, all files are deleted, then the subdirectories from the deepest one, then the directory itself. Then the callback is called. Example: Delete a directory ```js PATH.rmdir(PATH.temp('export'), function() { print('Directory removed'); }); ``` ### Total.FsPromises Type: `property` The Node.js module `node:fs/promises`. Returns: `Object` The module `node:fs/promises`. The promise version of the file system functions of Node.js, loaded by the framework. `F.FsPromises` is the same object, and `Total.Fs` (`F.Fs`) is the module `node:fs`. Example: Read and list ```js var text = await Total.FsPromises.readFile(PATH.root('README.md'), 'utf8'); var files = await Total.FsPromises.readdir(PATH.public()); ``` ### U.parseInt(value, [def]) Type: `method` Converts any value to a number. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `value` | `Object` | yes | | The value to convert. | | `def` | `Number` | no | `0` | The result for empty or invalid values. | Returns: `Number` A number is returned as it is. A string is trimmed and converted with the unary `+`; other values are converted to a string first. `null`, `undefined`, an empty string and a value that is not a number return `def` (0 by default). The result is not rounded (`'1.5'` gives `1.5`). `U.parseFloat(value, [def])` works the same and also accepts a comma as the decimal separator (`'12,50'` gives `12.5`). Example: Query values ```js var page = U.parseInt(this.query.page, 1); var price = U.parseFloat(this.query.price); ``` ### U.parseBoolean(value, [def]) Type: `method` Converts any value to a boolean. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `value` | `Object` | yes | | The value to convert. | | `def` | `Boolean` | no | `false` | The result for `null` or `undefined`. | Returns: `Boolean` A boolean is returned as it is; a number is `true` when it is greater than 0; the strings `true`, `1` and `on` (in any case) are `true` and every other string is `false`. `null` and `undefined` return `def` (`false` by default). Example: A checkbox ```js var newsletter = U.parseBoolean(this.body.newsletter); // 'on' -> true ``` ### U.get(obj, path) Type: `method` Reads a nested value by a path. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `obj` | `Object` | yes | | The object to read. | | `path` | `String` | yes | | The path. | Returns: `Object` The value, or `undefined`. The path uses dots and brackets: `a.b.c`, `items[0].name`. When a part of the path is missing, it returns `undefined` instead of throwing. Paths with spaces, parentheses or keywords such as `__proto__` and `constructor` are refused (`undefined`). Compiled readers are cached per path. Example: Nested values ```js var data = { user: { address: { city: 'Bratislava' } }, items: [{ name: 'A' }] }; U.get(data, 'user.address.city'); // 'Bratislava' U.get(data, 'items[0].name'); // 'A' U.get(data, 'user.phone.number'); // undefined ``` ### U.set(obj, path, value) Type: `method` Writes a nested value by a path. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `obj` | `Object` | yes | | The object to write into. | | `path` | `String` | yes | | The path. | | `value` | `Object` | yes | | The value. | Returns: `Object` The written value. Missing objects on the path are created. A path that ends with `[]` pushes the value into the array, and an index creates an array with objects in it (`items[0].name`). Paths with spaces, parentheses or keywords such as `__proto__` and `constructor` are refused: nothing is written. Returns the value. Example: Build an object ```js var model = {}; U.set(model, 'address.city', 'Bratislava'); U.set(model, 'tags[]', 'new'); // { address: { city: 'Bratislava' }, tags: ['new'] } ``` Example: Path with an index ```js var model = {}; U.set(model, 'items[0].name', 'Pen'); // { items: [{ name: 'Pen' }] } ``` ### U.extend(target, source, [rewrite]) Type: `method` Copies the keys of source into target. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `target` | `Object` | yes | | The object to write into. | | `source` | `Object` | yes | | The object to read. | | `rewrite` | `Boolean` | no | `true` | `false` keeps existing values. | Returns: `Object` The target. Every key of `source` is cloned into `target`. With `rewrite` set to `false`, keys that already exist in `target` are not changed, which is how you fill defaults. Returns `target`. Example: Defaults ```js var options = { limit: 50 }; U.extend(options, { limit: 10, sort: 'name' }, false); // { limit: 50, sort: 'name' } ``` ### U.sortcomparer(sort) Type: `method` Returns a compare function for Array.sort(). | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `sort` | `String` | yes | | For example `name` or `price_desc,name`. | Returns: `Function` `function(a, b)` for `Array.prototype.sort()`. `sort` is a comma-separated list of keys; add `_desc` for descending order (`_asc` is the default). Nested keys use dots (`address.city`). The type of each key is read from the first value that is not empty the first time the expression is used, and is kept for later uses of the same expression: strings are compared with diacritics in mind, numbers, booleans and dates by value. Example: Sort products ```js products.sort(U.sortcomparer('price_desc,name')); ``` ### U.random([max], [min]) Type: `method` Returns a random integer in a range. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `max` | `Number` | no | `100000` | The largest value. | | `min` | `Number` | no | `0` | The smallest value. | Returns: `Number` Returns an integer between `min` and `max`, both included. Example: A dice ```js var dice = U.random(6, 1); ``` ### U.random_text(length) Type: `method` Returns a random string of letters and digits. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `length` | `Number` | yes | | The number of characters. | Returns: `String` The characters are `0-9`, `A-Z` and `a-z`. `U.random_string(length)` uses only letters, and `U.random_number(length)` only digits (returned as a string that does not start with 0). These values come from `Math.random()`: do not use them as passwords or security tokens. Example: Random strings ```js U.random_text(8); // 'yb7JVb2a' U.random_string(6); // 'HNXkTk' U.random_number(6); // '825174' ``` ### U.convert62(number) Type: `method` Converts a number to a base-62 string. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `number` | `Number` | yes | | A non-negative number. | Returns: `String` The digits are `0-9`, `A-Z` and `a-z`, in this order. The number is rounded down first. `U.from62(value)` converts the string back to the number. Use it for short codes made from numeric ids. Example: Short codes ```js var code = U.convert62(123456); // 'W7E' var id = U.from62(code); // 123456 ``` ### U.getExtension(filename, [raw]) Type: `method` Returns the extension of a file name. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `filename` | `String` | yes | | A file name, a path or a URL. | | `raw` | `Boolean` | no | `false` | `true` keeps the original case. | Returns: `String` Returns the part after the last dot, without the dot and in lower case (with `raw`, in the original case). A query string after `?` is ignored. Returns an empty string when the name has no extension. Example: Extensions ```js U.getExtension('/img/Photo.JPG'); // 'jpg' U.getExtension('/files/a.pdf?v=1'); // 'pdf' U.getExtension('README'); // '' ``` ### U.getName(path) Type: `method` Returns the last part of a path. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `path` | `String` | yes | | A path or a URL. | Returns: `String` Returns the file name (or the last directory) of a path with `/` or `\\` separators. A trailing separator is ignored. Example: File names ```js U.getName('/www/app/public/logo.png'); // 'logo.png' U.getName('/www/app/public/'); // 'public' ``` ### U.getContentType(ext) Type: `method` Returns the MIME type for an extension. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `ext` | `String` | yes | | An extension, e.g. `png` or `.png`. | Returns: `String` The extension may start with a dot. Unknown extensions return `application/octet-stream`. `U.getExtensionFromContentType(type)` does the reverse and returns the first extension with that type (or `undefined`). The whole table is `U.contentTypes`. Example: Content types ```js U.getContentType('png'); // 'image/png' U.getContentType('.json'); // 'application/json' U.getExtensionFromContentType('image/png'); // 'png' ``` ### U.btoa(value) Type: `method` Encodes text or a buffer to base64. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `value` | `String|Buffer` | yes | | The data to encode. | Returns: `String` A buffer is encoded directly; other values are converted to a string and encoded as UTF-8. `U.atob(value)` decodes base64 back to a UTF-8 string. Example: Base64 ```js var encoded = U.btoa('Hello'); // 'SGVsbG8=' var text = U.atob(encoded); // 'Hello' ``` ### U.validhost(host) Type: `method` Checks that a host name is plain ASCII and that an IP address is in its canonical form. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `host` | `String` | yes | | The host name or IP address. | Returns: `Boolean` `true` for a valid host. Returns `false` for a value that is not a string, is empty, or contains a character outside the visible ASCII range (spaces, NUL bytes, letters with accents). A value made only of numbers and dots (or hex numbers) must be a canonical IPv4 address: `127.0.0.1` is valid, `127.1`, `0127.0.0.1`, `0x7f.0.0.1` and `2130706433` are not. Other ASCII values, including IPv6 addresses, return `true`; the function does not check the full syntax of a host name. Convert an international name with `U.tohost()` first. Example: Check hosts ```js U.validhost('example.com'); // true U.validhost('127.0.0.1'); // true U.validhost('127.1'); // false U.validhost('0x7f.0.0.1'); // false U.validhost('münchen.de'); // false U.validhost('evil.example\0.trusted.example'); // false ``` ### U.tohost(host) Type: `method` Converts a host name to its canonical ASCII form. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `host` | `String` | yes | | The host name or IP address. | Returns: `String` The canonical host, or an empty string. Converts the host with the URL parser of Node.js: letters become lower case, an international name becomes punycode, and an IPv4 address in another notation becomes the dotted form (a leading `0` means an octal number, `0x` a hex number). The result is then checked with `U.validhost()`. A value that contains `:` (an IPv6 address) is only checked. Returns an empty string when the host is not valid, so test the result before you use it. Example: Convert hosts ```js U.tohost('münchen.de'); // 'xn--mnchen-3ya.de' U.tohost('EXAMPLE.com'); // 'example.com' U.tohost('127.1'); // '127.0.0.1' U.tohost('0x7f.0.0.1'); // '127.0.0.1' U.tohost('evil.example\0.trusted.example'); // '' ``` Example: Validate input ```js function host(value) { var host = U.tohost(value); if (!host) throw new Error('Invalid hostname'); return host; } ``` ### U.wait(validator, [callback], [timeout], [interval]) Type: `method` Waits until a condition is true. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `validator` | `Function` | yes | | Returns `true` when the wait is over. | | `callback` | `Function` | no | | `function(err, success)`. | | `timeout` | `Number` | no | `5000` | Milliseconds before the wait fails. | | `interval` | `Number` | no | `500` | Milliseconds between checks. | Returns: `Promise` When `callback` is omitted. `validator` is called right away and then every `interval` milliseconds until it returns `true`; then the callback gets `(null, true)`. When `timeout` passes first, the callback gets an `Error('Timeout')`. Without a callback, the function returns a promise that resolves or rejects the same way. Example: Wait for a connection ```js await U.wait(() => MAIN.db != null, null, 10000, 200); print('Database ready'); ``` ### U.resolve(url, callback, [param]) Type: `method` Resolves the host of a URL to IPv4 addresses, with a cache. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `url` | `String` | yes | | An absolute URL. | | `callback` | `Function` | yes | | `function(err, uri, param, addresses)`. | | `param` | `Any` | no | | A value passed to the callback. | Parses `url`, checks its host name with `U.validhost()` and asks the DNS servers for its IPv4 addresses (`dns.resolve4()`, so the hosts file is not used). The callback gets `(err, uri, param, addresses)`: `uri` is the parsed URL with `host` set to the first address, `param` is the third argument and `addresses` the whole list. The addresses are cached for the life of the process; a failed lookup is tried once more before `err` is passed. A string that is not a URL gives `TypeError: Invalid URL`, and a host name that is not valid gives the error `Invalid hostname` without a DNS query. For `http` and `https` URLs the URL parser already converts the host; for other schemes a non-canonical address such as `tcp://127.1/` gives `Invalid hostname`. `REQUEST()` uses this function with the option `resolve: true`, and `RESTBuilder` by default. Example: Resolve a host ```js U.resolve('https://example.com/api/', function(err, uri, param, addresses) { if (err) console.log(err.message || err.code); else console.log(uri.hostname, addresses); }); ``` ### U.streamer(beg, [end], callback, [skip], [stream]) Type: `method` Splits a stream of data into parts by delimiters. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `beg` | `String|Buffer` | yes | | The start of a part, or the separator. | | `end` | `String|Buffer` | no | | The end of a part. | | `callback` | `Function` | yes | | `function(value, index)`; return `false` to stop. | | `skip` | `Number` | no | `0` | The number of first parts to ignore. | | `stream` | `Stream` | no | | A stream whose `end` event flushes the rest. | Returns: `Function` `function(chunk)`. Returns a function that you call with each chunk (a buffer), for example as the `data` handler of a stream. With `beg` and `end`, the callback gets each part that starts with `beg` and ends with `end`, both included (for example one `<item>...</item>` of a large XML file). With `beg` only, `beg` is a separator and the callback gets each part up to and including it (for example lines with `\n`). The callback gets `(value, index)` with the value as a string; returning `false` stops the parsing. `skip` ignores that many first parts. With `stream`, the remaining data is processed when the stream ends. `U.streamer2()` takes the same arguments and passes buffers instead of strings. Example: Read a large XML file ```js var stream = Fs.createReadStream(PATH.databases('products.xml')); stream.on('data', U.streamer('<product>', '</product>', function(value, index) { var product = value.parseXML(); print(index, product); })); ``` Example: Lines of a CSV file ```js var stream = Fs.createReadStream(filename); stream.on('data', U.streamer('\n', function(line, index) { var cols = line.trim().split(';'); }, 1, stream)); // skips the header line ``` ### U.connect(options, [callback]) Type: `method` Opens a TCP or TLS connection. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `options` | `Object` | yes | | `{ host, port, secure, tls, timeout }` and, with `secure`, other options of `tls.connect()`. | | `callback` | `Function` | no | | `function(err, meta)`. | Connects to `options.host` and `options.port` and calls `callback(err, meta)` when the connection is open. The host is converted with `U.tohost()` first, so an international name is sent as punycode and `127.1` as `127.0.0.1`; a host that is not valid gives the error `Invalid hostname` and no connection is made. With `secure: true` the connection uses TLS from the start and the other options (`servername`, `rejectUnauthorized`, `ca` ...) go to `tls.connect()`. With `tls` the connection starts as plain TCP and is upgraded to TLS as soon as it is open: `tls: true` uses the default options of `tls.connect()`, an object passes its options (`servername`, `rejectUnauthorized`, `ca` ...). With `timeout` (in milliseconds) a connection that is not open in time gives the error `Timeout`. `meta` has `socket` (the Node.js socket), `opt` (the options with the converted host), `write(data)`, `ondata(fn)` for the received chunks, and `close()` (also `destroy()`). `LDAP()` connects with this function. Example: Read the greeting of a server ```js U.connect({ host: 'mail.example.com', port: 25, timeout: 5000 }, function(err, meta) { if (err) { console.log(err.message); return; } meta.ondata(function(chunk) { console.log(chunk.toString()); meta.close(); }); }); ``` Example: Upgrade to TLS ```js U.connect({ host: 'mail.example.com', port: 465, tls: { servername: 'mail.example.com' } }, function(err, meta) { if (!err) console.log(meta.socket.encrypted); // true }); ``` ### U.ls(path, [callback], [filter]) Type: `method` Lists the files and directories of a directory recursively. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `path` | `String` | yes | | The directory. | | `callback` | `Function` | no | | `function(files, directories)`. | | `filter` | `String|RegExp|Function` | no | | The filter. | Returns: `Promise` `{ files, directories }` when `callback` is omitted. The callback gets two arrays of absolute paths: `files` and `directories` (directories end with the path separator). `filter` can be a string (paths that contain it, case-insensitive), a regular expression, or a function `(path, isdirectory)` that returns `true` to keep the item; string and regular expression filters apply to files only. A directory that the filter drops is not searched. Without a callback, the function returns a promise with `{ files, directories }`. `U.ls2()` takes the same arguments and returns files as `{ filename, stats }` objects with the `fs.Stats` of each file. Example: Find JSON files ```js U.ls(PATH.databases(), function(files, directories) { print(files); }, /\.json$/); ``` Example: Sizes with ls2 ```js var result = await U.ls2(PATH.public('uploads')); var size = 0; for (var file of result.files) size += file.stats.size; ``` ### U.chunker(name, [max]) Type: `method` Stores a large list in temporary files, in pages. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `name` | `String` | yes | | A unique name, used for the file names. | | `max` | `Number` | no | `50` | Items per page. | Returns: `Chunker` A chunker collects items with `write(item)` (alias `append()`); every `max` items are written to a file `tmp/{name}-{index}.chunker` (compressed with deflate when `compress` is `true`, the default) so the memory stays small. Call `end()` to write the rest. Then `each(onitem, [ondone])` reads the pages in order: `onitem(items, next, index)` gets one page and calls `next()` to continue, and `percentage` tells how far the reading is. `read(index, callback)` reads one page. With `autoremove` (`true` by default), each file is deleted after it is read; `clear()` deletes all files and `destroy()` also releases the chunker. The properties `count` and `pages` hold the number of items and pages. Example: Process a large export ```js var chunker = U.chunker('export', 100); for (var row of rows) chunker.write(row); chunker.end(); chunker.each(function(items, next, index) { print('Page', index, chunker.percentage + '%'); send(items, next); }, function() { print('Done', chunker.count, 'items'); }); ``` ### chunker.load([callback]) Type: `method` · Since: `0.0.16` Finds the pages that an earlier chunker with the same name left on disk. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `callback` | `Function` | no | | `function(err, count)`. | Returns: `Promise` When `callback` is omitted. Counts the files of the chunker in the temporary directory and sets the internal page index, so `each()` and `read()` can read the pages that an earlier instance wrote and did not read (for example before a restart). Create the chunker with the same `name`. The callback gets `(null, count)`; without a callback, the function returns a promise that resolves when the counting is done. Example: Continue a chunker ```js var chunker = U.chunker('export'); await chunker.load(); chunker.each(function(items, next) { send(items, next); }); ``` ### new U.EventEmitter2() / U.EventEmitter2(obj) Type: `class` A small event emitter. Returns: `EventEmitter2` An object with `on(name, fn)`, `once(name, fn)`, `off(name, [fn])` and `emit(name, ...args)` (up to seven arguments). `off(name)` without a function removes all handlers of the event. Handlers run with the emitter as `this`. Called with an object (`U.EventEmitter2(obj)`), it adds these methods to that object, unless it already has `emit`, and returns it. Example: Events on your object ```js var Cart = {}; U.EventEmitter2(Cart); Cart.on('add', function(item) { print('Added', item.name); }); Cart.emit('add', { name: 'Shoes' }); ``` ### U.encrypt_data(value, key, [encode]) Type: `method` Obfuscates a string with a key. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `value` | `String` | yes | | The text. | | `key` | `String` | yes | | The key. | | `encode` | `String` | no | `'base64'` | The output encoding, or `buffer`. | Returns: `String|Buffer` Encodes the string with the key and a random 4-byte mask and returns it in base64 (or in the encoding you set; `buffer` returns a buffer). The same input gives a different output each time. `U.decrypt_data(value, key, [encode])` returns the original string, or `null` for invalid input. This is a light obfuscation, not strong encryption; for sensitive data use `ENCRYPT()` (see [Encryption](../../guides/encryption/)). Example: Round trip ```js var data = U.encrypt_data('hello', 'mykey'); var text = U.decrypt_data(data, 'mykey'); // 'hello' ``` ### U.encrypt_uid(value, [key]) Type: `method` Signs an identifier so that it cannot be changed. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `value` | `String|Number` | yes | | The identifier. | | `key` | `String` | no | `CONF.secret` | The key. | Returns: `String` Returns the identifier with a checksum in front, made from the value, the key and `CONF.secret_uid`. `U.decrypt_uid(value, [key])` checks it and returns the original identifier (a number when the original was a number) or `null` when the value was changed. The identifier itself stays readable. Without `key`, `CONF.secret` is used. Example: Signed id in a link ```js var signed = U.encrypt_uid(123, 'mykey'); // 'n...x123', the checksum depends on CONF.secret_uid U.decrypt_uid(signed, 'mykey'); // 123 U.decrypt_uid('n2v55u4jx124', 'mykey'); // null ``` ### U.minify_js(value) Type: `method` Minifies JavaScript; U.minify_css() and U.minify_html() do the same for CSS and HTML. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `value` | `String` | yes | | The source code. | Returns: `String` These are the minifiers that the framework uses for static files and views. They take a string and return the minified string. Example: Minify ```js U.minify_js('var a = 1 ; // note\n'); // 'var a=1;' U.minify_css('a { color : red ; }'); // 'a{color:red}' U.minify_html(html); ``` ### U.aistreamer(online, [onmessage]) Type: `method` · Since: `0.0.16` Parses a streamed response of an AI chat API into lines of text. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `online` | `Function` | yes | | `function(line)`, called for each complete line of text. | | `onmessage` | `Function` | no | | `function(message)`, called for each parsed JSON message. | Returns: `Function` `function(chunk)`. Returns a function that you call with each chunk (a buffer) of a streamed response. It reads JSON messages line by line in two formats: server-sent events with `data: {...}` (OpenAI completions, where the text is in `choices[0].delta.content` and `data: [DONE]` ends it) and plain JSON lines (Ollama, where the text is in `message.content` and `done` ends it). The text is collected and `online(line)` is called for every complete line. `onmessage(obj)`, when you set it, gets every parsed message; JSON dates are then parsed as dates. Example: Print an answer line by line ```js var parser = U.aistreamer(function(line) { print(line); }); response.stream.on('data', parser); ``` ### FILECACHE(id, expire, callback, maker, [encoding]) Type: `method` Caches the result of a task in a file. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `id` | `String` | yes | | Identifier of the cached item. | | `expire` | `String` | yes | | How long the file is valid, for example `'5 minutes'`. | | `callback` | `Function` | yes | | `function(err, response)`. | | `maker` | `Function` | yes | | `function(next, id)` that creates the value. | | `encoding` | `String` | no | `json` | `json` or a file encoding such as `utf8`. | Looks for the file of `id` in `tmp/`. When it exists and is newer than `expire`, its content goes to `callback(err, response)`. Otherwise `maker(next, id)` runs; `next(err, response, [load])` writes the response to the file and calls `callback`, unless `load` is `false`. With the `json` encoding the value is stored as JSON and parsed back; any other encoding stores and reads the raw content. Example: Cache a remote list ```js FILECACHE('currencies', '1 day', function(err, response) { MAIN.currencies = response; }, function(next) { REQUEST({ url: 'https://example.com/rates.json', callback: function(err, response) { next(err, err ? null : response.body.parseJSON()); }}); }); ``` --- title: Prototypes project: Total.js V5 version: 0.0.20 section: reference language: en license: MIT url: https://totaljs.es/docs/total-js-v5/0-0-20/reference/prototypes/ updated: 2026-11-18T16:57:14.575Z --- # Prototypes > Every method that Total.js adds to String, Number, Date and Array.prototype. Methods 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. ## API ### str.format(arg0, [arg1], [...]) Type: `method` Replaces numbered placeholders {0}, {1}, ... with the arguments. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `arg0...argN` | `Any` | yes | | Values for `{0}`, `{1}` and so on. | Returns: `String` The new string. Each `{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. Example: Numbered placeholders ```js 'Hello {0}, you have {1} messages.'.format('Peter', 5); // Hello Peter, you have 5 messages. ``` ### str.args(obj, [encode], [def]) Type: `method` Replaces named placeholders {key} or {{key}} with values of an object. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `obj` | `Object` | yes | | The values. | | `encode` | `String|Function` | no | | `html`, `json`, a function `(value, key)` or any other string for URL encoding. | | `def` | `String` | no | | The text for keys without a value. | Returns: `String` The new string. `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). `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. Example: Named placeholders ```js var tpl = 'Hello {name}, your order {{ id }} is ready.'; tpl.args({ name: 'Peter', id: 'A100' }); // Hello Peter, your order A100 is ready. '<b>{name}</b>'.args({ name: '<script>' }, 'html'); // <b><script></b> ``` ### str.slug([max]) Type: `method` Makes a URL-friendly slug from the text. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `max` | `Number` | no | `60` | The maximum length of the slug. | Returns: `String` The slug. The 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. When 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. Example: Slug a title ```js ' Hello World! Čaute 123 '.slug(); // hello-world-caute-123 'A very long article title'.slug(10); // a-very-lon ``` ### str.max(length, [chars]) Type: `method` Shortens the text to a maximum length and adds an ellipsis. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `length` | `Number` | yes | | The maximum length of the result. | | `chars` | `String` | no | `'...'` | The text appended to a shortened string. | Returns: `String` The text, shortened when needed. When the text is longer than `length`, it is cut so that the result including `chars` has exactly `length` characters. Shorter text is returned unchanged. Example: Shorten ```js 'Hello world'.max(8); // Hello... 'Hello world'.max(8, '…'); // Hello w… ``` ### str.capitalize([first]) Type: `method` Capitalizes the first letter of every word, or only of the text. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `first` | `Boolean` | no | `false` | Capitalize only the first character. | Returns: `String` The new string. The 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. Example: Capitalize ```js 'hello WORLD'.capitalize(); // Hello World 'hello WORLD'.capitalize(true); // Hello world ``` ### str.toName() Type: `method` Cleans a person name: removes digits and symbols, extra spaces and capitalizes words. Returns: `String` The cleaned name. Only 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. Example: Clean a name ```js 'peter sirka 12'.toName(); // Peter Sirka ``` ### str.encode() Type: `method` Encodes HTML special characters. Returns: `String` The encoded text. `String.safehtml()` is the same method. The characters `<`, `>`, `"`, `'` and `&` are replaced with `<`, `>`, `"`, `'` and `&`. Use it before you put user text into HTML. Example: Encode user input ```js '<a href="x">Tom & Jerry</a>'.encode(); // <a href="x">Tom & Jerry</a> ``` ### str.decode() Type: `method` Decodes HTML entities back to characters. Returns: `String` The decoded text. Named entities (`<`, `&`, `"`, ...) and numeric entities (`A`, `A`) are replaced with their characters. Unknown named entities stay as they are. Example: Decode ```js '<b>Tom & Jerry!</b>'.decode(); // <b>Tom & Jerry!</b> ``` ### str.removeTags() Type: `method` Removes HTML tags from the text. Returns: `String` The text without tags. Every `<...>` 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. Example: Strip tags ```js '<p><b>Hi</b> there</p>'.removeTags(); // Hi there ``` ### str.padLeft(max, [c]) Type: `method` Pads the text on the left to a length. String.padRight() pads on the right. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `max` | `Number` | yes | | The length of the result. | | `c` | `String` | no | `' '` | The padding character. | Returns: `String` The padded text. Characters `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. Example: Pad ```js '5'.padLeft(3, '0'); // 005 'a'.padRight(3, '-'); // a-- ``` ### str.toASCII() Type: `method` Replaces letters with diacritics by their ASCII form. Returns: `String` The text without diacritics. Letters such as `č`, `á` or `ü` are replaced with `c`, `a` and `u`. Characters without an ASCII form stay as they are. Example: Remove diacritics ```js 'Čučoriedka'.toASCII(); // Cucoriedka ``` ### str.toKeywords([forsearch], [alternative], [max_count], [max_length], [min_length]) Type: `method` Extracts keywords from the text, the most frequent first. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `forsearch` | `Boolean` | no | `true` | Normalize the words for search. | | `alternative` | `Boolean` | no | `false` | Shorten words to 80 % of their length. | | `max_count` | `Number` | no | `200` | The maximum number of words to read. | | `max_length` | `Number` | no | `20` | The maximum length of a keyword. | | `min_length` | `Number` | no | `2` | The minimum length of a keyword. | Returns: `Array` Unique keywords sorted by frequency. The 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. For 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`). Example: Keywords for a search index ```js 'Total.js is a great framework, great!'.toKeywords(); // ['great', 'totaljs', 'is', 'framework'] 'Čaute Hello'.toSearch(); // caute helo ``` ### str.pluralize(zero, one, few, other) Type: `method` Converts the text to a number and picks a plural form. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `zero` | `String` | yes | | Text for 0, or all four forms separated by commas. | | `one` | `String` | no | | Text for 1. | | `few` | `String` | no | | Text for 2 to 4. | | `other` | `String` | no | | Text for other numbers. | Returns: `String` The chosen form. The text is converted with `parseInt()` and the result is passed to `Number.pluralize()`. Example: Pluralize a string ```js '3'.pluralize('no items', '# item', '# items', '# items'); // 3 items ``` ### str.parseInt([def]) Type: `method` Converts the text to a number, with a default for invalid text. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `def` | `Number` | no | `0` | The value for text that is not a number. | Returns: `Number` The number or the default. The 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). `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. Example: Read numbers ```js '10'.parseInt(); // 10 'abc'.parseInt(5); // 5 'Total: 123 EUR'.parseInt2(); // 123 'x 1,5 y'.parseFloat2(); // 1.5 ``` ### str.parseFloat([def]) Type: `method` Converts the text to a decimal number; a comma is accepted as the decimal separator. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `def` | `Number` | no | `0` | The value for text that is not a number. | Returns: `Number` The number or the default. The 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). Example: Read decimals ```js '1,5'.parseFloat(); // 1.5 ' 2.25 '.parseFloat(); // 2.25 'n/a'.parseFloat(-1); // -1 ``` ### str.parseBoolean() Type: `method` Converts the text to a boolean. Returns: `Boolean` Returns `true` for `true`, `1` and `on` (case-insensitive) and `false` for everything else. Example: Read a flag ```js 'on'.parseBoolean(); // true 'TRUE'.parseBoolean(); // true 'no'.parseBoolean(); // false ``` ### str.parseDate([format]) Type: `method` Converts the text to a Date. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `format` | `String` | no | | A format such as `dd/MM/yyyy HH:mm`. | Returns: `Date` The parsed date. Without `format` the method understands: - JSON dates (`2024-05-01T12:30:00.000Z`), - `yyyy-MM-dd`, `yyyy-MM-dd HH:mm`, `yyyy-MM-dd HH:mm:ss` and `yyyy-MM-ddTHH:mm:ss.SSS`, - `d.M.yyyy` with an optional time (`1.5.2024 08:00`), - anything else that `new Date(text)` accepts. The date and time of these forms are read as UTC. Missing parts of the date are taken from today. With `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. Example: Parse dates ```js '2024-05-01 12:30'.parseDate(); // 2024-05-01T12:30:00.000Z '1.5.2024'.parseDate(); // 2024-05-01T00:00:00.000Z '01/05/2024'.parseDate('dd/MM/yyyy'); // 1 May 2024 ``` ### str.parseDateExpiration() Type: `method` Converts a relative time such as "5 minutes" to a Date in the future. Returns: `Date` The current time plus the given duration. The 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. Example: Expiration ```js var expire = '5 minutes'.parseDateExpiration(); var later = '1 day 2 hours'.parseDateExpiration(); ``` ### str.parseJSON([date]) Type: `method` Parses JSON without throwing. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `date` | `Boolean` | no | `false` | Convert JSON date strings to Date objects. | Returns: `Object` The parsed value or `undefined`. Returns 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. Example: Safe parse ```js var obj = '{"a":1}'.parseJSON(); // { a: 1 } var bad = '{a:1'.parseJSON(); // undefined var doc = '{"created":"2024-01-01T10:00:00.000Z"}'.parseJSON(true); doc.created instanceof Date; // true ``` ### str.parseCSV([delimiter]) Type: `method` Parses CSV text into an array of objects with column keys a, b, c, ... | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `delimiter` | `String` | no | `','` | The column delimiter, one character. | Returns: `Array` An array of objects. Each 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. Example: Parse CSV ```js var rows = 'name,age\n"Sirka, Peter",40\nAnna,'.parseCSV(); // [{ a: 'name', b: 'age' }, { a: 'Sirka, Peter', b: '40' }, { a: 'Anna' }] var header = rows.shift(); for (var row of rows) console.log(row.a, row.b || '-'); ``` ### str.parseContext() Type: `method` · Since: `0.0.17` Parses a text made of blocks with a header and a body. Returns: `Array` An array of objects, one per block. Each 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. Example: Parse blocks ```js var text = [ '--------------------', 'Name: Hello', 'Type: note', '--------------------', 'Body one', '--------------------', 'Name: Second', '--------------------', 'Body two' ].join('\n'); text.parseContext(); // [{ name: 'Hello', type: 'note', body: 'Body one' }, { name: 'Second', body: 'Body two' }] ``` ### str.parseEncoded() Type: `method` Parses URL-encoded text (a query string or a form body) into an object. Returns: `Object` The parsed keys and values (strings). Pairs `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. Example: Parse a query string ```js 'q=total.js&page=2&name=%20Peter'.parseEncoded(); // { q: 'total.js', page: '2', name: ' Peter' } ``` ### str.parseConfig([def], [onerr]) Type: `method` Parses text in the Total.js configuration format into an object. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `def` | `Object` | no | | Default values copied into the result first. | | `onerr` | `Function` | no | | `function(err, line)` for values that cannot be evaluated. | Returns: `Object` The parsed values. Each 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. A 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. Example: Parse settings ```js var text = 'name : Shop\ncount (number) : 10\nenabled (boolean) : true\n# comment\ntags (array) : [\'a\', \'b\']'; text.parseConfig(); // { name: 'Shop', count: 10, enabled: true, tags: ['a', 'b'] } ``` ### str.parseEnv() Type: `method` Parses text in the .env format into an object. Returns: `Object` The keys and values. Each 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. Example: Parse .env ```js 'PORT=8000\nNAME="My app"\n# comment'.parseEnv(); // { PORT: '8000', NAME: 'My app' } ``` ### str.parseUA([structured]) Type: `method` Reads the operating system, browser and device type from a User-Agent header. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `structured` | `Boolean` | no | `false` | Return an object instead of text. | Returns: `String|Object` Without 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. Example: Read the user agent ```js var ua = 'Mozilla/5.0 (iPhone; CPU iPhone OS 17_0 like Mac OS X) Version/17.0 Mobile Safari/604.1'; ua.parseUA(); // iPhone Safari ua.parseUA(true); // { os: 'iPhone', browser: 'Safari', device: 'mobile' } ``` ### str.isEmail() Type: `method` Checks that the text is an e-mail address. Returns: `Boolean` The 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. Example: Validate ```js 'info@example.com'.isEmail(); // true 'info@example'.isEmail(); // false ``` ### str.isPhone() Type: `method` Checks that the text is a phone number. Returns: `Boolean` The 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. Example: Validate ```js '+421903123456'.isPhone(); // true '(123) 456-7890'.isPhone(); // true '12345'.isPhone(); // false ``` ### str.isURL() Type: `method` Checks that the text is an http or https URL. Returns: `Boolean` The text must start with `http://` or `https://` and must not contain `,`, `{`, `}` or `\`. Text of seven characters or less is never valid. Example: Validate ```js 'https://www.totaljs.com'.isURL(); // true 'www.totaljs.com'.isURL(); // false ``` ### str.isUID() Type: `method` Checks that the text is a valid identifier made by UID(). Returns: `Boolean` The 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()`. Example: Validate an id ```js var id = UID(); id.isUID(); // true 'abc'.isUID(); // false id.parseUID().date; // the time the id was created '123e4567-e89b-12d3-a456-426614174000'.isGUID(); // true ``` ### str.isNumber([isDecimal]) Type: `method` Checks that the text contains only digits. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `isDecimal` | `Boolean` | no | `false` | Allow one decimal separator. | Returns: `Boolean` Every 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. Example: Validate ```js '0123'.isNumber(); // true '1.5'.isNumber(); // false '1,5'.isNumber(true); // true ``` ### str.isJSON() Type: `method` Quickly checks that the text looks like a JSON object, array or string. Returns: `Boolean` Leading 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. Example: Check before parsing ```js var body = ' {"a":1} '; if (body.isJSON()) var obj = body.parseJSON(); ``` ### str.isXSS() Type: `method` Checks that the text contains an HTML tag. Returns: `Boolean` Returns `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. Example: Reject markup ```js '<script>alert(1)</script>'.isXSS(); // true 'Hello'.isXSS(); // false 'DROP TABLE users'.isSQLInjection(); // true ``` ### str.hash([type], [salt]) Type: `method` Returns a hash of the text: a fast number hash or an md5, sha1, sha256, sha512 or crc32 digest. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `type` | `String|Boolean` | no | | `md5`, `sha1`, `sha256`, `sha512`, `crc32`, `crc32unsigned`, or `true` for an unsigned number hash. | | `salt` | `String` | no | | Text appended before hashing. | Returns: `Number|String` A number for the number hash and crc32, a hex string otherwise. `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. Example: Hashes ```js 'hello'.hash(); // a signed 32-bit number 'hello'.hash(true); // the same, unsigned 'hello'.hash('sha256'); // hex digest 'hello'.hash('crc32unsigned'); ``` ### str.md5([salt]) Type: `method` Returns the MD5 digest of the text as a hex string. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `salt` | `String` | no | | Text appended before hashing. | Returns: `String` 32 hex characters. The text (with `salt` appended) is hashed as UTF-8 with Node.js `crypto`. MD5 is suitable for checksums and cache keys, not for passwords. Example: MD5 ```js 'a'.md5(); // 0cc175b9c0f1b6a831c399e269772661 ``` ### str.sha256([salt]) Type: `method` Returns the SHA-256 digest of the text as a hex string. sha1() and sha512() work the same. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `salt` | `String` | no | | Text appended before hashing. | Returns: `String` 64 hex characters. The 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. Example: SHA digests ```js var digest = 'password'.sha256(CONF.secret); var short = 'text'.sha1(); var long = 'text'.sha512(); ``` ### str.sign([key], [check]) Type: `method` Signs the text with a short checksum, or checks and removes the signature. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `key` | `String` | no | | The signing key. | | `check` | `Boolean` | no | `false` | Check the signature and return the original text. | Returns: `String` The signed text, the original text, or `null`. `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. `str.makeid()` returns only a short base-36 checksum of the text, handy as a compact key. Example: Sign an id ```js var token = '123'.sign('mykey'); // 123-155hlxd token.sign('mykey', true); // 123 (token + 'x').sign('mykey', true); // null ``` ### str.encrypt(key, [isUnique], [secret]) Type: `method` Encrypts the text with a key. String.decrypt() reverses it. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `key` | `String` | yes | | The encryption key. | | `isUnique` | `Boolean` | no | `false` | Make a different result for each call. | | `secret` | `String` | no | `CONF.secret` | The secret used in the checksum. | Returns: `String` The encrypted text. The 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. `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. Example: Encrypt and decrypt ```js var value = 'user@example.com'.encrypt('mykey', true); value.decrypt('mykey'); // user@example.com value.decrypt('other'); // null ``` ### str.encrypt_uid([key]) Type: `method` Encrypts an identifier into a short URL-safe token. String.decrypt_uid() reverses it. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `key` | `String` | no | `CONF.secret` | The key. | Returns: `String` The token. Use 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. Example: Hide an id ```js var token = '123'.encrypt_uid('mykey'); token.decrypt_uid('mykey'); // 123 ``` ### str.base64ToBuffer() Type: `method` Converts base64 text or a data URI to a Buffer. Returns: `Buffer` The decoded data. Everything 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). Example: Decode an upload ```js var uri = 'data:text/plain;base64,aGVsbG8='; uri.base64ToBuffer().toString(); // hello uri.base64ContentType(); // text/plain uri.parseDataURI().type; // text/plain uri.base64ToFile(PATH.temp('hello.txt')); ``` ### num.format([decimals], [separator], [separatorDecimal]) Type: `method` Formats a number with a thousands separator and a fixed number of decimals. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `decimals` | `Number` | no | | The number of decimals. | | `separator` | `String` | no | `' '` | The thousands separator. | | `separatorDecimal` | `String` | no | `'.'` | The decimal separator. | Returns: `String` The formatted number. The 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, '.')`. Example: Format ```js (1234567.891).format(2); // 1 234 567.89 (1234.5).format(2, ',', '.'); // 1,234.50 (1234.5).format('.', 2); // 1.234,50 (1.999).round(2).format(2); // 2.00 ``` ### num.pluralize(zero, one, few, other) Type: `method` Picks a plural form by the number; # is replaced with the number. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `zero` | `String` | yes | | Text for 0, or all four forms separated by commas. | | `one` | `String` | no | | Text for 1. | | `few` | `String` | no | | Text for 2 to 4. | | `other` | `String` | no | | Text for other numbers. | Returns: `String` The chosen form. The 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. Example: Plural forms ```js (1).pluralize('no items', '# item', '# items', '# items'); // 1 item (7).pluralize('no items,# item,# items,# items'); // 7 items ``` ### num.padLeft(max, [c]) Type: `method` Pads the number on the left with zeros. Number.padRight() pads on the right. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `max` | `Number` | yes | | The length of the result. | | `c` | `String` | no | `'0'` | The padding character. | Returns: `String` The padded number. The number is converted to a string and padded to `max` characters with `c` (`0` by default). `num.padRight(max, [c])` pads on the right. Example: Zero padding ```js (5).padLeft(3); // 005 (7).padLeft(4, ' '); // ' 7' (5).padRight(3); // 500 ``` ### num.round(precision) Type: `method` Rounds the number to a number of decimals. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `precision` | `Number` | yes | | The number of decimals. | Returns: `Number` The rounded number. Rounding 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`). Example: Round ```js (1.005).round(2); // 1.01 (2.5).round(0); // 3 (1.239).floor(2); // 1.23 ``` ### num.fixed(decimals) Type: `method` Rounds the number with toFixed() and returns a number, not a string. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `decimals` | `Number` | yes | | The number of decimals. | Returns: `Number` Example: Fixed ```js (1.236).fixed(2); // 1.24 (a number) ``` ### num.between(condition, [otherwise]) Type: `method` Returns the value of the first range that contains the number. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `condition` | `Object` | yes | | Ranges as keys, results as values. | | `otherwise` | `Any` | no | | The result when no range matches. | Returns: `Any` The value of the matching range or `otherwise`. `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. Example: Grade a score ```js var score = 5; score.between({ '0-3': 'low', '4-6': 'medium', '7-': 'high' }, 'unknown'); // medium ``` ### num.VAT(percentage, [decimals], [includedVAT]) Type: `method` Adds a tax to the number, or removes it from a price that includes it. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `percentage` | `Number` | yes | | The tax rate in percent. | | `decimals` | `Number` | no | `2` | The number of decimals. | | `includedVAT` | `Boolean` | no | `false` | The number already includes the tax. | Returns: `Number` `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)`. Example: Prices with VAT ```js (100).VAT(20); // 120 (120).VAT(20, true); // 100 (99.99).TAX(10, 0); // 110 ``` ### num.discount(percentage, [decimals]) Type: `method` Reduces the number by a percentage. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `percentage` | `Number` | yes | | The discount in percent. | | `decimals` | `Number` | no | `2` | The number of decimals. | Returns: `Number` The result is rounded down to `decimals` (2 by default). Example: Discount ```js (100).discount(15); // 85 (19.99).discount(10); // 17.99 ``` ### num.filesize([decimals], [type]) Type: `method` Formats a number of bytes as a human-readable size. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `decimals` | `Number` | no | | The number of decimals. | | `type` | `String` | no | | `bytes`, `KB`, `MB`, `GB` or `TB`. | Returns: `String` The size with its unit. Without `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. Example: File sizes ```js (500).filesize(); // 500 bytes (1536000).filesize(); // 1.46 MB (5000000).filesize(1, 'MB'); // 4.7 MB ``` ### num.currency([currency], [a], [b], [c]) Type: `method` Formats the number as an amount with a currency formatter registered in DEF.currencies. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `currency` | `String` | no | `'default'` | The key in `DEF.currencies`. | | `a, b, c` | `Any` | no | | Extra arguments for the formatter. | Returns: `String` The formatted amount. The 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. Example: Register and use a currency ```js // /definitions/currencies.js DEF.currencies.eur = function(val) { return val.format(2, ' ', ',') + ' €'; }; (1234.5).currency('eur'); // 1 234,50 € (10).currency('usd'); // 10.00 (no formatter) ``` ### date.add(type, [value]) Type: `method` Returns a new date shifted by an amount of time. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `type` | `String|Number` | yes | | The unit, a string with value and unit, or milliseconds. | | `value` | `Number` | no | | The amount, negative for the past. | Returns: `Date` A new date. The 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)`). Units: `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. Example: Shift dates ```js var now = new Date(); now.add('1 day'); now.add('minutes', 30); now.add('-2 hours'); now.add(5000); // + 5 seconds ``` ### date.diff([date], type) Type: `method` Returns the difference between two dates in seconds, minutes, hours or days. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `date` | `Date|String|Number` | no | `now` | The date to compare with. | | `type` | `String` | yes | | The unit of the result. | Returns: `Number` The difference in the unit. The 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`. Example: Differences ```js var created = new Date('2024-01-30T00:00:00Z'); var end = new Date('2024-01-31T10:00:00Z'); end.diff(created, 'hours'); // 34 end.diff('2024-01-01T00:00:00Z', 'days'); // 31 created.diff('seconds'); // negative: created is in the past ``` ### date.format([format], [resource]) Type: `method` Formats the date by a pattern; without a pattern returns an ISO string in UTC. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `format` | `String` | no | | The pattern. | | `resource` | `String` | no | | The resource used for month and day names. | Returns: `String` The formatted date. Without `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): - `yyyy`, `yy` year; `MM`, `M` month number; `MMMM` month name, `MMM` its first three letters, - `dd`, `d` day; `dddd` day name, `ddd` its first two letters in uppercase, - `HH`, `H` hours (0-23); `mm`, `m` minutes; `ss`, `s` seconds, - `ww`, `w` ISO week number; `a` `AM` or `PM`. Uppercase `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. Example: Format dates ```js var d = new Date('2024-01-31T10:00:00Z'); d.format(); // 2024-01-31T10:00:00.000Z d.format('yyyy-MM-dd HH:mm'); // 2024-01-31 10:00 d.format('dd.MM.yy'); // 31.01.24 d.format('dddd, d. MMMM yyyy'); // Wednesday, 31. January 2024 d.format('MMMM', 'sk'); // the month name from sk.resource ``` ### date.extend(text) Type: `method` Returns a new date with the date or time parts replaced from a text. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `text` | `String` | yes | | A date, a time, or both. | Returns: `Date` A new date. The 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. Example: Change parts ```js var d = new Date('2024-01-31T10:00:00Z'); d.extend('12:30'); // 2024-01-31T12:30:00.000Z d.extend('2025-03-04'); // 2025-03-04T10:00:00.000Z d.extend('1.3.2020 08:00'); // 2020-03-01T08:00:00.000Z ``` ### date.toUTC([ticks]) Type: `method` Shifts a local date by the time zone offset to UTC. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `ticks` | `Boolean` | no | `false` | Return milliseconds. | Returns: `Date|Number` The 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. Example: To UTC ```js var utc = new Date().toUTC(); var ms = new Date().toUTC(true); ``` ### date.setTimeZone(timezone) Type: `method` Returns a new date that shows the same moment in another time zone. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `timezone` | `String` | yes | | An IANA time zone name. | Returns: `Date` A new date. The 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`. Example: Show local time ```js var d = new Date('2024-01-31T10:00:00Z'); d.setTimeZone('Europe/Bratislava').format('HH:mm'); // 11:00 ``` ### arr.findItem(cb, [value]) Type: `method` Returns the first item that matches, or null. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `cb` | `Function|String|Any` | yes | | A test function, a property name or a value. | | `value` | `Any` | no | | The value of the property. | Returns: `Object` The item or `null`. Pass a function `(item, index)`, a property name and a value (`('id', 5)` compares `item.id === 5`), or a single value that is compared with `===`. Example: Find an item ```js var users = [{ id: 1, name: 'Peter' }, { id: 2, name: 'Anna' }]; users.findItem('id', 2); // { id: 2, name: 'Anna' } users.findItem(u => u.name === 'Peter'); // { id: 1, name: 'Peter' } users.findItem('id', 9); // null ``` ### arr.findAll(cb, [value]) Type: `method` Returns all items that match. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `cb` | `Function|String|Any` | yes | | A test function, a property name or a value. | | `value` | `Any` | no | | The value of the property. | Returns: `Array` The matching items. Pass 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. Example: Filter ```js var items = [{ type: 'a' }, { type: 'b' }, { type: 'a' }]; items.findAll('type', 'a').length; // 2 ``` ### arr.findIndex(cb, [value]) Type: `method` Returns the index of the first item that matches, or -1. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `cb` | `Function|String|Any` | yes | | A test function, a property name or a value. | | `value` | `Any` | no | | The value of the property. | Returns: `Number` The index or `-1`. Pass 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. Example: Index of an item ```js var users = [{ id: 1 }, { id: 2 }]; var index = users.findIndex('id', 2); // 1 if (index !== -1) users.splice(index, 1); ``` ### arr.findValue(cb, value, path, [def]) Type: `method` Finds an item and returns one of its properties. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `cb` | `Function|String` | yes | | A test function or a property name. | | `value` | `Any` | yes | | The value of the property (pass `undefined` with a function). | | `path` | `String` | yes | | The property to return. | | `def` | `Any` | no | | The default value. | Returns: `Any` The item is found like in `Array.findItem()`. The result is `item[path]`, or `def` when no item matches or the property is `null` / `undefined`. Example: Read a property ```js var users = [{ id: 1, name: 'Peter' }]; users.findValue('id', 1, 'name'); // Peter users.findValue('id', 9, 'name', 'guest'); // guest ``` ### arr.remove(cb, [value]) Type: `method` Returns a new array without the items that match. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `cb` | `Function|String|Any` | yes | | A test function, a property name or a value. | | `value` | `Any` | no | | The value of the property. | Returns: `Array` A new array without the matching items. Pass 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. Example: Remove items ```js var users = [{ id: 1 }, { id: 2 }, { id: 3 }]; users = users.remove('id', 1); // [{ id: 2 }, { id: 3 }] var nums = [1, 2, 3, 2].remove(2); // [1, 3] ``` ### arr.quicksort([sort], [desc]) Type: `method` Sorts the array in place by one or more properties. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `sort` | `String|Boolean` | no | | Properties to sort by, or `true` for descending plain values. | | `desc` | `Boolean` | no | `false` | Descending order for `sort`. | Returns: `Array` The same array, sorted. `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. Without `sort` the array of plain values is sorted ascending; `quicksort(true)` sorts it descending. The method returns the same array. Example: Sort objects ```js var products = [{ name: 'B', price: 10 }, { name: 'A', price: 20 }]; products.quicksort('name'); // A, B products.quicksort('price_desc'); // 20, 10 products.quicksort('name', true); // B, A [3, 1, 2].quicksort(); // [1, 2, 3] ``` ### arr.take(count) Type: `method` Returns the first count items as a new array. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `count` | `Number` | yes | | The number of items. | Returns: `Array` Example: Take ```js [1, 2, 3, 4].take(2); // [1, 2] ``` ### arr.skip(count) Type: `method` Returns the items after the first count items as a new array. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `count` | `Number` | yes | | The number of items to skip. | Returns: `Array` Combine with `take()` for paging. Example: Paging ```js var page = 2; var limit = 10; var items = all.skip((page - 1) * limit).take(limit); ``` ### arr.first([def]) Type: `method` Returns the first item, or a default for an empty array. Array.last() returns the last one. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `def` | `Any` | no | | The value for an empty array. | Returns: `Any` `arr.last([def])` returns the last item or `def`. Example: First and last ```js [1, 2].first(); // 1 [].first('none'); // none [1, 2].last(); // 2 ``` ### arr.group(name) Type: `method` Groups the items by a property. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `name` | `String` | yes | | The property to group by. | Returns: `Array` Groups `{ name, items }`. Returns 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. Example: Group ```js var items = [{ type: 'x', id: 1 }, { type: 'y', id: 2 }, { type: 'x', id: 3 }]; items.group('type'); // [{ name: 'x', items: [...2 items] }, { name: 'y', items: [...1 item] }] ``` ### arr.trim() Type: `method` Trims strings and returns a new array without empty values. Returns: `Array` Strings 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. Example: Clean a list ```js ' a , ,b'.split(',').trim(); // ['a', 'b'] ``` ### arr.random([item]) Type: `method` Shuffles the array in place, or returns one random item. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `item` | `Boolean` | no | `false` | Return one random item. | Returns: `Array|Any` Without 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. Example: Random ```js var colors = ['red', 'green', 'blue']; colors.random(true); // one color colors.random(); // the shuffled array ``` ### arr.wait(onItem, [callback], [thread]) Type: `method` Processes the items one by one with an asynchronous function. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `onItem` | `Function` | yes | | `function(item, next)`. | | `callback` | `Function` | no | | Called when all items are processed. | | `thread` | `Number|Boolean` | no | `1` | Parallel items, or `true` to remove items as they are processed. | Returns: `Array` The array. `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. Example: Process in sequence ```js var ids = [1, 2, 3]; ids.wait(function(id, next) { FUNC.removeuser(id, next); }, function() { console.log('All removed'); }); ``` Example: Two at a time ```js urls.wait(function(url, next) { REQUEST({ url: url, callback: () => next() }); }, () => console.log('done'), 2); ``` ### arr.async([thread], [callback]) Type: `method` Runs an array of functions one after another. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `thread` | `Number` | no | `1` | How many functions run at the same time. | | `callback` | `Function` | no | | Called at the end. | Returns: `Array` The array. Each 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')`. Example: Run tasks ```js var tasks = []; tasks.push(function(next) { console.log('first'); next(); }); tasks.push(function(next) { setTimeout(next, 100); }); tasks.async(function() { console.log('done'); }); ``` ### arr.limit(max, fn, [callback]) Type: `method` Processes the array in chunks of max items. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `max` | `Number` | yes | | The size of a chunk. | | `fn` | `Function` | yes | | `function(items, next, beg, end)`. | | `callback` | `Function` | no | | Called at the end. | Returns: `Array` The array. `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. Example: Insert in batches ```js rows.limit(100, function(items, next) { FUNC.importrows(items, next); }, function() { console.log('Imported'); }); ``` --- title: Images project: Total.js V5 version: 0.0.20 section: reference language: en license: MIT url: https://totaljs.es/docs/total-js-v5/0-0-20/reference/images/ updated: 2026-11-18T16:57:34.578Z --- # Images > The Image global and every method of image objects. The `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. ## API ### Image Type: `class` The global image module. `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`. Example: Resize a photo ```js Image.load(PATH.public('photo.jpg')).resize(800).save(PATH.public('photo-800.jpg')); ``` ### Image.load(source, [converter], [width], [height]) Type: `method` Creates an image object. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `source` | `String|Buffer|Stream` | yes | | A file name, a Buffer or a readable stream. | | `converter` | `String` | no | `CONF.$imageconverter` | The program: `gm`, `im` or `magick`. | | `width` | `Number` | no | | The known width, stored in `img.width`. | | `height` | `Number` | no | | The known height, stored in `img.height`. | Returns: `Image` A new image object. `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. Example: Load from a file and a buffer ```js var a = Image.load(PATH.public('photo.jpg')); var b = Image.load(buffer, 'magick'); ``` ### F.image(source, [converter], [width], [height]) Type: `method` The same function as `Image.load()`. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `source` | `String|Buffer|Stream` | yes | | A file name, a Buffer or a readable stream. | | `converter` | `String` | no | `CONF.$imageconverter` | The program: `gm`, `im` or `magick`. | | `width` | `Number` | no | | The known width. | | `height` | `Number` | no | | The known height. | Returns: `Image` A new image object. An alias of `Image.load()` on the framework object. Example: Load an image ```js F.image(filename).grayscale().save(target); ``` ### new Image.Image(source, [converter], [width], [height]) Type: `class` The constructor of image objects. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `source` | `String|Buffer|Stream` | yes | | A file name, a Buffer or a readable stream. | | `converter` | `String` | no | `CONF.$imageconverter` | The program: `gm`, `im` or `magick`. | | `width` | `Number` | no | | The known width. | | `height` | `Number` | no | | The known height. | `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`. Example: Add a method ```js Image.Image.prototype.avatar = function() { return this.resizecenter(128, 128).quality(90); }; Image.load(filename).avatar().save(target); ``` ### Image.measure(type, buffer) Type: `method` Reads the width and height from the header of an image. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `type` | `String` | yes | | An extension or a MIME type. | | `buffer` | `Buffer` | yes | | The beginning of the file. | Returns: `Object` `{ width, height }`, `null` for a JPEG without the size marker, `undefined` for an unsupported type. `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`. Example: Measure an uploaded buffer ```js var size = Image.measure('image/png', buffer); if (size && size.width > 2000) $.invalid('The image is too wide'); ``` ### Image.measureJPG(buffer) Type: `method` Reads the size of a JPEG image from a buffer. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `buffer` | `Buffer` | yes | | The beginning of the file. | Returns: `Object` `{ width, height }` or `null`. It 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. Example: Measure ```js var size = Image.measureJPG(buffer); console.log(size.width, size.height); ``` Example: A JPEG without the size ```js var buffer = Buffer.from([0xFF, 0xD8, 0xFF, 0xE0, 0x00, 0x10, 0x4A, 0x46, 0x49, 0x46, 0x00]); var size = Image.measureJPG(buffer); console.log(size); // null: no frame header in the buffer ``` ### Image.measurePNG(buffer) Type: `method` Reads the size of a PNG image from a buffer. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `buffer` | `Buffer` | yes | | The beginning of the file. | Returns: `Object` `{ width, height }`. It reads the IHDR header, so 24 bytes are enough. Example: Measure ```js var size = Image.measurePNG(buffer); console.log(size.width, size.height); ``` ### Image.measureGIF(buffer) Type: `method` Reads the size of a GIF image from a buffer. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `buffer` | `Buffer` | yes | | The beginning of the file. | Returns: `Object` `{ width, height }`. It reads the logical screen size, so 10 bytes are enough. Example: Measure ```js var size = Image.measureGIF(buffer); console.log(size.width, size.height); ``` ### Image.measureWEBP(buffer) Type: `method` Reads the size of a WebP image from a buffer. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `buffer` | `Buffer` | yes | | The beginning of the file. | Returns: `Object` `{ width, height }`. It reads the `VP8 `, `VP8L` and `VP8X` headers. Returns `undefined` for other data. Example: Measure ```js var size = Image.measureWEBP(buffer); console.log(size.width, size.height); ``` ### Image.measureSVG(buffer) Type: `method` Reads the size of a SVG image from a buffer. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `buffer` | `Buffer` | yes | | The beginning of the file. | Returns: `Object` `{ width, height }`. It reads the first `width="..."` and `height="..."` attributes with whole numbers. Returns `undefined` when there is none. Example: Measure ```js var size = Image.measureSVG(buffer); console.log(size.width, size.height); ``` ### Image.measureBMP(buffer) Type: `method` Reads the size of a BMP image from a buffer. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `buffer` | `Buffer` | yes | | The beginning of the file. | Returns: `Object` `{ width, height }`. It reads the BITMAPINFOHEADER. Example: Measure ```js var size = Image.measureBMP(buffer); console.log(size.width, size.height); ``` ### Image.measurePSD(buffer) Type: `method` Reads the size of a Photoshop (PSD) image from a buffer. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `buffer` | `Buffer` | yes | | The beginning of the file. | Returns: `Object` `{ width, height }`. It reads the PSD file header. Example: Measure ```js var size = Image.measurePSD(buffer); console.log(size.width, size.height); ``` ### Image.middleware(type, fn) Type: `method` Registers a stream that post-processes results of one type. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `type` | `String` | yes | | The image type, for example `png` or `.jpg`. | | `fn` | `Function` | yes | | Returns a Transform stream. | `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. Example: Pass PNG results through a stream ```js var Transform = require('stream').Transform; Image.middleware('png', function() { return new Transform({ transform: function(chunk, encoding, next) { next(null, chunk); } }); }); ``` ### img.width Type: `property` The width passed to `Image.load()`. Returns: `Number` The 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. Example: Known size ```js var img = Image.load(file.path, null, file.width, file.height); if (img.width > 1000) img.resize(1000); ``` ### img.filename Type: `property` The source file name. Returns: `String` The file name given to `Image.load()`, or `null` when the source is a Buffer or a stream. ### img.stream Type: `property` The source Buffer or stream. Returns: `Buffer|Stream` The 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. ### img.type Type: `property` The image type. Returns: `String` The 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. ### img.shell Type: `property` The program that processes the image. Returns: `String` `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. ### img.resize([w], [h], [options]) Type: `method` Resizes the image. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `w` | `Number|String` | no | | The width in pixels, or a percentage like `'50%'`. Empty to keep the ratio. | | `h` | `Number|String` | no | | The height in pixels, or a percentage. Empty to keep the ratio. | | `options` | `String` | no | | A suffix of the size: `!` ignores the ratio, `^` fills the box, `>` only shrinks, `<` only enlarges. | Returns: `Image` The same image object, for chaining. Adds `-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. Example: Resize ```js img.resize(800, 600); // into 800x600 img.resize(800); // width 800 img.resize(null, 600); // height 600 img.resize(200, 200, '!'); // exactly 200x200 img.resize('50%'); // half size ``` ### img.thumbnail([w], [h], [options]) Type: `method` Resizes the image for a small preview. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `w` | `Number|String` | no | | The width in pixels, or a percentage like `'50%'`. Empty to keep the ratio. | | `h` | `Number|String` | no | | The height in pixels, or a percentage. Empty to keep the ratio. | | `options` | `String` | no | | A suffix of the size: `!` ignores the ratio, `^` fills the box, `>` only shrinks, `<` only enlarges. | Returns: `Image` The same image object, for chaining. Adds `-thumbnail WxH`: a resize that also removes the profiles, so the file is smaller. The arguments are the same as in `resize()`. Example: Thumbnail ```js Image.load(filename).thumbnail(150, 150).save(target); ``` ### img.scale([w], [h], [options]) Type: `method` Resizes the image quickly without filtering. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `w` | `Number|String` | no | | The width in pixels, or a percentage like `'50%'`. Empty to keep the ratio. | | `h` | `Number|String` | no | | The height in pixels, or a percentage. Empty to keep the ratio. | | `options` | `String` | no | | A suffix of the size: `!` ignores the ratio, `^` fills the box, `>` only shrinks, `<` only enlarges. | Returns: `Image` The same image object, for chaining. Adds `-scale WxH`. Faster than `resize()` but with lower quality. The arguments are the same as in `resize()`. Example: Scale ```js img.scale(64, 64); ``` ### img.geometry([w], [h], [options]) Type: `method` Adds the `-geometry` option. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `w` | `Number|String` | no | | The width in pixels, or a percentage like `'50%'`. Empty to keep the ratio. | | `h` | `Number|String` | no | | The height in pixels, or a percentage. Empty to keep the ratio. | | `options` | `String` | no | | A suffix of the size: `!` ignores the ratio, `^` fills the box, `>` only shrinks, `<` only enlarges. | Returns: `Image` The same image object, for chaining. Adds `-geometry WxH` with the optional suffix. The program uses it as the preferred size and offset. Example: Geometry ```js img.geometry(300, 200, '!'); ``` ### img.crop(w, h, [x], [y]) Type: `method` Cuts an area of the image. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `w` | `Number` | yes | | The width of the area. | | `h` | `Number` | yes | | The height of the area. | | `x` | `Number` | no | `0` | The horizontal offset. | | `y` | `Number` | no | `0` | The vertical offset. | Returns: `Image` The same image object, for chaining. Adds `-crop WxH+X+Y`. The offset is measured from the corner set by `align()` (top left by default). Example: Crop ```js img.crop(400, 300, 50, 20); // The centre img.align('center').crop(400, 300); ``` ### img.extent([w], [h], [x], [y]) Type: `method` Sets the size of the canvas. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `w` | `Number` | no | | The width of the canvas. | | `h` | `Number` | no | | The height of the canvas. | | `x` | `Number` | no | | The horizontal offset, can be negative. | | `y` | `Number` | no | | The vertical offset, can be negative. | Returns: `Image` The same image object, for chaining. Adds `-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()`. Example: Square canvas ```js img.resize(500, 500).background('white').align('center').extent(500, 500); ``` ### img.miniature(w, h, [color], [filter]) Type: `method` Fits the image into a box and fills the rest. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `w` | `Number` | yes | | The width. | | `h` | `Number` | yes | | The height. | | `color` | `String` | no | `'white'` | The color of the free area. | | `filter` | `String` | no | `'Hamming'` | The resize filter. | Returns: `Image` The same image object, for chaining. A 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()`. Example: Product photo ```js Image.load(filename).miniature(300, 300, '#F0F0F0').save(target); ``` ### img.resizecenter(w, h, [color]) Type: `method` Fills a box and crops the centre. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `w` | `Number` | yes | | The width. | | `h` | `Number` | yes | | The height. | | `color` | `String` | no | `'white'` | The background color. | Returns: `Image` The same image object, for chaining. A shortcut for `resize(w, h, '^').background(color).align('center').crop(w, h)`. The result is `w`x`h` and the image covers it completely. Example: Cover ```js Image.load(filename).resizecenter(1200, 630).save(target); ``` ### img.resizealign(w, h, [align], [color]) Type: `method` Fills a box and crops at a side. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `w` | `Number` | yes | | The width. | | `h` | `Number` | yes | | The height. | | `align` | `String` | no | `'center'` | Where to crop: `top`, `bottom`, `left`, `center`… | | `color` | `String` | no | `'white'` | The background color. | Returns: `Image` The same image object, for chaining. A shortcut for `resize(w, h, '^').background(color).align(align).crop(w, h)`. `align` takes the values of `align()`. Example: Avatar ```js Image.load(filename).resizealign(200, 200, 'top').save(target); ``` ### img.align(type) Type: `method` Sets the gravity for crop and extent. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `type` | `String` | yes | | The position. | Returns: `Image` The same image object, for chaining. Adds `-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'`. Example: Align ```js img.align('bottom right').crop(400, 300); ``` ### img.gravity(type) Type: `method` The same method as `align()`. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `type` | `String` | yes | | The position. | Returns: `Image` The same image object, for chaining. An alias of `align()`. Example: Gravity ```js img.gravity('NorthWest'); ``` ### img.quality([percentage]) Type: `method` Sets the compression quality. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `percentage` | `Number` | no | `80` | The quality. | Returns: `Image` The same image object, for chaining. Adds `-quality`. For JPEG and WebP it is the quality from 1 to 100; an empty value means 80. Example: Quality ```js img.quality(70); ``` ### img.rotate([deg]) Type: `method` Rotates the image. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `deg` | `Number` | no | `0` | The angle in degrees. | Returns: `Image` The same image object, for chaining. Adds `-rotate`. The angle is in degrees clockwise. For angles other than multiples of 90 the corners are filled with the background color. Example: Rotate ```js img.background('white').rotate(45); ``` ### img.flip() Type: `method` Mirrors the image vertically. Returns: `Image` The same image object, for chaining. Adds `-flip` (top to bottom). Example: Flip ```js img.flip(); ``` ### img.flop() Type: `method` Mirrors the image horizontally. Returns: `Image` The same image object, for chaining. Adds `-flop` (left to right). Example: Flop ```js img.flop(); ``` ### img.blur(radius) Type: `method` Blurs the image. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `radius` | `Number|String` | yes | | The radius or `radiusxsigma`. | Returns: `Image` The same image object, for chaining. Adds `-blur`. The value is the radius, or `radiusxsigma` as a string (`'0x8'`). Example: Blur ```js img.blur(5); img.blur('0x8'); ``` ### img.grayscale() Type: `method` Converts the image to gray. Returns: `Image` The same image object, for chaining. Adds `-colorspace Gray`. Example: Gray ```js img.grayscale(); ``` ### img.sepia() Type: `method` Gives the image a sepia tone. Returns: `Image` The same image object, for chaining. Adds `-modulate 115,0,100 -colorize 7,21,50`. Example: Sepia ```js img.sepia(); ``` ### img.normalize() Type: `method` Stretches the contrast. Returns: `Image` The same image object, for chaining. Adds `-normalize`: the colors are spread over the full range. Example: Normalize ```js img.normalize(); ``` ### img.colors(value) Type: `method` Reduces the number of colors. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `value` | `Number` | yes | | The maximum number of colors. | Returns: `Image` The same image object, for chaining. Adds `-colors`. Example: Palette ```js img.output('png').colors(64); ``` ### img.bitdepth(value) Type: `method` Sets the bit depth. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `value` | `Number` | yes | | Bits per channel, for example 8. | Returns: `Image` The same image object, for chaining. Adds `-depth`. Example: Depth ```js img.bitdepth(8); ``` ### img.background(color) Type: `method` Sets the background color. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `color` | `String` | yes | | The color. | Returns: `Image` The same image object, for chaining. Adds `-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. Example: Background ```js img.background('#FFFFFF').extent(800, 800); ``` ### img.fill(color) Type: `method` Sets the fill color. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `color` | `String` | yes | | The color. | Returns: `Image` The same image object, for chaining. Adds `-fill`. Used by operations that draw, for example `-colorize` or your own `command()` options. Example: Fill ```js img.fill('red').command('-colorize', '30'); ``` ### img.filter(type) Type: `method` Sets the resize filter. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `type` | `String` | yes | | The filter name. | Returns: `Image` The same image object, for chaining. Adds `-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()`. Example: Filter ```js img.resize(400).filter('Lanczos'); ``` Example: The command ```js Image.load('photo.jpg').filter('Lanczos').resize(200, 200).cmd('photo.jpg', 'small.jpg'); // gm convert 'photo.jpg' -filter 'Lanczos' -resize '200x200' 'small.jpg' ``` ### img.define(value) Type: `method` Passes a coder option. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `value` | `String` | yes | | The definition `format:key=value`. | Returns: `Image` The same image object, for chaining. Adds `-define`, for example `'jpeg:extent=200kb'` or `'png:compression-level=9'`. Example: Define ```js img.define('jpeg:extent=200kb'); ``` ### img.minify() Type: `method` Removes the profiles and metadata. Returns: `Image` The same image object, for chaining. Adds `+profile '*'`, which removes EXIF, ICC and other profiles. `save()`, `pipe()` and `writer()` call it when the image has no operations. Example: Strip metadata ```js Image.load(filename).minify().save(target); ``` ### img.limit(type, value) Type: `method` Limits a resource of the program. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `type` | `String` | yes | | The resource. | | `value` | `Number|String` | yes | | The limit, for example `256MB`. | Returns: `Image` The same image object, for chaining. Adds `-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. Example: Limit memory ```js img.limit('memory', '256MB').limit('map', '512MB'); ``` ### img.watermark(filename, [x], [y], [w], [h]) Type: `method` Draws another image over the picture. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `filename` | `String` | yes | | The file of the watermark. | | `x` | `Number` | no | `0` | The horizontal offset. | | `y` | `Number` | no | `0` | The vertical offset. | | `w` | `Number` | no | `0` | The width of the watermark. | | `h` | `Number` | no | `0` | The height of the watermark. | Returns: `Image` The same image object, for chaining. Adds `-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. Example: Logo in the corner ```js Image.load(filename) .watermark(PATH.public('img/logo.png'), 20, 20, 120, 40) .save(target); ``` ### img.command(key, [value], [priority], [escape]) Type: `method` Adds any option of the program. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `key` | `String` | yes | | The option, for example `-sharpen`. | | `value` | `String|Number` | no | | The value. | | `priority` | `Number|Boolean` | no | `10` | The position, or `true` to quote the value. | | `escape` | `Boolean` | no | `false` | Quote the value. | Returns: `Image` The same image object, for chaining. Adds `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). Example: Custom options ```js img.command('-sharpen', '0x1'); img.command('-strip'); img.command('-label', 'My photo', true); ``` ### img.make(fn) Type: `method` Applies a function to the image. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `fn` | `Function` | yes | | Gets the image. | Returns: `Image` The same image object, for chaining. Calls `fn(img)` with `this` set to the image. Use it to reuse a set of operations. Example: Preset ```js function avatar(img) { img.resizecenter(128, 128).quality(90); } Image.load(filename).make(avatar).save(target); ``` ### img.clear() Type: `method` Removes all operations. Returns: `Image` The same image object, for chaining. Empties the list of operations. `save()` calls it after the program finishes. Example: Clear ```js img.clear().resize(100); ``` ### img.output(type) Type: `method` Sets the image type. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `type` | `String` | yes | | The type, for example `png` or `.webp`. | Returns: `Image` The same image object, for chaining. Sets `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. Example: Buffer to PNG ```js Image.load(buffer).output('png').resize(100).pipe($.res); ``` ### img.save([filename], [callback]) Type: `method` Runs the program and writes the result to a file. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `filename` | `String` | no | `img.filename` | The target file. | | `callback` | `Function` | no | | `function(err, success)`. | Returns: `Image` The same image object, for chaining. Builds 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. Example: Save ```js Image.load(file.path).resize(1024).quality(80).save(PATH.public('photos/' + id + '.jpg'), function(err) { if (err) $.invalid(err); else $.success(); }); ``` ### img.pipe(stream, [type], [options]) Type: `method` Runs the program and sends the result to a stream. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `stream` | `Stream` | yes | | A writable stream, for example `$.res`. | | `type` | `String` | no | `img.type` | The output format. | | `options` | `Object` | no | | Options of `stream.pipe()`. | Returns: `Image` The same image object, for chaining. Writes 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`. Example: Send to the response ```js function preview($) { $.res.writeHead(200, { 'content-type': 'image/png' }); Image.load(PATH.public('photo.jpg')).resize(300).pipe($.res, 'png'); } ``` ### img.writer([type]) Type: `method` Runs the program and returns the output stream. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `type` | `String` | no | `img.type` | The output format. | Returns: `Stream` A readable stream with the result. Starts 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()`. Example: Collect into a Buffer ```js var chunks = []; var stream = Image.load(buffer).resize(100, 100).writer('webp'); stream.on('data', chunk => chunks.push(chunk)); stream.on('end', function() { var output = Buffer.concat(chunks); }); ``` ### img.measure(callback) Type: `method` Reads the size of the source file. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `callback` | `Function` | yes | | `function(err, size)`. | Returns: `Image` The same image object, for chaining. Reads 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. Example: Measure a file ```js Image.load(PATH.public('photo.jpg')).measure(function(err, size) { console.log(size.width, size.height); }); ``` ### img.cmd(from, to) Type: `method` Returns the command line without running it. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `from` | `String` | yes | | The source file or `-`. | | `to` | `String` | yes | | The target file or `-`. | Returns: `String` The command line. Builds 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. Example: Show the command ```js var img = Image.load('photo.jpg').resize(200, 100); console.log(img.cmd('photo.jpg', 'small.jpg')); // gm convert 'photo.jpg' -resize '200x100' 'small.jpg' ``` --- title: AI models project: Total.js V5 version: 0.0.20 section: reference language: en license: MIT url: https://totaljs.es/docs/total-js-v5/0-0-20/reference/ai-models/ updated: 2026-11-18T16:57:34.578Z --- # AI models > NEWAIMODEL(), AIMODEL(), the request methods and properties, and the AI stream parser. This 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. ## API ### NEWAIMODEL(name, [config], handler) Type: `method` · Since: `0.0.16` Registers a handler for one or more AI models. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `name` | `String` | yes | | The model name, or several names separated by commas. | | `config` | `Object` | no | | Default config (URL, token, settings) copied into `ai.config` of each request. | | `handler` | `Function` | yes | | `function(ai, callback)`. Calls the provider and ends with `callback(err, response)`. | Returns: `undefined` Stores `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. Example: Ollama model ```js NEWAIMODEL('llama3', { url: 'http://localhost:11434/api/chat' }, function(ai, callback) { var opt = {}; opt.method = 'POST'; opt.headers = { 'Content-Type': 'application/json' }; opt.body = JSON.stringify({ model: ai.payload.model, messages: ai.payload.messages, stream: false }); fetch(ai.config.url, opt).then(res => res.json()).then(function(json) { callback(null, json.message.content); }).catch(callback); }); ``` ### function(ai, callback) Type: `delegate` · Since: `0.0.16` The model handler passed to NEWAIMODEL(). | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `ai` | `AIModel` | yes | | The request. | | `callback` | `Function` | yes | | `function(err, response)` that ends the request. | Called 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. Example: Echo handler for tests ```js NEWAIMODEL('echo', function(ai, callback) { var last = ai.payload.messages[ai.payload.messages.length - 1]; ai.options.stream && ai.options.stream(last.content); callback(null, last.content); }); ``` ### AIMODEL(name) Type: `method` · Since: `0.0.16` Creates a request for a registered AI model. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `name` | `String` | yes | | The name used in `NEWAIMODEL()`. It is also stored as `payload.model`. | Returns: `AIModel` A new request. Returns 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.'`. Example: Simple question ```js AIMODEL('assistant').user('What is 2 + 2?').callback(function(err, response) { console.log(response); }); ``` ### ai.system(content, [merge]) Type: `method` · Since: `0.0.16` Adds a system message. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `content` | `String|Object` | yes | | The text, or an object whose keys are copied into the message. | | `merge` | `String` | no | | A separator. When set and a system message exists, the content is appended to it. | Returns: `AIModel` The same request, for chaining. The same as `ai.message('system', content, merge)`. Use it for the instructions of the model. Example: Instructions ```js AIMODEL('assistant').system('Answer in one sentence.').user('What is Node.js?').callback(console.log); ``` ### ai.user(content, [merge]) Type: `method` · Since: `0.0.16` Adds a user message. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `content` | `String|Object` | yes | | The text, or an object whose keys are copied into the message. | | `merge` | `String` | no | | A separator. When set and a user message exists, the content is appended to it. | Returns: `AIModel` The same request, for chaining. The same as `ai.message('user', content, merge)`. Example: Message with an image ```js AIMODEL('vision').user({ content: 'What is in this picture?', images: [base64] }).callback(console.log); ``` ### ai.assistant(content, [merge]) Type: `method` · Since: `0.0.16` Adds an assistant message. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `content` | `String|Object` | yes | | The text, or an object whose keys are copied into the message. | | `merge` | `String` | no | | A separator. When set and an assistant message exists, the content is appended to it. | Returns: `AIModel` The same request, for chaining. The same as `ai.message('assistant', content, merge)`. Use it to replay earlier answers of the model in a conversation. Example: Conversation history ```js var ai = AIMODEL('assistant'); for (var item of history) { if (item.fromuser) ai.user(item.text); else ai.assistant(item.text); } ai.user(question).callback(console.log); ``` ### ai.message(role, content, [merge]) Type: `method` · Since: `0.0.16` Adds a message with any role. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `role` | `String` | yes | | The role, e.g. `system`, `user`, `assistant` or `tool`. | | `content` | `String|Object` | yes | | The text, or an object whose keys are copied into the message. | | `merge` | `String` | no | | A separator string that turns on merging. | Returns: `AIModel` The same request, for chaining. Pushes `{ 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. Example: Merged instructions ```js AIMODEL('assistant') .message('system', 'You are a translator.') .message('system', 'Translate to German.', '\n') .user('Good morning') .callback(console.log); ``` ### ai.prompt(content) Type: `method` · Since: `0.0.16` Sets a single prompt. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `content` | `String` | yes | | The prompt. | Returns: `AIModel` The same request, for chaining. Sets `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. Example: Prompt ```js AIMODEL('generator').prompt('Write a slogan for a bakery').callback(console.log); ``` ### ai.think() Type: `method` · Since: `0.0.16` Asks for the thinking mode. Returns: `AIModel` The same request, for chaining. Sets `ai.payload.think = true`. The handler maps it to the option of the provider (for example `think` of Ollama). Example: Thinking ```js AIMODEL('reasoner').think().user('Is 1001 a prime number?').callback(console.log); ``` ### ai.configure(obj) Type: `method` · Since: `0.0.16` Sets the config of the request. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `obj` | `Object` | yes | | The keys to set. | Returns: `AIModel` The same request, for chaining. Copies the keys of `obj` into `ai.config`. These values win over the defaults of `NEWAIMODEL()`, which fill only the keys that are not set. Example: Temperature for one request ```js AIMODEL('assistant').configure({ temperature: 0 }).user('List three colors').callback(console.log); ``` ### ai.callback(fn) Type: `method` · Since: `0.0.16` Sets the callback and runs the request. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `fn` | `Function` | yes | | `function(err, response)`. | Returns: `AIModel` The same request, for chaining. Stores `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. Example: Callback ```js AIMODEL('assistant').user('Hello').callback(function(err, response) { err && console.log(err); }); ``` ### ai.stream(fn) Type: `method` · Since: `0.0.16` Sets the stream function and runs the request. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `fn` | `Function` | yes | | Called by the handler with each piece of the answer. | Returns: `AIModel` The same request, for chaining. Stores `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. Example: Stream to the console ```js AIMODEL('assistant').user('Tell a story').stream(function(text) { process.stdout.write(text); }).callback(function(err) { console.log('end', err); }); ``` ### ai.promise([$]) Type: `method` · Since: `0.0.16` Runs the request and returns a Promise. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `$` | `Object` | no | | The `$` of an action or controller, to report errors with `$.invalid()`. | Returns: `Promise` Resolves with the response of the handler. Runs 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. Example: In an action ```js NEWACTION('Assistant/ask', { input: '*question:String', action: async function($, model) { var answer = await AIMODEL('assistant').user(model.question).promise($); $.callback({ answer: answer }); } }); ``` ### ai.payload {Object} Type: `property` · Since: `0.0.16` The data of the request for the provider. Returns: `Object` Holds `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. Example: Read the payload ```js NEWAIMODEL('debug', function(ai, callback) { callback(null, JSON.stringify(ai.payload)); }); ``` ### ai.config {Object} Type: `property` · Since: `0.0.16` The config of the request. Returns: `Object` The keys set with `ai.configure()`, completed with the defaults of `NEWAIMODEL()` just before the handler runs. ### ai.options {Object} Type: `property` · Since: `0.0.16` The run options of the request. Returns: `Object` Holds `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. Example: Check for streaming ```js if (ai.options.stream) body.stream = true; ``` ### F.aimodels {Object} Type: `property` · Since: `0.0.16` The registered AI models. Returns: `Object` An object with the names of the models as keys and `{ config, callback }` as values, filled by `NEWAIMODEL()`. Example: Is a model registered? ```js if (F.aimodels.assistant) console.log('ready'); ``` ### ai.tool(content) Type: `method` · Since: `0.0.17` Adds a tool definition. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `content` | `Object` | yes | | The tool definition. | Returns: `AIModel` The same request, for chaining. Pushes `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. Example: Tool from a schema ```js NEWSCHEMA('@Task', '*name:String // The name of the task,due:Date'); AIMODEL('assistant') .user('Create a task: call Peter tomorrow') .tool(F.jsonschemas.Task.toAITool('create_task')) .callback(console.log); ``` ### AIPARSER(provider) Type: `method` · Since: `0.0.17` Creates a parser for streamed AI responses. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `provider` | `String` | no | `generic` | The format of the stream. | Returns: `AIParser` A new parser. Returns 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()`. Example: Parse a Claude stream ```js var parser = AIPARSER('claude'); parser.on('content', e => process.stdout.write(e.delta)); for await (var chunk of res.body) parser.write(Buffer.from(chunk)); var output = parser.end(); ``` ### parser.write(chunk) Type: `method` · Since: `0.0.17` Writes a piece of the stream. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `chunk` | `Buffer|String|Object` | yes | | Raw data or a parsed event. | Returns: `Object` The current output, the same as `parser.output()`. A `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. Example: Write parsed objects ```js var parser = AIPARSER('ollama'); parser.write({ message: { content: 'Hel' } }); parser.write({ message: { content: 'lo' } }); parser.end().content; // 'Hello' ``` ### parser.end() Type: `method` · Since: `0.0.17` Finishes the stream. Returns: `Object` `{ content, thinking, tools, reasoning }`, plus `thinking_signature` or `thought_signatures` when the provider sends them. Parses 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. Example: Final output ```js var output = parser.end(); console.log(output.content); ``` Example: Tool calls of a Claude stream ```js var parser = AIPARSER('claude'); parser.on('tool_arguments', function(e) { console.log(e.tool.name, e.delta); }); // recorded events of an Anthropic Messages stream parser.write({ type: 'content_block_start', index: 1, content_block: { type: 'tool_use', id: 'toolu_1', name: 'weather', input: {} } }); parser.write({ type: 'content_block_delta', index: 1, delta: { type: 'input_json_delta', partial_json: '{"city": "Bra' } }); parser.write({ type: 'content_block_delta', index: 1, delta: { type: 'input_json_delta', partial_json: 'tislava"}' } }); parser.write({ type: 'message_delta', delta: { stop_reason: 'tool_use' } }); var output = parser.end(); // output.tools: [{ id: 'toolu_1', name: 'weather', arguments: { city: 'Bratislava' } }] ``` ### parser.output() Type: `method` · Since: `0.0.17` Returns the current output. Returns: `Object` The output so far. Returns `{ 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. ### parser.on(type, fn) Type: `method` · Since: `0.0.17` Listens to an event of the parser. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `type` | `String` | yes | | The event name. | | `fn` | `Function` | yes | | `function(event)`. | Returns: `AIParser` The parser, for chaining. Adds `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. Example: All events ```js AIPARSER('openai').on('*', function(e) { console.log(e.type); }); ``` ### parser.off(type, fn) Type: `method` · Since: `0.0.17` Removes a listener. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `type` | `String` | yes | | The event name. | | `fn` | `Function` | yes | | The function given to `parser.on()`. | Returns: `AIParser` The parser, for chaining. Removes `fn` from the listeners of `type`. ### parser.reset() Type: `method` · Since: `0.0.17` Clears the parser. Returns: `AIParser` The parser. Clears 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. ### parser.content {String} Type: `property` · Since: `0.0.17` The text collected so far. Returns: `String` All text of the answer, joined from the deltas. ### parser.thinking {String} Type: `property` · Since: `0.0.17` The reasoning collected so far. Returns: `String` All reasoning or thinking text sent by the model (for example `reasoning_content`, Claude `thinking_delta` or Gemini thought parts). ### parser.reasoning {String} Type: `property` · Since: `0.0.17` What the model is producing now. Returns: `String` `content`, `thinking` or `tool`, by the last kind of data received. ### parser.tools {Array} Type: `property` The tool calls collected so far. Returns: `Array` One 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. Example: Raw and parsed arguments ```js var parser = AIPARSER('ollama'); parser.write({ message: { role: 'assistant', content: '', tool_calls: [{ function: { name: 'weather', arguments: { city: 'Bratislava' } } }] } }); console.log(parser.tools[0].name); // 'weather' console.log(parser.tools[0].arguments); // '{"city":"Bratislava"}' console.log(parser.end().tools[0].arguments); // { city: 'Bratislava' } ``` ### parser.on('content', function(e) {}) Type: `event` · Since: `0.0.17` New text of the answer. `e.delta` is the new text and `e.content` all text so far. ### parser.on('thinking', function(e) {}) Type: `event` · Since: `0.0.17` New reasoning text. `e.delta` is the new text and `e.thinking` all reasoning so far. ### parser.on('tool_start', function(e) {}) Type: `event` A new tool call appears. `e.tool` is `{ id, name, arguments }` of the new call; `arguments` is usually `{}` at this point. `e.reasoning` is `tool`. Example: Log the calls ```js var parser = AIPARSER('openai'); parser.on('tool_start', function(e) { console.log('The model calls', e.tool.name, e.tool.id); }); ``` ### parser.on('tool_update', function(e) {}) Type: `event` More data of a known tool call. Emitted 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. Example: Watch the arguments grow ```js var parser = AIPARSER('openai'); parser.on('tool_update', function(e) { console.log(e.tool.id, e.tool.arguments); }); ``` ### parser.on('tool_arguments', function(e) {}) Type: `event` A piece of the arguments of a tool call. `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. Example: Arguments of a Claude stream ```js var parser = AIPARSER('claude'); parser.on('tool_arguments', function(e) { console.log(e.tool.name, e.delta); }); // recorded events of an Anthropic Messages stream parser.write({ type: 'content_block_start', index: 1, content_block: { type: 'tool_use', id: 'toolu_1', name: 'weather', input: {} } }); parser.write({ type: 'content_block_delta', index: 1, delta: { type: 'input_json_delta', partial_json: '{"city": "Bra' } }); parser.write({ type: 'content_block_delta', index: 1, delta: { type: 'input_json_delta', partial_json: 'tislava"}' } }); parser.write({ type: 'message_delta', delta: { stop_reason: 'tool_use' } }); var output = parser.end(); // output.tools: [{ id: 'toolu_1', name: 'weather', arguments: { city: 'Bratislava' } }] ``` ### parser.on('done', function(e) {}) Type: `event` · Since: `0.0.17` The stream ended. Emitted by `parser.end()`. `e.output` is the final output. --- title: Proxy project: Total.js V5 version: 0.0.20 section: reference language: en license: MIT url: https://totaljs.es/docs/total-js-v5/0-0-20/reference/proxy/ updated: 2026-11-18T16:57:34.578Z --- # Proxy > PROXYSERVER() and PROXYCLIENT(). ## API ### PROXYSERVER([endpoint], [socketendpoint], [logger]) Type: `method` · Since: `0.0.17` Forwards HTTP requests to a proxy client connected over a WebSocket. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `endpoint` | `String` | no | `'/'` | Path prefix of the requests to forward. | | `socketendpoint` | `String` | no | `'/'` | Path of the WebSocket route for the client. | | `logger` | `Function` | no | `console with a date` | Called as `logger(status, message)` when the client connects or disconnects. | Registers `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. Only 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`. Example: Public server ```js exports.install = function() { PROXYSERVER('/', '/$proxy/'); }; ``` ### PROXYCLIENT(proxyserver, target, [logger]) Type: `method` · Since: `0.0.17` Connects a local HTTP server to a `PROXYSERVER()` and answers its requests. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `proxyserver` | `String` | yes | | URL of the WebSocket endpoint of `PROXYSERVER()`. | | `target` | `String` | yes | | Local server as `'ip:port'` or `'port'`. | | `logger` | `Function` | no | `console with a date` | Called with the status and a message on connect, disconnect and each request. | Returns: `WebSocketClient` The client connection. Opens 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. `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. Example: Publish a local app ```js PROXYCLIENT('https://public.example.com/$proxy/', '8000'); ``` Example: Quiet ```js PROXYCLIENT('https://public.example.com/$proxy/', '192.168.1.10:8000', NOOP); ``` --- title: LDAP project: Total.js V5 version: 0.0.20 section: reference language: en license: MIT url: https://totaljs.es/docs/total-js-v5/0-0-20/reference/ldap/ updated: 2026-11-18T16:57:34.578Z --- # LDAP > LDAP() and its options. ## API ### LDAP(options, [callback]) Type: `method` Searches an LDAP server (Active Directory) and returns users or groups. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `options` | `Object` | yes | | The connection and the search, see below. | | `callback` | `Function` | no | | `function(err, response)`. Without it the function returns a promise. | Returns: `Promise` With the response when no callback is given. Binds 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. | Option | Description | | --- | --- | | `ldap` | `{ host, port, secure, timeout }`. `port` defaults to `389`; `secure: true` connects with TLS; `timeout` limits the connection in ms | | `user`, `password` | Credentials for the bind (a DN or, for Active Directory, also `user@domain`) | | `dn` | Base DN of the search | | `type` | `objectClass` to search for, such as `person` or `group`; `profile` searches one person by `login` | | `login` | The `sAMAccountName` for `type: 'profile'` | | `noauth` | `true` skips the bind | | `attributes` | How to read attributes: `{ thumbnailPhoto: 'buffer' }`. Types: `string`, `number`, `date`, `buffer`, `binary` (also a buffer), `hex`, `base64`, `ascii`, `utf8`, in lower case | The 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`. When 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. Example: Groups ```js var groups = await LDAP({ ldap: { host: 'ad.example.com' }, user: 'reader@example.com', password: CONF.ldap_password, dn: 'OU=Groups,DC=example,DC=com', type: 'group' }); ``` Example: One account ```js LDAP({ 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) { profile && console.log(profile.mail); }); ``` --- title: Markdown project: Total.js V5 version: 0.0.20 section: reference language: en license: MIT url: https://totaljs.es/docs/total-js-v5/0-0-20/reference/markdown/ updated: 2026-11-18T16:57:24.576Z --- # Markdown > String.prototype.markdown() and the Markdown syntax. ## API ### String.prototype.markdown([options], [nested]) Type: `method` Converts a Markdown string to HTML. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `options` | `Object` | no | `{}` | Options, see the table. | | `nested` | `Boolean` | no | `false` | Leaves out the `markdown-container` class. | Returns: `String` HTML. Every option is on by default; set it to `false` to skip that syntax. | Option | Description | | --- | --- | | `wrap` | Wraps the output in `<div class="markdown markdown-container">` | | `linetag` | Tag of paragraphs, default `'p'`; an empty string gives plain lines | | `bookmarks` | Adds an `id` made from the text to headings | | `prefix` | Text before the `id` of headings | | `headlines`, `ul`, `tables`, `code`, `blockquotes`, `sections`, `hr`, `blocks` | Block syntax | | `formatting`, `links`, `images`, `icons`, `keywords`, `footnotes`, `urlify`, `br` | Inline syntax (`urlify` turns plain URLs into links, `br` keeps `<br>`) | | `emptynewline` | Two empty lines give `<br />` | | `custom` | `function(line)` that changes each line before it is parsed | | `html` | `function(text, type)` that changes the text of a block; `type` is `'#'`…`'#####'`, `'li'`, `'blockquote'`, `'section'`, `'block'` or the line tag | `<` 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`. Example: Article ```js var html = article.body.markdown(); ``` Example: Plain fragment ```js '**Note:** see [docs](https://docs.totaljs.com)'.markdown({ wrap: false, linetag: '' }); // '<strong>Note:</strong> see <a href="https://docs.totaljs.com" target="_blank">docs</a>' ``` ### Markdown syntax Type: `type` Markdown supported by `String.prototype.markdown()`, with the Total.js extensions. | Syntax | Result | | --- | --- | | `# Title` … `##### Title` | `<h1>` … `<h5>` with an `id` | | `**text**`, `*text*` | `<strong>`, `<em>` | | `__text__`, `_text_`, `~~text~~` | `<b>`, `<u>`, `<strike>` | | `` `code` `` and ```` ```js ```` blocks | `<code>`, `<pre><code class="lang-js">` | | `- item`, `* item`, `+ item`, `1. item`, `a. item` | Lists; a tab nests them; `[ ]` and `[x]` make tasks | | `\| a \| b \|` with a `\|---\|--:\|` line | A table with `left`, `right` or `center` columns | | `> text` | `<blockquote>` | | `< text` | `<section>` | | `---`, `***` | `<hr>` | | `[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 | | `![+alt](url)`, `![-alt](url)` | An image without `img-responsive`, a gallery image | | `:check:`, `:ti ti-user:` | Icons | | `{text}(type)` | `<span class="markdown-keyword" data-type="type">` | | `[1](#1)` and `#1: text` | A footnote and its body | | `::: Title` … `:::` | An expandable block | --- title: HTML and XML parser project: Total.js V5 version: 0.0.20 section: reference language: en license: MIT url: https://totaljs.es/docs/total-js-v5/0-0-20/reference/html-parser/ updated: 2026-11-19T16:17:02.153Z --- # HTML and XML parser > String.prototype.parseHTML(), HTMLElement and the methods of an element. ## API ### String.prototype.parseHTML([trim]) Type: `method` Parses HTML into a tree of elements. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `trim` | `Boolean` | no | `false` | Trims text nodes. | Returns: `HTMLElement` The root element. Returns 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. `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()`. Example: Read links ```js var dom = html.parseHTML(); var links = dom.find('a').map(function(a) { return { url: a.attr('href'), text: a.text() }; }); ``` Example: XML ```js var xml = body.parseXML2(); var items = xml.find('*:item'); // any prefix ``` ### HTMLElement Type: `class` An element (or a text node) of a tree from `parseHTML()`. | Property | Description | | --- | --- | | `tagName` | Tag name in upper case, `TEXT` for a text node | | `raw` | Tag name as written | | `prefix` | XML prefix with the colon, such as `SOAP:` | | `attrs` | Attributes as an object | | `children` | Child nodes | | `parentNode` | Parent element | | `textContent` | Text of a `TEXT` node | | `innerHTML`, `outerHTML`, `innerText` | Getters for `html()`, the element with its tag, and `text()` | Example: Walk ```js var dom = '<ul><li>A</li><li>B</li></ul>'.parseHTML(); var ul = dom.children[0]; ul.tagName; // 'UL' ul.children.length; // 2 ul.outerHTML; // '<ul><li>A</li><li>B</li></ul>' ``` ### element.find(selector) Type: `method` Finds elements below this element. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `selector` | `String` | yes | | CSS-like selector. | Returns: `Array` Found elements. Supports 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. The result is an array with the methods `aclass()`, `rclass()`, `tclass()`, `attr()`, `attrd()`, `find()`, `html()` (same as `toString()`) and `text()`, applied to all found elements. Example: Find ```js dom.find('table.data > tr td').text(); dom.find('a').attr('rel', 'nofollow'); ``` Example: Elements with an attribute ```js var dom = html.parseHTML(); var images = dom.find('img[alt]'); // images with an alt text var ids = dom.find('[data-id]'); ``` ### element.parent() Type: `method` Returns the parent element. Returns: `HTMLElement` The parent. The same as `element.parentNode`. Example: Parent ```js var td = dom.find('td.price')[0]; var row = td.parent(); ``` ### element.browse(fn, [reverse]) Type: `method` Calls a function for every node below this one. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `fn` | `Function` | yes | | `function(node)`; `true` skips the children. | | `reverse` | `Boolean` | no | `false` | Walks the parents. | Returns: `HTMLElement` This element. `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. Example: Collect ```js var tags = {}; dom.browse(function(el) { tags[el.tagName] = (tags[el.tagName] || 0) + 1; }); ``` ### element.attr(name, [value]) Type: `method` Reads or sets an attribute. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `name` | `String` | yes | | Attribute name. | | `value` | `Object` | no | | New value. | Returns: `String` The value when reading, otherwise the element. Without `value` it returns the attribute. An empty value or `null` removes it; other values are stored as strings. Example: Attributes ```js var href = a.attr('href'); a.attr('rel', 'nofollow'); a.attr('target', null); ``` ### element.attrd(name, [value]) Type: `method` Reads or sets a `data-` attribute. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `name` | `String` | yes | | Name without `data-`. | | `value` | `Object` | no | | New value. | Returns: `String` The value when reading, otherwise the element. `attrd('id')` is `attr('data-id')`. Example: Data ```js el.attrd('id', 123); el.attrd('id'); // '123' ``` ### element.aclass(cls) Type: `method` Adds classes. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `cls` | `String` | yes | | Class names. | Returns: `HTMLElement` This element. Several classes are separated by spaces or commas. Example: Add ```js el.aclass('active selected'); ``` ### element.rclass(cls) Type: `method` Removes classes. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `cls` | `String` | yes | | Class names. | Returns: `HTMLElement` This element. Several classes are separated by spaces or commas. Example: Remove ```js el.rclass('hidden'); ``` ### element.tclass(cls, [value]) Type: `method` Toggles classes. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `cls` | `String` | yes | | Class names. | | `value` | `Boolean` | no | | Force add or remove. | Returns: `HTMLElement` This element. Without `value` each class is switched; `true` adds and `false` removes. Example: Toggle ```js el.tclass('active', item.id === current); ``` ### element.hclass(cls) Type: `method` Tests a class. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `cls` | `String` | yes | | One class name. | Returns: `Boolean` Returns `true` when the element has the class. Example: Test ```js if (el.hclass('price')) console.log(el.text()); ``` ### element.css(key, [value]) Type: `method` Sets inline styles. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `key` | `String|Object` | yes | | Property or object. | | `value` | `String` | no | | Value; empty removes. | Returns: `HTMLElement` This element. Accepts a property and a value, or an object of properties. An empty value removes the property from the `style` attribute. Example: Styles ```js el.css('color', 'red'); el.css({ width: '100px', display: '' }); ``` ### element.remove() Type: `method` Removes the element from its parent. Returns: `HTMLElement` The removed element. Example: Remove scripts ```js dom.find('script').forEach(function(el) { el.remove(); }); ``` ### element.append(html) Type: `method` Parses HTML and adds it at the end of the children. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `html` | `String` | yes | | HTML to add. | Returns: `HTMLElement` The new element or elements. Returns the new element, or an array when the HTML has more top-level nodes. Example: Append ```js ul.append('<li>New</li>'); ``` ### element.prepend(html) Type: `method` Parses HTML and adds it at the beginning of the children. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `html` | `String` | yes | | HTML to add. | Returns: `HTMLElement` The parsed root. Returns the parsed root of the new HTML. Example: Prepend ```js body.prepend('<p>Notice</p>'); ``` ### element.text() Type: `method` Returns the text of the element. Returns: `String` Text. Text nodes are joined and decoded; text of block elements (`div`, `p`, headings, lists, tables...) is separated by new lines. Example: Text ```js '<p>Hello <b>world</b></p>'.parseHTML().text(); // 'Hello world' ``` ### element.html([formatted]) Type: `method` Returns the inner HTML. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `formatted` | `Boolean` | no | `false` | Indents the output. | Returns: `String` HTML. `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. Example: Serialize ```js var html = dom.html(); var pretty = dom.html(true); ``` --- title: Macros project: Total.js V5 version: 0.0.20 section: reference language: en license: MIT url: https://totaljs.es/docs/total-js-v5/0-0-20/reference/macros/ updated: 2026-11-18T16:56:54.572Z --- # Macros > NEWMACRO() and the macro syntax. ## API ### NEWMACRO(code, [nocompile], [isasync]) Type: `method` Compiles a macro into a function `fn(model, helpers)`. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `code` | `String` | yes | | The macro, one command per line (or separated by `;`). | | `nocompile` | `Boolean` | no | `false` | Returns the JavaScript code instead of a function. | | `isasync` | `Boolean` | no | `false` | Makes an async function. | Returns: `Function` `function(model, [helpers])`, or a string with `nocompile`. The 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. Example: Shipping ```js var shipping = NEWMACRO('IF weight > 10\n\tRETURN 15\nELSE IF weight > 2\n\tRETURN 8\nFI\nRETURN 4'); shipping({ weight: 5 }); // 8 ``` Example: Async helpers ```js var fn = NEWMACRO('RETURN rate(currency) * price', false, true); var value = await fn({ price: 10, currency: 'EUR' }, { rate: async function(code) { return 1.1; } }); ``` ### Macro syntax Type: `type` Commands and values of `NEWMACRO()`. | Syntax | Meaning | | --- | --- | | `IF condition` … `ELSE IF condition` … `ELSE` … `FI` | Conditions; `FI` closes them | | `RETURN expression` | Returns a value | | `AND`, `OR` | `&&`, `\|\|` | | `==`, `!=`, `>`, `>=`, `<`, `<=`, `+`, `-`, `*`, `/` | Operators as in JavaScript | | `price`, `order.total` | Properties of the model, read in lower case | | `#name` | A temporary variable: `#total = price * count` | | `name(a, b)` | A helper call | | `"text"`, `'text'` | Text; a quoted number becomes a number | | `TRUE`, `FALSE`, `YES`, `NO`, `NULL` | Values | | `// text` | A comment line | Keywords can be in any case. Example: Rule ```js IF total >= 100 AND customer.vip == YES RETURN total * 0.9 FI RETURN total ``` --- title: Tangular project: Total.js V5 version: 0.0.20 section: reference language: en license: MIT url: https://totaljs.es/docs/total-js-v5/0-0-20/reference/tangular/ updated: 2026-11-18T16:56:54.572Z --- # Tangular > Tangular.compile(), Tangular.render(), Tangular.register() and Tangular.helpers. ## API ### Tangular.compile(template, [tagbeg], [tagend]) Type: `method` Compiles a Tangular template into a function. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `template` | `String` | yes | | The template. | | `tagbeg` | `String` | no | `'{{'` | Start of a command. | | `tagend` | `String` | no | `'}}'` | End of a command. | Returns: `Function` `function(model, [repository], [helpers])`. The 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). Example: Compile once ```js var row = Tangular.compile('<tr><td>{{ name }}</td><td>{{ price | format(2) }}</td></tr>'); var html = items.map(item => row(item)).join(''); ``` Example: Local helpers ```js var t = Tangular.compile('{{ name | badge }}'); t({ name: 'New' }, null, { badge: function(value) { return '<span class="badge">' + value + '</span>'; } }); ``` ### Tangular.render(template, [model], [repository], [helpers]) Type: `method` Compiles and renders a template in one call. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `template` | `String` | yes | | The template. | | `model` | `Object` | no | `{}` | The model. | | `repository` | `Object` | no | | Available as `$`. | | `helpers` | `Object` | no | | Helpers for this call. | Returns: `String` The output. Use `Tangular.compile()` for templates that you render often. Example: Render ```js Tangular.render('Hello {{ name }}!', { name: 'Peter' }); // 'Hello Peter!' ``` ### Tangular.register(name, fn) Type: `method` Adds a helper for all Tangular templates. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `name` | `String` | yes | | Helper name. | | `fn` | `Function` | yes | | `function(value, [args...])`. | Returns: `Object` Tangular, for chaining. The 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. Example: Helper ```js Tangular.register('money', function(value, currency) { return value.format(2) + ' ' + (currency || 'EUR'); }); ``` ### Tangular.helpers Type: `property` Built-in helpers of Tangular, also available as the global `Thelpers`. Returns: `Object` | Helper | Description | | --- | --- | | `encode([type])` | HTML-encodes; used for every value without `raw`. Types: `json`, `json2`, `url`, `querify` | | `raw` | The value without encoding | | `format([format], ...)` | Formats a number or a date (strings are detected) | | `currency([code])` | Formats a number with a formatter from `DEF.currencies[code]` (or `DEF.currencies.default`); without one it uses two decimals | | `pluralize(zero, one, few, other)` | Chooses a word by a number | | `empty([text])`, `def([text])` | The value, or `text` (default `---`) when it is empty | Example: Usage ```js Tangular.render('{{ count | pluralize(\'no items\', \'# item\', \'# items\', \'# items\') }}', { count: 3 }); ``` --- title: Minification project: Total.js V5 version: 0.0.20 section: reference language: en license: MIT url: https://totaljs.es/docs/total-js-v5/0-0-20/reference/minification/ updated: 2026-11-18T16:57:24.576Z --- # Minification > U.minify_css(), U.minify_js() and U.minify_html(). ## API ### U.minify_css(css) Type: `method` Minifies CSS and compiles nested rules and `$variables`. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `css` | `String` | yes | | CSS source. | Returns: `String` Minified CSS. Removes 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. Example: Nested rules ```js U.minify_css('.menu {\n\t.item { color: red; }\n\t.active { font-weight: bold; }\n}'); // '.menu .item{color:red}.menu .active{font-weight:bold}' ``` Example: Variables ```js U.minify_css('$brand: #0066FF;\n.button { background: $brand; }'); // '.button{background:#0066FF}' ``` ### U.minify_js(js) Type: `method` Minifies JavaScript. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `js` | `String` | yes | | JavaScript source. | Returns: `String` Minified code. Removes comments, line breaks and unneeded whitespace. Strings are kept as they are. It does not rename variables. Example: Minify ```js U.minify_js('if (a) {\n\tconsole.log(a); // log\n}'); // 'if(a){console.log(a);}' ``` ### U.minify_html(html) Type: `method` Minifies HTML. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `html` | `String` | yes | | HTML source. | Returns: `String` Minified HTML. Removes 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. Example: Minify ```js var html = U.minify_html(source); ``` --- title: CMS compiler project: Total.js V5 version: 0.0.20 section: reference language: en license: MIT url: https://totaljs.es/docs/total-js-v5/0-0-20/reference/cms/ updated: 2026-11-19T16:17:02.153Z --- # CMS compiler > F.TCMS.compile(), the methods of a compiled page, F.TCMS.widgets() and F.TCMS.run(). ## API ### F.TCMS.compile(html, widgets, [used]) Type: `method` Compiles a page of the Total.js CMS into a render object. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `html` | `String` | yes | | HTML of the page. | | `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`. | | `used` | `Boolean` | no | `false` | Joins CSS and JS only of the widgets used on the page. | Returns: `CMSRender` Compiled page with `render()`, `importcss()`, `importjs()`, `importmeta()`, `css`, `js` and `widgets`. Finds 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. The 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. Example: Compile ```js var page = F.TCMS.compile(item.html, MAIN.widgets, true); page.importcss().importjs(); ``` ### cmsrender.render(meta, [layout], [callback]) Type: `method` Renders a compiled CMS page. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `meta` | `Object` | yes | | Data for the widgets and templates, see the table. | | `layout` | `CMSRender` | no | | A compiled layout page. | | `callback` | `Function` | no | | `function(err, html)`. Without it a promise is returned. | Returns: `Promise` With the HTML when no callback is given. Calls `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`. The 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). | `meta` key | Description | | --- | --- | | `url` | URL of the request | | `navigation` | `function(id)` that returns the value of a navigation template | | `breadcrumb` | Array for the breadcrumb template | | `widgets` | Widgets that override the `render` of the compiled ones | | `body` | Content for the `id="CMS"` element of a layout | | `inlinecache` | Object that stores the rendered navigations and breadcrumbs | With `layout` (another compiled page) the output goes into `meta.body` and the layout is rendered. Example: In a route ```js async function page($) { var html = await MAIN.page.render({ url: $.url, controller: $, navigation: id => MAIN.navigations[id] }); $.html(html); } ``` ### cmsrender.importcss([html]) Type: `method` Inserts CSS before `</head>`. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `html` | `String` | no | `'<style>' + page.css + '</style>'` | HTML to insert. | Returns: `CMSRender` The page. Without 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. Example: Link a file ```js page.importcss('<link rel="stylesheet" href="/css/page.css">'); ``` ### cmsrender.importjs([html]) Type: `method` Inserts JavaScript before `</body>`. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `html` | `String` | no | `'<script>' + page.js + '</script>'` | HTML to insert. | Returns: `CMSRender` The page. Without 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. Example: Inline ```js page.importjs(); ``` ### cmsrender.importmeta(html) Type: `method` Inserts HTML before `</head>`. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `html` | `String` | yes | | HTML to insert. | Returns: `CMSRender` The page. For meta tags, a title or other head content. Nothing happens when the page has no `</head>`. Example: Meta ```js page.importmeta('<meta name="description" content="' + item.description.encode() + '">'); ``` ### F.TCMS.widgets(html) Type: `method` Lists the widgets used in a CMS page. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `html` | `String` | yes | | HTML of the page. | Returns: `Array` Widget elements. Returns 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. Example: Used widgets ```js var ids = F.TCMS.widgets(item.html).map(w => w.id); ``` ### F.TCMS.run(html) Type: `method` Creates a widget from its HTML source. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `html` | `String` | yes | | Widget source. | Returns: `Object` The widget. A 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()`. Example: Load widgets ```js var widgets = sources.map(source => F.TCMS.run(source)); var page = F.TCMS.compile(html, widgets); ``` --- title: Application structure and modes project: Total.js V5 version: 0.0.20 section: reference language: en license: MIT url: https://totaljs.es/docs/total-js-v5/0-0-20/reference/application-structure/ updated: 2026-11-18T16:57:34.578Z --- # Application structure and modes > F.run() and its start options, LOAD(), IMPORT(), REQUIRE(), MODS and the framework statistics. The 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. The guide [Application structure and modes](../../guides/application-structure/) explains the folders, the loading order, debug and release mode, bundles and remote editing. The `Test` runner has its own page: [Unit tests](../unit-tests/). ## API ### F.run([options]) Type: `method` Starts the application in debug mode with the watcher, or in release mode. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `options` | `Object` | no | `{}` | The start options: `ip`, `port`, `unixsocket`, `config`, `load`, `watcher`, `release`, `servicemode`, `watch`, `livereload`, `inspector`, `debugger`, `cluster`, `limit`, `edit`, `editmcp`. | Returns: `undefined` The 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. Example: Debug mode ```js require('total5'); F.run({ port: 8000 }); ``` Example: Release mode ```js require('total5'); F.run({ watcher: false, port: 8000 }); ``` Example: Mode from the command line ```js require('total5'); var options = {}; options.port = 8000; if (process.argv.includes('--release')) options.watcher = false; F.run(options); ``` ### F.http([options]) Type: `method` Loads the application and starts the HTTP server in the current process. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `options` | `Object` | no | `{}` | `ip`, `port`, `unixsocket`, `unixsocket777`, `config`, `load` (alias `type`) and `clear`. | Returns: `undefined` Applies `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. `F.run()` calls it for you; call it directly in scripts that start the server without a watcher (tests, tools). Example: Server for tests ```js require('total5'); F.http({ port: 8001, config: { name: 'Test' } }); ``` ### LOAD([types], [callback], [clear]) Type: `method` Loads the configuration, the resources and the JavaScript files of the application. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `types` | `String|Array` | no | `''` | The parts to load, as a comma-separated string or an array; empty loads everything. | | `callback` | `Function` | no | | `function()` called when everything is loaded. | | `clear` | `Boolean` | no | `true` | Clears the temporary folder before loading. | Returns: `Promise` Resolves when everything is loaded. `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. At 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. Example: Background process ```js require('total5'); LOAD('config,modules,actions', function() { ACTION('Jobs/run').callback(console.log); }); ``` Example: With await ```js require('total5'); (async function() { await LOAD('env,config'); console.log(CONF.name); })(); ``` ### IMPORT(url, [callback]) Type: `method` Downloads a JavaScript file and loads it as a module. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `url` | `String` | yes | | URL of a `.js` file. | | `callback` | `Function` | no | | `function(err, module, response)` | Returns: `Promise` When `callback` is not set. The 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. Example: Promise ```js var helpers = await IMPORT('https://cdn.example.com/helpers.js'); helpers.hello(); ``` Example: Callback ```js IMPORT('https://cdn.example.com/helpers.js', function(err, helpers) { if (err) console.error(err); else helpers.hello(); }); ``` ### REQUIRE(name) Type: `method` Loads a Node.js module or an NPM package. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `name` | `String` | yes | | The name of the module or package. | Returns: `Object` The module. Names 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. Example: Load ```js var Fs = REQUIRE('fs'); var mqtt = REQUIRE('mqtt'); ``` ### MODS Type: `property` The loaded modules from the `modules` folder, by their id. Returns: `Object` The 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. Example: Call a module ```js // modules/counter.js exports.id = 'counter'; var count = 0; exports.increment = function() { return ++count; }; // a controller or an action MODS.counter.increment(); ``` ### F.isLoaded Type: `property` `true` when the application is loaded. Returns: `Boolean` Set by `LOAD()` after all files are loaded, just before the `ready` and `load` events. Example: Check ```js if (F.isLoaded) console.log('Ready'); ``` ### F.directory Type: `property` The root folder of the application. Returns: `String` The 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. Example: Read ```js console.log(F.directory); console.log(PATH.root('config')); ``` ### F.isBundle Type: `property` `true` when the application runs from bundles. Returns: `Boolean` Set when the `bundles` folder contains bundles (or `bundles.debug` exists) and the application was built into `.src`. Example: Check ```js if (F.isBundle) console.log('Running from', F.directory); ``` ### F.dir([directory]) Type: `method` Sets the root folder and recomputes the folders of the application. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `directory` | `String` | no | | A new root folder. | Returns: `undefined` With `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. Example: Read a folder ```js F.dir(); console.log(F.temporary.directories.public); ``` ### F.restart() Type: `method` Asks the watcher to restart the application. Returns: `undefined` Sends `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. Example: After an update ```js NEWACTION('Settings/save', { input: '*name:String', action: function($, model) { F.Fs.writeFile(PATH.root('config'), 'name : ' + model.name, function() { $.success(); F.restart(); }); } }); ``` ### F.exit([signal]) Type: `method` Stops the application. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `signal` | `Number` | no | `15` | The signal for the child processes. | Returns: `undefined` Kills 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. Example: Stop ```js ON('exit', function() { console.log('Bye'); }); F.exit(); ``` ### F.console() Type: `method` Prints the start information. Returns: `undefined` Prints 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. Example: Print it again ```js ON('ready', function() { F.console(); }); ``` ### F.remote(url, [directory]) Type: `method` Connects the folder of the application to the Total.js Code Editor. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `url` | `String` | yes | | The URL from the editor, `wss://...?id=project`. | | `directory` | `String` | no | `F.directory` | The folder to edit. | Returns: `undefined` Starts 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. Example: Connect ```js F.remote('wss://code.example.com/?id=myproject'); ``` ### F.consumption Type: `property` The usage statistics of the process, updated once a minute. Returns: `Object` The 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`. Example: Read ```js setInterval(function() { console.log(F.consumption.memory, 'MB', F.consumption.requests, 'requests'); }, 60000); ``` ### F.stats Type: `property` Counters of the framework for the whole life of the process. Returns: `Object` `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. Example: Simple report ```js ROUTE('GET /stats/', function($) { var s = F.stats; $.json({ requests: s.request.request, errors: s.error, notfound: s.response.error404 }); }); ``` ### ON('$watcher', function(child) {}) Type: `event` Emitted in the debug watcher after it starts the application process. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `child` | `ChildProcess` | yes | | The process of the application. | It 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()`. Example: Log restarts ```js require('total5'); ON('$watcher', function(child) { console.log('Application PID:', child.pid); }); F.run(); ``` ### ON('watcher', function(child) {}) Type: `event` Emitted in the release watcher after it starts the application process. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `child` | `ChildProcess` | yes | | The process of the application. | Release mode started with `--watcher` only. It runs in the watcher process after each start. `child` is the `ChildProcess` of the application. Example: Log starts ```js require('total5'); ON('watcher', function(child) { console.log('Started PID:', child.pid); }); F.run({ watcher: false }); ``` ### options.ip = String Type: `property` The IP address the server listens on. Returns: `String` Default: `CONF.$ip` (`0.0.0.0`) Stored into `CONF.$ip`. The default `0.0.0.0` listens on all interfaces. Example: Local only ```js F.run({ ip: '127.0.0.1', port: 8000 }); ``` ### options.port = Number Type: `property` The port of the server. Returns: `Number` Default: `8000` Stored 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`. Example: Port from the arguments ```js F.run({ port: parseInt(process.argv[2]) || 8000 }); ``` ### options.unixsocket = String Type: `property` Listens on a Unix socket instead of a port. Returns: `String` An existing socket file is removed first. On Windows the path is placed into the named pipe space. Stored into `CONF.$unixsocket`. Example: Socket ```js F.run({ unixsocket: require('node:path').join(require('node:os').tmpdir(), 'app_name') }); ``` ### options.unixsocket777 = Boolean Type: `property` Gives the Unix socket the permissions 777. Returns: `Boolean` Default: `false` With `unixsocket`, the socket file gets `chmod 777` when it is created, so another user (for example the web server) can connect to it. Example: Socket for nginx ```js F.run({ unixsocket: '/tmp/app.socket', unixsocket777: true }); ``` ### options.config = Object Type: `property` Configuration keys applied before the application is loaded. Returns: `Object` Every 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`. Example: Name and bundling ```js F.run({ config: { name: 'My app', bundling: 'shallow' } }); ``` ### options.load = String Type: `property` The parts of the application that are loaded. Returns: `String` Default: `''` Passed to `LOAD()`: a comma-separated list such as `'config,controllers'`. Empty loads everything; `'none'` starts only the web server. `options.type` is an alias. Example: Static file server ```js F.http({ load: 'none', port: 8000 }); ``` ### options.watcher = Boolean Type: `property` `false` starts release mode. Returns: `Boolean` Default: `true` With `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. Example: Release ```js F.run({ watcher: false }); ``` ### options.release = Boolean Type: `property` Runs the application with `DEBUG = false` under the debug watcher or the cluster. Returns: `Boolean` Default: `false` In 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. Example: Release cluster ```js F.run({ cluster: 4, release: true }); ``` ### options.servicemode = Boolean|String Type: `property` Loads the application without the HTTP server. Returns: `Boolean|String` `true` loads everything, a string loads the listed parts (the names of `LOAD()`), for example `'config,modules,actions'`. Example: Worker process ```js F.run({ servicemode: 'config,modules,actions' }); ``` ### options.watch = Array Type: `property` More folders for the debug watcher. Returns: `Array` Paths relative to the root of the application. A leading and a trailing slash are removed. Example: Watch a folder ```js F.run({ watch: ['adminer', '/libs/'] }); ``` ### options.livereload = String Type: `property` Sends changed files to the Total.js live reload service. Returns: `String` The 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. Example: Live reload ```js F.run({ livereload: 'myapp.example.com' }); ``` ### options.inspector = Number Type: `property` Starts the application process with the Node.js inspector. Returns: `Number` Default: `9229` The 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`. Example: Inspector ```js F.run({ inspector: 9229 }); ``` ### options.debugger = Number Type: `property` Starts the application process with `--debug=<port>`. Returns: `Number` Default: `40894` The 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`. Example: Debugger ```js F.run({ debugger: 40894 }); ``` ### options.cluster = Number|String Type: `property` Runs the application in several cluster threads. Returns: `Number|String` A 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. Example: Four threads ```js F.run({ cluster: 4, port: 8000 }); ``` Example: Automatic ```js F.run({ cluster: 'auto', limit: 8, release: true }); ``` ### options.limit = Number Type: `property` The maximum number of threads for `cluster: 'auto'`. Returns: `Number` Without it, the automatic cluster adds threads without a limit. Example: Limit ```js F.run({ cluster: 'auto', limit: 4 }); ``` ### options.edit = String Type: `property` Connects the application to the Total.js Code Editor. Returns: `String` The 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. Example: Remote editing ```js F.run({ edit: 'wss://code.example.com/?id=myproject' }); ``` ### options.editmcp = String Type: `property` Connects the application to an MCP edit proxy, so an AI agent can work on its files. Returns: `String` The 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. The 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`. Example: The application ```js F.run({ editmcp: 'wss://proxy.example.com/$mcp/?id=myproject' }); ``` Example: The proxy ```js // config: $mcp : true const editmcp = require('total5/edit-mcp'); ROUTE('SOCKET /$mcp/', function($) { editmcp.proxy($); }); Total.mcp.auth = function($) { if ($.token === CONF.mcp_token) $.success({ id: 'agent', name: 'Agent', sa: true }); else $.invalid(); }; // the AI client connects to https://proxy.example.com/$mcp/?id=myproject ``` ### bundling : shallow Type: `config` `shallow` reuses the extracted `.src` folder instead of building it again. Returns: `String` When 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`. Example: Shallow bundling ```js F.run({ watcher: false, config: { bundling: 'shallow' } }); ``` --- title: Unit tests project: Total.js V5 version: 0.0.20 section: reference language: en license: MIT url: https://totaljs.es/docs/total-js-v5/0-0-20/reference/unit-tests/ updated: 2026-11-18T16:57:34.578Z --- # Unit tests > The Test runner of total5/test: Test.push(), Test.run(), Test.print(), Test.start(), Test.fake(), Test.restore(), Test.count and Test.items. The `Test` runner from `total5/test`. The guide [Unit tests](../../guides/unit-tests/) explains how to use it with examples. ## API ### Test Type: `class` The global test runner created by `require('total5/test')`. Returns: `Object` Loads `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/)). Example: Load ```js require('total5/test'); Test.push('Numbers', function(next) { Test.print('sum', 1 + 1 === 2 ? null : 'Wrong sum'); next(); }); Test.run(); ``` ### Test.push(name, fn) Type: `method` Adds a group of tests. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `name` | `String` | yes | | The name printed as the header of the group. | | `fn` | `Function` | yes | | `function(next)` | Returns: `undefined` The groups run in the order they were added. `fn` gets `next` and must call it when the group is done, also after asynchronous checks. Example: Async group ```js Test.push('Download', function(next) { RESTBuilder.GET('https://www.example.com').callback(function(err) { Test.print('GET', err); next(); }); }); ``` ### Test.run([callback]) Type: `method` Runs all groups one by one. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `callback` | `Function` | no | | `function()` called instead of ending the process. | Returns: `undefined` Prints 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. Example: Run and stop the server ```js Test.run(function() { F.exit(); }); ``` ### Test.print(message, [err]) Type: `method` Prints the result of one check. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `message` | `String` | yes | | The name of the check. | | `err` | `Error|String` | no | | The reason of a failure. | Returns: `undefined` Without `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. Example: Check a value ```js var value = 'Total.js'.slug(); Test.print('slug()', value === 'total-js' ? null : 'Unexpected: ' + value); ``` ### Test.start(message) Type: `method` Prints a header between two divider lines. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `message` | `String` | yes | | The text of the header. | Returns: `undefined` `Test.run()` calls it with the name of each group. Call it yourself to separate parts of a long group. Example: Header ```js Test.start('Second part'); ``` ### Test.fake(name, action) Type: `method` Replaces an action with a fake. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `name` | `String` | yes | | The name of the action. | | `action` | `Object` | yes | | The definition of the fake, the same object as in `NEWACTION()`. | Returns: `Object` The registered fake action. Keeps 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. Example: Fake and restore ```js NEWACTION('Users/read', { action: $ => $.callback('real') }); Test.push('Fake', async function(next) { Test.fake('Users/read', { action: $ => $.callback('fake') }); var value = await ACTION('Users/read').promise(); Test.print('fake', value === 'fake' ? null : 'Unexpected: ' + value); Test.restore(); value = await ACTION('Users/read').promise(); Test.print('restore', value === 'real' ? null : 'Unexpected: ' + value); next(); }); Test.run(); ``` ### Test.count Type: `property` The number of checks printed by `Test.print()`. Returns: `Number` `Test.run()` prints it at the end as `Tests: <count>`. Example: Read ```js Test.run(function() { console.log('Checks:', Test.count); process.exit(0); }); ``` ### Test.restore() Type: `method` Puts the original actions back. Returns: `undefined` Removes every fake registered with `Test.fake()` and puts the original actions back. A fake of a name that had no action is only removed. Example: After a group ```js Test.push('Payments', function(next) { Test.fake('Payments/charge', { action: $ => $.callback({ paid: true }) }); // ... the checks Test.restore(); next(); }); ``` ### Test.items Type: `property` The groups added with `Test.push()`. Returns: `Array` An array of `{ name, fn }` objects. `Test.run()` runs them one by one; the array keeps them. Example: Count groups ```js console.log(Test.items.length, 'groups'); ``` --- title: Command line (total5) project: Total.js V5 version: 0.0.20 section: reference language: en license: MIT url: https://totaljs.es/docs/total-js-v5/0-0-20/reference/command-line/ updated: 2026-11-18T16:57:34.578Z --- # Command line (total5) > Every command and argument of the total5 and flow5 programs. The 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/). ```bash npm install -g total5 total5 help flow5 ``` ## API ### total5 [command] [arguments] Type: `command` The command-line toolbox of the total5 package. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `command` | `String` | no | `help` | The name of the command. | | `arguments` | `String` | no | | The arguments of the command, in order. | Runs 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. Example: Show the help ```bash total5 ``` ### total5 help Type: `command` Prints the list of commands. Prints 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. Example: Help ```bash total5 help total5 --help ``` ### total5 --<command> [arguments] Type: `command` Dashes in front of a command are ignored. The 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. Example: The same command twice ```bash total5 --help total5 help ``` ### total5 minify <filename> Type: `command` Minifies a JavaScript, CSS or HTML file. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `filename` | `String` | yes | | The full path of the file to minify. | Reads 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. Example: Minify a script ```bash total5 minify "$PWD/public/js/app.js" # Output : /home/me/shop/public/js/app.min.js ``` ### total5 edit <url> Type: `command` Opens the current directory for remote editing in the Total.js Code Editor. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `url` | `String` | yes | | The address of the project in the Code Editor, for example `https://code.example.com/?id=project`. | Connects 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`. Example: Edit a project ```bash cd ~/projects/shop total5 edit "https://code.example.com/?id=shop" ``` ### TYPE: browse | load | save | ... Type: `type` What the Code Editor can do through total5 edit. The 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. Example: A request and its answer ```js // sent by the editor { TYPE: 'browse', data: '{}' } // answer { TYPE: 'browse', data: '{}', success: true, response: { files: ['/index.js'], directories: ['/controllers/'] } } ``` ### total5 <port> Type: `command` Starts a static web server for the current directory on the given port. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `port` | `Number` | yes | | The port of the server. | A 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. Example: Serve a folder ```bash cd ~/projects/landing total5 8000 # open http://127.0.0.1:8000/ ``` ### total5 proxy <endpoint> <port> Type: `command` · Since: `0.0.17` Connects a local port to a remote Total.js proxy server. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `endpoint` | `String` | yes | | The WebSocket address of the proxy server. | | `port` | `String` | yes | | A local port (on `127.0.0.1`) or an `ip:port` pair. | Opens 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. Example: Share a local server ```bash total5 proxy wss://proxy.example.com/ 8000 ``` Example: The server side ```js // index.js of the proxy server require('total5'); PROXYSERVER('/', '/proxy/'); F.http({ port: 8000, load: 'none' }); // on your machine: // total5 proxy wss://proxy.example.com/proxy/ 8000 ``` ### total5 server [port] Type: `command` Starts a static web server for the current directory. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `port` | `Number` | no | `8000` | The port of the server. | The long form of `total5 <port>`. Without a port it listens on `8000`. Example: Default port ```bash total5 server # http://0.0.0.0:8000/ ``` Example: Another port ```bash total5 server 8080 ``` ### total5 test [name1] [name2] [...] Type: `command` Runs the unit tests of the current directory. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `name` | `String` | no | | The name of a test script without `.js`; several names with spaces or commas. | Takes 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/). Example: All tests ```bash cd ~/projects/shop total5 test ``` Example: Two scripts ```bash total5 test strings orders total5 test strings,orders ``` ### flow5 Type: `command` Prints the help of the Flow engine. Without arguments `flow5` prints `[Total.js v5 Flow Engine]` and the ways to call it. Example: Help ```bash flow5 # flow5 [path or URL address] [PORT_NUMBER] # flow5 path/to/flowschema.json # flow5 flow1.json flow2.json flowN.json 8001 # flow5 https://yourdomain.com/flowschema.json ``` ### GET /{path}/ Type: `type` What the web server shows for a directory. For 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. Example: Browse ```bash total5 8000 # http://127.0.0.1:8000/ -> the listing of the directory # http://127.0.0.1:8000/index.html -> the page ``` ### total5 translate <filename> Type: `command` Collects the @(...) texts of the current directory into a resource file. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `filename` | `String` | yes | | The full path of the resource file to write. | Reads 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. Example: Into resources ```bash total5 translate "$PWD/resources/default.resource" ``` ### flow5 <file> [port] Type: `command` Runs the flows of a local schema file. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `file` | `String` | yes | | The full path of the schema file. | | `port` | `Number` | no | `8000` | The port of the HTTP server. | Loads 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. Example: One file ```bash flow5 "$PWD/flowschema.json" # |--- http://127.0.0.1:8000 # |--- Orders: https://flow.totaljs.com/?socket=... ``` ### flow5 <url> [port] Type: `command` Runs the flows of a schema downloaded from an https address. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `url` | `String` | yes | | The `https://` address of the schema. | | `port` | `Number` | no | `8000` | The port of the HTTP server. | An 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. Example: Remote schema ```bash flow5 https://example.com/flowschema.json 8001 ``` ### KEY : text Type: `type` The file that total5 translate writes. A 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/). Example: Content ```text T1l964ro : Hello world T1j2ql : Save ``` ### flow5 <files...> <port> Type: `command` Sets the port of the Flow engine and runs several schemas at once. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `files` | `String` | yes | | One or more schema files or addresses. | | `port` | `Number` | no | `8000` | The port of the HTTP server. | Arguments 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. Example: Several files ```bash flow5 "$PWD/flow1.json" "$PWD/flow2.json" 8001 ``` ### total5 bundle <filename> Type: `command` Packs the current directory into a bundle file. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `filename` | `String` | yes | | The full path of the bundle file. | Writes 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. Example: Pack a project ```bash cd ~/projects/shop total5 bundle ~/backups/shop # ~/backups/shop.bundle ``` ### { id, name, components, design } | { <id>: schema } Type: `type` The two shapes of a file that flow5 reads. A 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. Example: One flow ```json { "id": "orders", "name": "Orders", "components": {}, "design": {} } ``` Example: Several flows ```json { "orders": { "id": "orders", "name": "Orders", "components": {}, "design": {} }, "mail": { "id": "mail", "name": "Mail", "components": {}, "design": {} } } ``` ### .bundle Type: `type` Which files total5 bundle puts into a bundle. All 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/`. Example: Deploy with a bundle ```bash total5 bundle ~/backups/shop scp ~/backups/shop.bundle server:/www/shop/bundles/ ``` ### GET|POST /notify/{id}/ Type: `property` The notification route of the Flow engine. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `id` | `String` | yes | | `<flow id>-<instance id>[-param...]`. | Sends 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/). Example: Notify a component ```bash curl -X POST -d '{"paid":true}' -H "Content-Type: application/json" http://127.0.0.1:8000/notify/orders-c1x8a/ ``` ### total5 extract <filename> Type: `command` Unpacks a bundle into the current directory. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `filename` | `String` | yes | | The full path of the bundle file to unpack. | Restores 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. Example: Unpack ```bash mkdir shop-copy && cd shop-copy total5 extract ~/backups/shop.bundle ``` ### SOCKET /flowstreams/{id}/ Type: `property` The WebSocket of the Flow editor. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `id` | `String` | yes | | The id of the flow. | The 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. Example: Open the editor ```text https://flow.totaljs.com/?socket=http%3A%2F%2F127.0.0.1%3A8000%2Fflowstreams%2Forders%2F ``` --- title: 0.0.20 project: Total.js V5 version: 0.0.20 section: changelog language: en license: MIT url: https://totaljs.es/docs/total-js-v5/0-0-20/changelog/0-0-20/ updated: 2026-11-19T16:16:52.152Z --- # 0.0.20 > What changed in release 0.0.20. Release 0.0.20 of the npm package `total5`. ## New - Extended stats by adding `app` property - Added `Total.FsPromises` a link to the `node:fs/promises` - Added `mcp` module - `CONF.$mcp = true` activates MCP route `POST /$mcp/` - Any `NEWACTION` with the `mcp: true` property will be available in the endpoint - 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 - 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` - `?q=words` returns only the tools whose name or description contain all the words - it is available whenever `CONF.$mcp` is enabled; nothing runs on the server - Added a new method `JSONSchema.toAIObject(name, [description])` - Added a new method `JSONSchema.toAITool(name)` - 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 - Added a new controller method `$.content(value, content_type)` - Added a new event `reset` in the FlowStream - Added support for the `cache` option of `NEWACTION()` (the response is kept for the same `query`, `params`, `input`, `user` or `language`) - Added the compact schema types `json` and `ip` (the values are validated) - 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`) - Added `U.validhost(host)` that accepts only plain hostnames and canonical IP literals - 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 - Added a new global class `User` - Added a new action method `.env(str)` for definining environment in the action `$.env {String}` - Added a new action and controller's method `$.throw(err)` to printing error into the console - Added a new action and controller's method `$.touch([url])` - Added a new action and controller's method `$.invalidsafe(msg, err)` - 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) - Added `Test.fake(name, action)` that replaces an action with a fake and `Test.restore()` that puts the original actions back - Added a native PostgreSQL client + QueryBuilderPG, initialization `DATA.init('connection name', 'connection string?pooling=1')` ## Changed - Improved `total5 test`: the framework of the tested project is found from its subdirectories too (e.g. from `tests`) - 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 - CVE-2026-105482: `dns.resolve*()` truncates a name at a NUL byte (`attacker.example\0.trusted.example`) - 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`) - 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) ## Fixed - Fixed `AIPARSER()` with tool calling - Fixed `CRON()` with the step form (`*/15`, `5/20`): it matches the values of the step and not every value - Fixed the `limit` argument of `setTimeout2()` - Fixed `AJAX()` for the answers with `application/xml` and `text/xml` - Fixed `F.python()` without a callback (the promise resolves with the output) and `F.pipinstall()` without a callback - Fixed `LOGMAIL()` with an object as the body - Fixed `IMPORT()`: an answer with the status 400 or more, or a file that is not a module, gives an error - Fixed the tunnel client (`proxy.js`): the types of the messages "error" and "abort" - Fixed the controller method `$.href()` - Fixed `QueryBuilder.gridfields()`: the accepted fields are applied - Fixed the handling of the pending requests (a single pass instead of `splice()` for each finished request) - 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) - 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) - Fixed `LDAP()`: a bind with a status other than 0 gives an error even when the server sends no text - 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) - 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) - Fixed `@{hostname()}` view engine command - Fixed `U.resolve()` (used by `REQUEST()`): an invalid hostname gives an error before the DNS query - Fixed `U.connect()`: the `host` is normalized and an invalid hostname gives the `Invalid hostname` error - 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 - Fixed `url` in the view engine - 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 - 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` - Fixed the `X-Priority` and `Sensitivity` headers of `high()`, `low()` and `confidential()` in the mail sent over SMTP - Fixed the `writer` option of `REQUEST()`: it was ignored and an empty body was sent - Fixed `RESTBuilder.API().get()`: it switched the request to GET and failed with "write after end" - Fixed `compress()` of `RESTBuilder.API()`: `null` values were still sent - Fixed `U.set()` with a path that goes on after an index (`items[0].name` made `items[0]` an array) - Fixed the `cache` option of `NEWACTION()`: actions without `id` shared one cache entry, and the caller could change the cached response - Fixed the `tls` option of `U.connect()`: the socket was never upgraded - Fixed `U.parseURI()`, `REQUEST()`, `RESTBuilder` and proxies with credentials in the URL (`user:pass@`): they failed with "user is not defined" - Fixed the `>` and `<` prefixes of `update()` and `modify()` in the NoSQL QueryBuilder - Fixed the `-`, `*` and `/` prefixes of `update()` and `modify()` in the NoSQL QueryBuilder (they all added the value) - Fixed `scalar()` of the NoSQL QueryBuilder: `avg` returns the average, and the aggregates work without a key - Fixed `count` and `pages` of `list()` with the NoSQL QueryBuilder - Fixed `search()` with `beg` and `end` in the PostgreSQL QueryBuilder, also on columns that are not text - Fixed the toggle `!name` of `update()` in the PostgreSQL QueryBuilder (the column is quoted) - Fixed `fields()` before `autoquery()` and `autoqueryjson()`: later queries no longer select extra columns - Fixed `gridfields()` with an empty or missing value - Fixed the `memory` key of FlowStream: it did not limit the heap of forks and worker threads - Fixed `$.send(null)` in FlowStream: `end` fired once per output, and an output without a ready target stopped the message for the next outputs - Fixed `TRANSFORM()` without a callback: `$.invalid()` threw a `TypeError` and the Promise never settled - Fixed `F.worker.isfork`: it was `true` in worker threads and `false` in forks - Fixed `NEWFORK()`: `--worker` did not reach the child process, so `F.worker.is` was `false` in forks - 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 - Fixed loading the framework from `node -e` (`process.argv[1]` and `process.mainModule` are undefined there) - Fixed `async` actions that throw an exception: the action is answered with an error (routes and MCP tools) instead of waiting for the timeout - Fixed the errors of JSON schema arrays whose items are objects with properties (wrong path, index and error) - Fixed double HTML encoding of the text added by `@{title2()}` - Fixed double HTML encoding of the title, description and keywords set by `@{meta(title, description, keywords)}` - Fixed `@{language}` in views rendered with `F.view()` - Fixed a global variable `language` created by every compiled view - Fixed views with more than one `@{}` value in a `<style>` block - Fixed `$.href()` with an object or array value, a trailing `&`, and lost parameters when it is called more than once - Fixed `$.href({ key: value })` and `@{href({ key: value })}`: they returned the URL without the query - Fixed the `filter` argument of `Image.miniature()` (and `.filter()`): it was placed after `-thumbnail` - Fixed `Image.background()`: `-background` goes before `-extent` so the color is used - Fixed the `[attr]` selector without a value in the HTML parser - Fixed `F.TCMS.compile()` with an object of widgets - Fixed binary WebSocket messages with compression: they were sent as compressed text frames - Fixed WebSocket clients refused by the authorization: they get the close code `4001` (or `4004`) instead of a dropped connection - Fixed the compression errors of WebSocket messages: they threw "self is not defined" instead of reaching the `error` event - Fixed `WEBSOCKETCLIENT` losing a message that arrives together with the `101` answer - Fixed `fs.clone(id)` without a new id in the Promise form - Fixed `clone()`, `copy()` and `readbuffer()` of `FILESTORAGE` while the storage is paused - Fixed `$tms : false`: it did not remove the TMS route when `$tmsurl` stayed the same - Fixed MCP tools whose action throws an exception: the request gets an error answer instead of waiting for the timeout - 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 - 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) - 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 - Fixed `AIPARSER('ollama')` with tool calls in separate chunks: it reads `function.index` - Fixed the generic `AIPARSER()` with tool calls without id in separate chunks: they no longer overwrite each other --- title: 0.0.19 project: Total.js V5 version: 0.0.20 section: changelog language: en license: MIT url: https://totaljs.es/docs/total-js-v5/0-0-20/changelog/0-0-19/ updated: 2026-11-15T17:28:39.396Z --- # 0.0.19 > What changed in release 0.0.19 (2026-09-29). Release 0.0.19 of the npm package `total5`, published on 2026-09-29. ```bash npm install total5@0.0.19 ``` ## New - Added an additional `check` for invalid hex values in `F.decrypt()` - Added loading stats after loading the framework (due to Flow) - Added support for auto-loading `index.flow` file in the plugins folder - Extended `NEWACTION` by adding a new handler: `onoutput: function(err, response, $)` - Extended `NEWACTION` by adding a new handler: `oninput: function($)` - Extended action's `$` by adding `$.input` property (alias for the `$.model`) - Extended `flowinstance.save(redraw = true)` method by adding `redraw` argument - Extended FlowStream by adding `instance.activity(key, name, [progress])` method - Extended `NEWACTION.route` option by adding support for `true` that adds `API ?` value - Added `.xhr` property in the `$` Options - Extended `SHELL()` method by increasing `maxBuffer` to `100 MB` - Added FlowStream node persistent in-memory cache `instance.cache` ## Changed - Removed watcher for the `.flow` files - Improved FlowStream stats by adding `online` editors ## Fixed - Fixed binding origin in the FlowStream - Fixed `restart` FlowStream - Fixed handling errors in the `NEWTRANSFORM()` method - Fixed CSS compiler - Fixed directory in the start information - Fixed initializing `TMSCLIENT` --- title: 0.0.18 project: Total.js V5 version: 0.0.20 section: changelog language: en license: MIT url: https://totaljs.es/docs/total-js-v5/0-0-20/changelog/0-0-18/ updated: 2026-11-16T07:54:28.030Z --- # 0.0.18 > What changed in release 0.0.18 (2026-06-29). Release 0.0.18 of the npm package `total5`, published on 2026-06-29. ```bash npm install total5@0.0.18 ``` ## New - Added `flow.proxytimeout {Number}` property - Extended the `message.send(output, data, [clone_data], [check(from, to, output, input)])` method by adding `check` argument - Extended `LDAP()` options by adding a new option `attributes = { thumbnailPhoto: 'buffer' }` for custom parsing data ## Changed - Updated Total.js debug watcher to detect incomplete file writes ## Fixed - Fixed handling static files - Fixed Flow error handling --- title: 0.0.17 project: Total.js V5 version: 0.0.20 section: changelog language: en license: MIT url: https://totaljs.es/docs/total-js-v5/0-0-20/changelog/0-0-17/ updated: 2026-11-16T07:54:33.030Z --- # 0.0.17 > What changed in release 0.0.17 (2026-06-01). Release 0.0.17 of the npm package `total5`, published on 2026-06-01. ```bash npm install total5@0.0.17 ``` ## New - Added `PROXYCLIENT(proxyserver, ip:port, [logger])` method - Added `PROXYSERVER(endpoint, socketendpoint, [logger])` method - Added `AIMODEL().tool(content)` method - Added `AIPARSER(provider)` method for parsing AI responses - Extended `String.prototype` by adding the `String.parseContext()` method to parse a specific text file format - Added `ACTION().config(obj)` method - Added a new property `flow.instance.repo = {}` for storing additional data for Flow node instances ## Changed - Improved returing `origin` in the CORS - `DEBUG` is set according to the `process.env.NODE_ENV` variable - Improved code - Improved `Utils.filestreamer()` method by adding percentage ## Fixed - Fixed error handling in emails - Fixed removing routes via `route.remove()` method - Fixed `beautify` and `replacer` arguments in the `controller.json()` - Fixed `mail` priority - Fixed `kB` and `GB` units in the routing as upload limits - Fixed server pinging of all WebSocket connections - Fixed typo in send method data assignment - Fixed `Utils.filestreamer()` method - Fixed sending data to all outputs `$.send(null, [data])` in the FlowStream - Fixed sending data to all outputs `instance.send(null, [data])` in the FlowStream - Fixed removing WebSocket route --- title: 0.0.16 project: Total.js V5 version: 0.0.20 section: changelog language: en license: MIT url: https://totaljs.es/docs/total-js-v5/0-0-20/changelog/0-0-16/ updated: 2026-11-16T07:54:33.030Z --- # 0.0.16 > What changed in release 0.0.16 (2026-03-31). Release 0.0.16 of the npm package `total5`, published on 2026-03-31. ```bash npm install total5@0.0.16 ``` ## New - Added `RESTBuilder.?.logerror()` method for printing errors into the console - Added `API.?.logerror()` method for printing errors into the console - Added a new config key `CONF.$httpcacheoffset` for extending `last-modified` header - Exended `Total.download()` by adding `size {Number}` property to the response - Extended FlowStream by adding the ability to execute Total.js actions - Added a new global event `ON('flowstream', function(instance) {` - Added new action methods `$.progress(percentage)` and `ACTION().progress(console.log)` to measure percentage - Added a new method `U.aistreamer(on_line, on_message)` - Added `Flow.edit(proxy_socket_url)` method for the remote editing of the FlowStream - Added a new global methods `AIMODEL()` and `NEWAIMODEL()` - Added `exec` command to the remote editing functionality - Added `timeout {Number}` property into the `NEWACTION` method - Extended `NEWAPI(type, [config], callback)` by adding the `config` argument - Added support for nested inline action schemas in action schemas - Extended `data` object in the `DEF.onAudit` delegate by adding `sessionid {String}` property - Added `options.timeout {Number}` to the `WebSocketClient` - Extended `U.chunker()` by adding `.load([callback])` method for loading existing chunks ## Changed - Improved loading plugins - Framework reads a `/config` file in `plugins` - Improved auditlogs by adding `files` - Improved compiling navigation in the CMS compiler - Always set `cwd` directory for the current executed script - Replaced `Url.parse()` with `new URL()` - Changed `SIGTERM` for `SIGKILL` in the `NEWFORK()` method ## Fixed - Fixed handling of unexpected problems in the Flow with the main process becoming disconnected - Fixed `uptime` value in the framework stats - Fixed unexpected errors when compressing/decompressing data via WebSocket - Fixed processing TMS data in the FlowStream - Fixed Total error handling - Fixed filling of the `template` property in the CMS compiler - Fixed `NEWFORK()` method - Fixed callback with `$` in the `ACTION().callback($)` - Fixed returing a default JSON schema object in actions - Fixed loading of `totalapi` key via `LOADCONFIG()` - Fixed promise in the `AJAX()` method --- title: 0.0.15 project: Total.js V5 version: 0.0.20 section: changelog language: en license: MIT url: https://totaljs.es/docs/total-js-v5/0-0-20/changelog/0-0-15/ updated: 2026-11-15T17:28:34.394Z --- # 0.0.15 > What changed in release 0.0.15 (2025-12-04). Release 0.0.15 of the npm package `total5`, published on 2025-12-04. ```bash npm install total5@0.0.15 ``` ## New - Added support for `.webmanifest` file extension - Added a new JSON Schema type `DataURI2` that keeps a value as text ## Changed - Improved `keepalive` option in the `REQUEST()` method (it can contain HttpAgent or options for it) - Updated `RESTBuilder.keepalive()` method by adding `val` argument - Improved error handling in the Flow engine ## Fixed - Fixed nested objects in JSON schemas - Fixed column indexer in the CSV parser - Fixed proxy timeout - Fixed string slug method - Fixed an issue with generating file names when merging files directly in the view engine - Fixed handling of case-sensitive file names - Fixed unexpected errors with the stream when handling static files - Fixed sending mail attachments - Fixed creating an empty object according to the nested JSON schema - Fixed handling unexpected errors in the FlowStream - Fixed network connection problems in remote editing - Fixed throwing of timeout error in WebSocketClient