--- title: Introduction project: Total.js V4 version: 0.0.99 section: guides language: en license: MIT url: https://totaljs.es/docs/total-js-v4/0-0-99/guides/introduction/ updated: 2026-11-16T15:41:00.817Z --- # Introduction > Total.js 4 is a full-stack framework for Node.js written in pure JavaScript, with no dependencies. Total.js 4 is a full-stack framework for Node.js written in pure JavaScript. It builds web applications, REST APIs, background services, desktop and IoT applications with one package, `total4`, and **no dependencies**: only Node.js. ## What it gives you - **Routing**: one `ROUTE()` function for pages, REST endpoints, file handlers and WebSockets. See [Routing](../routing/). - **Controllers**: the object that answers a request (`this.json()`, `this.view()`, `this.plain()`…). - **Schemas and actions**: validated input and operations (`insert`, `update`, `read`, your own) that routes call directly. - **Views**: a template engine for HTML with layouts, partials and localization. - **Embedded databases**: NoSQL and TextDB, stored in files inside the app. - **Localization**: resource files and `@(Text)` markers in views. - **Workers, tasks and FlowStream**: background work and visual data flows. - **The `total4` command**: templates, translations, bundles and packages. ## How an app is organized An app is a folder with a start script (`index.js`) and some of these folders. Total.js loads them when the app starts; none of them is required. | Folder | What goes in it | | --- | --- | | `controllers/` | Routes (`exports.install`) and their actions | | `schemas/` | Schemas and their actions | | `definitions/` | Code that runs at start: helpers, auth, configuration | | `views/` | HTML templates | | `public/` | Static files: CSS, JavaScript, images | | `resources/` | Localization files | | `databases/` | Data of NoSQL, TextDB and file storages | | `modules/`, `plugins/` | Reusable parts of an app | | `workers/`, `tasks/` | Background work | | `jsonschemas/`, `operations/`, `middleware/`, `flowstreams/` | JSON schemas, operations, middleware and FlowStream data | | `private/` | Files that are never served | ## Versions of this documentation This project documents the official Total.js 4: the [totaljs/framework4](https://github.com/totaljs/framework4) repository and the `total4` package on npm (latest **0.0.99**). API entries say **since** which version they exist, so you know what you can use with the version of your app. --- title: Installation and first app project: Total.js V4 version: 0.0.99 section: guides language: en license: MIT url: https://totaljs.es/docs/total-js-v4/0-0-99/guides/installation/ updated: 2026-11-16T15:41:00.817Z --- # Installation and first app > Install Total.js 4, write the start script and answer your first requests. ## Requirements Node.js. Total.js 4 has no dependencies and does not require a specific version of Node.js; use a current LTS release. ## Install ```bash mkdir myapp cd myapp npm init -y npm install total4 ``` ## The start script Create `index.js`. It is the official start script of Total.js 4, reduced to what you need now: ```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); ``` Run it: ```bash node index.js ``` The app listens on port **8000**. In **debug** mode it restarts by itself when you change a file. In production start it with `node index.js --release`. ## Your first routes Create `controllers/default.js`: ```js exports.install = function() { ROUTE('GET /', home); ROUTE('GET /hello/{name}/', hello); }; function home() { this.plain('Hello world'); } function hello(name) { this.json({ hello: name }); } ``` Open `http://127.0.0.1:8000/` and `http://127.0.0.1:8000/hello/Peter/`. Each action runs with the controller as `this`, and the dynamic parts of the URL arrive as arguments. ## Options of the start script | Option | What it does | | --- | --- | | `ip`, `port` | Address and port of the server (default port `8000`) | | `unixsocket` | Listens on a Unix socket instead of a port | | `config` | Values that override the `config` file | | `sleep` | Waits before starting, in milliseconds | | `inspector` | Opens the Node.js inspector on a port | | `watch` | Extra folders that restart the app in debug mode | | `https` | `key` and `cert` to serve HTTPS directly | | `cluster`, `cluster_limit` | Runs several processes (`'auto'` scales them) | | `servicemode` | Starts without the web server (`--servicemode`) | ## Next Read [Routing](../routing/) to learn the whole syntax of `ROUTE()`. --- title: Routing project: Total.js V4 version: 0.0.99 section: guides language: en license: MIT url: https://totaljs.es/docs/total-js-v4/0-0-99/guides/routing/ updated: 2026-11-16T15:41:00.817Z --- # Routing > Methods, dynamic parameters, signed-in users, schemas, API routes, views and flags of ROUTE(). Every route is declared with `ROUTE()`, usually inside `exports.install` of a file in `controllers/`. ```js exports.install = function() { ROUTE('GET /products/', products); ROUTE('POST /products/', create); }; ``` The first argument describes the route in one line: **method**, **URL**, and optionally a **schema operation**, **middleware**, **roles** and **flags**. The full list of arguments is in the reference of [ROUTE()](../../reference/routing/). ## Methods `GET` is the default. Write the method before the URL: `GET`, `POST`, `PUT`, `PATCH`, `DELETE`, `HEAD`, `OPTIONS`. Several methods are separated by commas: ```js ROUTE('GET,POST /contact/', contact); ``` ## Dynamic parameters Parts in braces are parameters. They arrive as arguments of the action, in their order, and in `this.params`: ```js ROUTE('GET /users/{id}/', read); ROUTE('GET /blog/{year}/{slug}/', article); function article(year, slug) { // this.params.year, this.params.slug } ``` A parameter can have a type: `{page:number}`, `{active:boolean}` and `{date:date}` are converted in `this.params`. `{id:uid}` and `{id:guid}` accept only identifiers of that kind. A `*` at the end of the URL matches the rest of the path: ```js ROUTE('GET /docs/*', docs); ``` ## Signed-in users `+` before the method allows only requests that your `AUTH()` delegate accepted, and `-` only the others. A role (`@admin`) implies a signed-in user: ```js ROUTE('+GET /account/', account); ROUTE('-GET /login/', login); ROUTE('+GET /admin/ @admin', admin); ``` ## Schemas and actions A route can call operations of a schema without writing an action. `*Schema --> operation` validates the request body with the schema and runs the operation: ```js ROUTE('POST /api/users/ *Users --> insert'); ROUTE('GET /api/users/{id}/ *Users --> read'); ``` Several operations run one after another. `(response)` after one of them says whose result is sent back: ```js ROUTE('POST /api/orders/ *Orders --> check insert (response) notify'); ``` ## API routes `API` groups many operations behind one URL. The client sends `POST` with `{ "schema": "name/params", "data": {} }`; `+` marks the operations that take data and `-` those that do not: ```js ROUTE('API /api/ -users_list *Users --> list'); ROUTE('API /api/ -users_read/{id} *Users --> read'); ROUTE('API /api/ +users_save *Users --> save'); ``` ## Views An action can be the name of a view. Without an action, the view is chosen from the URL: ```js ROUTE('GET /about/', 'about'); // views/about.html ROUTE('GET /pricing/'); // views/pricing.html ``` ## Flags Flags change how a route works. Write them in the URL after a space, or pass them as an array: ```js ROUTE('POST /upload/', upload, ['upload', 60000], 1024 * 5); ``` - `json`, `xml`, `raw`: the body comes as JSON, XML or raw data (the route becomes `POST`). - `upload`: the body is `multipart/form-data` with files. - `cors`, origins (`https://app.com`) and `credentials`: cross-origin requests. - `csrf`, `referer`: checks the CSRF token or the referer. - `mobile`, `robot`: only for mobile devices, or only for crawlers. - `encrypt`: the answer is encrypted. - `delay`: the request has no timeout. - `novalidate`: the schema converts the body without validating it. - A number: the timeout of the request in milliseconds (default `3000`). - `#name` or `&name`: runs a middleware first. - `// text`: a description of the route. ## Request size The last argument limits the size of the request body, in **kilobytes** (default `10`). It is needed for big JSON bodies and uploads: ```js ROUTE('POST /api/import/ json', importdata, 1024); // 1 MB ``` ## Files and WebSockets `FILE` routes handle static-like files and `SOCKET` routes open WebSockets; they have their own pages in the reference. ```js ROUTE('FILE /docs/*.pdf', pdf); ROUTE('SOCKET /chat/', chat); ``` ## Subdomains and removing routes A route only for a subdomain starts with it in brackets: `ROUTE('[api]/users/', users)`. `ROUTE(url, null)` removes a route that was declared before. --- title: Controllers project: Total.js V4 version: 0.0.99 section: guides language: en license: MIT url: https://totaljs.es/docs/total-js-v4/0-0-99/guides/controllers/ updated: 2026-11-16T15:41:00.817Z --- # Controllers > The controller is `this` in every route action: it holds the request data and answers the request. Every action of a route runs with a **controller** as `this`. The controller holds the data of the request and has the methods that answer it. A new controller is created for each request. ```js exports.install = function() { ROUTE('GET /products/{id}/', detail); }; function detail(id) { // id === this.params.id this.json({ id: id, ip: this.ip }); } ``` The dynamic parts of the URL arrive as arguments of the action, in their order. The full list of properties and methods is in the reference of [Controller](../../reference/controller/). ## Request data | Property | What it contains | | --- | --- | | `this.body` | The parsed body of the request (JSON or a form) | | `this.query` | The query string as an object (`?page=2` gives `{ page: '2' }`) | | `this.params` | The dynamic parameters of the URL, converted by their type (`{page:number}`) | | `this.files` | Uploaded files, for routes with the `upload` flag | | `this.user` | The user that your `AUTH()` delegate accepted, or `undefined` | | `this.headers` | The request headers, with lower-case names | | `this.ip` | The IP address of the client (the first `X-Forwarded-For` address behind a proxy) | | `this.url` | The path of the URL in lower case, with a trailing slash | | `this.uri` | The parsed URL (`pathname`, `query`, `hostname`…) | | `this.ua` | A short name of the browser and the system, parsed from `User-Agent` | | `this.mobile`, `this.robot` | `true` for mobile devices, or for crawlers | | `this.xhr` | `true` when the request has `X-Requested-With: XMLHttpRequest` | | `this.referrer` | The `Referer` header, or an empty string | | `this.language` | The language set by your localization delegate | | `this.req`, `this.res` | The request and the response objects of the framework | ```js exports.install = function() { ROUTE('POST /api/contact/', contact); }; function contact() { var model = this.body; var page = this.query.page; var agent = this.headers['user-agent']; this.success(); } ``` `this.query` and `this.body` contain strings: convert numbers and dates yourself, or let a schema do it (see [Routing](../routing/)). ## Uploaded files A route with the `upload` flag reads `multipart/form-data`. Each item of `this.files` has `name` (the field), `filename`, `type`, `size`, `extension`, and `width` and `height` for images. `move()`, `copy()` and `read()` return a promise when you do not pass a callback: ```js exports.install = function() { ROUTE('POST /upload/', upload, ['upload'], 1024 * 5); }; async function upload() { var file = this.files[0]; if (!file || !file.isImage()) { this.invalid('Send an image'); return; } await file.move(PATH.public('photos/' + file.filename)); this.success(); } ``` The framework removes the temporary files when the request ends. Call `this.autoclear(false)` to keep them. ## Answering Answer each request **once**. The methods return the controller, so you can call `return this.json(...)` to stop the action. | Method | Answer | | --- | --- | | `this.json(obj)` | JSON (`application/json`) | | `this.plain(text)` | Plain text; an object is serialized as formatted JSON | | `this.html(body)` | HTML | | `this.content(body, type)` | Any text with your content type | | `this.view(name, [model])` | A rendered view from `views/` | | `this.file(filename, [download])` | A file from `public/` (or any path that starts with `~`) | | `this.binary(buffer, type)` | A buffer | | `this.stream(stream, type)` | A readable stream | | `this.redirect(url, [permanent])` | A redirect, `302` or `301` | | `this.empty()` | An empty body | | `this.nocontent()` | `204 No Content` | | `this.success([value])` | `{ "success": true }` | | `this.invalid(error)` | An error as JSON, `400` by default | ```js function download() { this.file('invoices/2024.pdf', 'invoice.pdf'); } function legacy() { this.redirect('/new-address/', true); } ``` ## The status code Set `this.status` before you answer. `json()`, `plain()`, `content()`, `html()`, `jsonstring()` and `empty()` use it; the default is `200`. ```js function create() { var item = { id: UID(), name: this.body.name }; this.status = 201; this.json(item); } ``` `this.empty(204)` sets the status and answers in one call. ## Success and validation errors `this.success()` answers `{ "success": true }`. With a value it answers `{ "success": true, "value": ... }`, and `this.success(false)` answers `{ "success": false }`. `this.invalid()` answers an array of errors as JSON with the status `400`. A number as the first argument sets another status: ```js function save() { if (!this.body.email) { this.invalid('email', 'The email is required'); return; } this.success(true, { id: UID() }); } ``` Two helpers create callbacks in the style `(err, response)`. `this.done()` answers `invalid(err)` on error and `success()` otherwise; `this.done(true)` adds the response as `value`. `this.callback()` answers the response as JSON, or with a view when you pass its name: ```js function list() { // loadproducts(callback) is your own function loadproducts(this.callback()); } function remove() { removeproduct(this.params.id, this.done()); } ``` ## Error pages `this.throw404()` and its siblings answer with an error page: `throw400()`, `throw401()`, `throw403()`, `throw404()`, `throw409()`, `throw500()`, `throw501()` and `throw503()`. They have aliases named `view400()`… `view503()`. The argument is a description of the problem; `throw500(err)` also logs the error. ```js function detail(id) { var self = this; // findproduct(id, callback) is your own function findproduct(id, function(err, item) { if (item) self.view('detail', item); else self.throw404(); }); } ``` To render your own page, declare a route for the status. The problem is in `this.exception`: ```js exports.install = function() { ROUTE('#404', notfound); }; function notfound() { this.status = 404; this.view('404'); } ``` Without such a route the framework renders its own error page. ## Headers and cache `this.header(name, value)` sets a header of the response. Most answering methods also take an object with headers. `this.nocache()` disables the HTTP cache of the answer: ```js function report() { this.nocache(); this.header('X-Report', 'daily'); this.plain('...'); } ``` ## Cookies `this.cookie(name)` reads a cookie. `this.cookie(name, value, expires, [options])` writes it; `expires` is a text such as `'5 days'`, and options are `domain`, `path` (`/`), `secure`, `httponly` and `samesite` (`Lax` by default): ```js function login() { this.cookie('session', 'token', '7 days', { httponly: true }); this.redirect('/'); } function logout() { this.cookie('session', '', '-1 day'); this.redirect('/'); } ``` ## Views and layouts `this.view(name, [model])` renders `views/name.html` inside the layout `views/layout.html`. Routes of `controllers/default.js` find their views in `views/`; routes of another controller, for example `controllers/admin.js`, in `views/admin/`. A name that starts with `~` always starts in `views/`. ```js function home() { this.layout('layout_home'); this.title('Welcome'); this.view('index', { products: [] }); } ``` - `this.layout(name)` chooses another layout; `this.layout('')` renders the view without a layout. - `this.title()` and `this.meta(title, [description], [keywords], [image])` set values the layout prints with `@{title}` and `@{meta}`. - `this.repository` is an object shared by the view and its layout. - `this.view(name, model, true)` returns the HTML as a string instead of answering. The template syntax is explained in [Views](../views/). ## Signed-in users `this.user` is what your `AUTH()` delegate accepted. Routes with `+` run only for signed-in users, so `this.user` always exists there: ```js // definitions/auth.js AUTH(function($) { var token = $.cookie('session'); if (token === 'token') $.success({ id: 1, name: 'Peter' }); else $.invalid(); }); // controllers/default.js exports.install = function() { ROUTE('+GET /account/', account); }; function account() { this.json(this.user); } ``` ## Errors in actions An exception thrown in an action is logged and the request gets the error page `500`. In callbacks and promises nothing catches the exception for you: catch it and call `this.throw500(err)` or `this.invalid(err)`. ```js async function stats() { try { var data = await loadstats(); this.json(data); } catch (err) { this.throw500(err); } } ``` --- title: Schemas and actions project: Total.js V4 version: 0.0.99 section: guides language: en license: MIT url: https://totaljs.es/docs/total-js-v4/0-0-99/guides/schemas/ updated: 2026-11-16T15:41:00.817Z --- # Schemas and actions > Declare schemas with typed and validated fields, write operations and actions, use the $ object and call them from routes and code. A **schema** describes the data your app receives and the operations that work with it. Total.js converts the request body to the types you declare, validates it, and runs your operation with a `$` object that knows the model, the query, the user and how to answer. Routes call schemas directly, so a REST endpoint often needs no action of its own. Put schemas in the `schemas/` folder. Total.js loads every file there when the app starts. ## Declaring a schema `NEWSCHEMA(name, declaration)` creates a schema. The declaration receives the schema and declares its fields and operations: ```js NEWSCHEMA('Users', function(schema) { schema.define('id', 'UID'); schema.define('name', 'String(50)', true); schema.define('email', 'Email', true); schema.define('age', Number); schema.define('role', ['admin', 'user']); schema.setInsert(function($, model) { model.id = UID(); NOSQL('users').insert(model); $.success(model.id); }); }); ``` Declaring a schema with an existing name replaces the old one. `NEWSCHEMA('Users', null)` removes it. `GETSCHEMA('Users')` returns a declared schema. ## Field types `schema.define(name, type, [required], [error])` accepts a constructor, a type name (case does not matter), an array or an object: | Type | What the value becomes | | --- | --- | | `String`, `'String'`, `'Text'` | A trimmed string. `'String(50)'` cuts it to 50 characters | | `'Name'`, `'Capitalize'`, `'Capitalize2'`, `'Lower'`, `'Upper'` | A string with its case changed | | `'SafeString'` | A string checked for XSS and SQL injection | | `'Email'`, `'Phone'`, `'Zip'`, `'URL'`, `'JSON'`, `'Base64'` | A string; a required field must have a valid value | | `'Color'`, `'Icon'` | A string with a color or an icon name | | `'UID'` or `UID`, `'GUID'` or `GUID` | An identifier | | `Number`, `'Number'`, `'Float'`, `'Decimal'`, `'Double'` | A decimal number | | `'Int'`, `'Integer'`, `'Byte'`, `'TinyInt'`, `'SmallInt'` | An integer | | `'Number2'` | A number; when required, `0` is also valid | | `Boolean`, `'Boolean'`, `'Bool'` | `true` or `false` | | `Date`, `'Date'`, `'Time'`, `'DateTime'` | A date | | `Object`, `'Object'` | Any object | | `'name:String, age:Number'` | An object with these fields | | `['a', 'b']` | An enum: one of the values | | `{ a: 'A', b: 'B' }` | A key-value list: one of the keys | | `Array`, `'[]'`, `'[String]'`, `'[Number]'` | An array, of the type in brackets | | `'Address'`, `'[Address]'` | Another schema, or an array of it, validated with its own rules | The model your operation receives contains only the declared fields, already converted. A schema without fields passes the body as it came. ## Required fields and error messages The third argument makes a field required. What "required" checks depends on the type: - a string must not be empty, and `Email`, `Phone`, `URL`, `UID` and similar must be valid; - a number must be greater than `0`, and a boolean must be `true`; - an array must not be empty. Instead of `true` you can pass a function `(value, model)` that returns `true`, `false` or an error message. A string as the third argument makes the field required and is its error message: ```js schema.define('name', 'String(50)', true); schema.define('email', 'Email', 'Enter a valid email address'); schema.define('password', 'String(30)', true, 'The password is too short'); schema.define('age', Number, value => value >= 18, 'You must be an adult'); ``` Without a message, Total.js reads it from the resource set with `schema.setResource()` (the key is the field name), or answers `The field "name" is invalid`. A message that starts with `@` is a resource key. `schema.required(name, fn)` makes a field required only when `fn(model, operations)` returns `true`, for example only on insert. ## Default values `schema.define()` returns a function that sets the default value. It returns the schema again: ```js schema.define('count', Number)(10); schema.define('created', Date)(() => new Date()); ``` ## Classic operations The classic way gives the schema up to seven operations. Each one receives `$` and the validated model: | Method | Operation name in routes | | --- | --- | | `schema.setSave(fn)` | `save` | | `schema.setInsert(fn)` | `insert` | | `schema.setUpdate(fn)` | `update` | | `schema.setPatch(fn)` | `patch` | | `schema.setRead(fn)` | `read` (or `get`) | | `schema.setQuery(fn)` | `query` (or `list`) | | `schema.setRemove(fn)` | `remove` | `schema.addWorkflow(name, fn)` adds an operation with your own name: ```js NEWSCHEMA('Users', function(schema) { schema.define('name', 'String(50)', true); schema.setQuery(function($) { NOSQL('users').find().callback($.callback); }); schema.setRead(function($) { NOSQL('users').one().where('id', $.id).callback($.callback, 'error-users-404'); }); schema.addWorkflow('activate', function($) { NOSQL('users').modify({ active: true }).where('id', $.id); $.success(); }); }); ``` ## Actions: schema.action() `schema.action(name, options)` is the newer style. One object declares the operation and everything it needs: the input, the query and the URL parameters it accepts, and who may run it. The input is declared inline, so the schema needs no `define()`: ```js NEWSCHEMA('Users', function(schema) { schema.action('list', { name: 'List of users', query: 'page:Number, limit:Number', user: true, action: function($) { NOSQL('users').find().take($.query.limit || 20).callback($.callback); } }); schema.action('create', { name: 'Create a user', input: '*name:String(50), *email:Email, role:{admin|user}', permissions: 'admin', action: function($, model) { model.id = UID(); NOSQL('users').insert(model); $.success(model.id); } }); }); ``` In `input`, `query` and `params`, fields are separated by commas, `*` marks a required field, `[String]` is an array, `{a|b}` an enum and `@Name` another schema or action. Instead of an inline declaration you can give the name of a JSON schema from the `jsonschemas/` folder. | Option | What it does | | --- | --- | | `action` | The function `($, model)` that runs the action | | `name` | A description of the action | | `input` | Fields of the request body. Invalid data stops the action | | `output` | Fields of the response. Other fields are removed | | `query` | Fields of the query string, converted into `$.query` | | `params` | Fields of the URL parameters, converted into `$.params` | | `user` | `true`: only for a signed-in user, otherwise `401` | | `sa` | `true`: only for a super admin (`user.sa` or `user.su`) | | `permissions` | `'read,write'`: the user needs one of them in `user.permissions` or `user.roles` | | `cache` | Caches the response: `{ query, params, user, language, expire }` | Both styles call operations the same way, and you can mix them in one schema. ## The $ object Every operation receives `$`. It ends the operation and gives you the request: | Member | What it is | | --- | --- | | `$.callback(value)` | Answers with the value; `$.callback(err)` with an error | | `$.success([value])` | Answers `{ "success": true, "value": ... }` | | `$.invalid(name, [message])` | Answers with an error; `$.invalid(404)` with a status code | | `$.done([value])` | Returns a callback `(err, response)` that answers with success or the error | | `$.successful(fn)` | Returns a callback that runs `fn(response)` only when there is no error | | `$.redirect(url)` | Redirects the request | | `$.model` | The validated model | | `$.query`, `$.params`, `$.id` | The query string, the URL parameters and the first one of them | | `$.user`, `$.session` | The signed-in user and the session | | `$.keys` | In a `PATCH` request, the fields that were sent | | `$.filter` | The query converted with the filter of the operation | | `$.controller` | The controller; also `$.req`, `$.res`, `$.headers`, `$.ip`, `$.language`, `$.files`, `$.body` | Call exactly one of `$.callback()`, `$.success()`, `$.invalid()` or `$.redirect()` per operation: ```js schema.setRead(function($) { NOSQL('users').one().where('id', $.id).callback(function(err, user) { if (user) $.callback(user); else $.invalid(404); }); }); ``` ## Calling operations from routes `*Schema --> operation` after the URL validates the request body with the schema and runs the operation. The first dynamic parameter becomes `$.id`: ```js exports.install = function() { ROUTE('GET /api/users/ *Users --> query'); ROUTE('GET /api/users/{id}/ *Users --> read'); ROUTE('POST /api/users/ *Users --> insert'); ROUTE('PATCH /api/users/{id}/ *Users --> patch'); ROUTE('DELETE /api/users/{id}/ *Users --> remove'); ROUTE('POST /api/users/{id}/activate/ *Users --> activate'); }; ``` `GET` requests have no body, so there is nothing to validate. In a `PATCH` request, only the fields that were sent are validated. Several operations run one after another, and `(response)` after one of them chooses whose result is sent back: ```js ROUTE('POST /api/users/ *Users --> insert (response) notify'); ``` The whole syntax is in the [Routing](../routing/) guide. ## NEWACTION(): actions without a schema `NEWACTION(name, options)` declares an action that does not belong to any schema. It takes the same options as `schema.action()`. Name actions with a slash, `Users/create`, to group them: ```js NEWACTION('Users/create', { name: 'Create a user', input: '*name:String(50), *email:Email', user: true, action: function($, model) { model.id = UID(); NOSQL('users').insert(model); $.success(model.id); } }); ``` A route calls it with `-->` and no schema: ```js ROUTE('POST /api/users/ --> Users/create'); ``` The option `route: 'API /api/'` declares an API route for the action by itself; the API name is the action name in lowercase with `_` instead of `/` (`users_create`). ## Running operations from code `CALL()` runs actions and schema operations from anywhere in your code. It starts on the next tick, so you can set options first: ```js CALL('Users/create', { name: 'Peter', email: 'peter@example.com' }).user(user).callback(function(err, response) { // ... }); var users = await CALL('Users --> list').query({ page: 1 }).promise(); ``` Inside an operation, `$.action(name, [data])` does the same; a name without `-->` is an operation of the current schema. `EXEC('+Users --> insert', model, callback)` also runs schema operations and returns a promise without a callback. `MAKE('Users', model)` only validates a model. All the methods are in the [Schemas](../../reference/schemas/) reference. --- title: Views project: Total.js V4 version: 0.0.99 section: guides language: en license: MIT url: https://totaljs.es/docs/total-js-v4/0-0-99/guides/views/ updated: 2026-11-16T15:41:00.817Z --- # Views > HTML templates in views/: expressions, conditions, loops, layouts, partials, sections, helpers and localization. A view is an HTML file in `views/` with commands in `@{...}`. Total.js compiles it into a JavaScript function, runs it with a model, wraps the result in a layout and sends it as the response. ## Where views live Views are `.html` files in `views/`. You name them without the extension. ```text views/ layout.html index.html contact.html users/ index.html detail.html ``` A controller looks first in the folder with its own name. In `controllers/users.js`, `this.view('detail')` renders `views/users/detail.html`. When that file does not exist, Total.js tries `views/detail.html`. The controller `default.js` uses `views/` directly. A prefix changes where the view is looked up: | Name | File | | --- | --- | | `index` | `views//index.html`, then `views/index.html` | | `~index` | `views/index.html`, always from the root of `views/` | | `=admin/index` | `themes/admin/views/index.html` | | `@index` | the view of a package | | `#plugin/index` | the view of a plugin | | `.path/to/file` | an absolute path, without `.html` | ## Render a view The simplest route has the name of a view instead of an action: ```js exports.install = function() { ROUTE('GET /', 'index'); ROUTE('GET /contact/', 'contact'); }; ``` From an action, call `this.view()` with the name and a model: ```js exports.install = function() { ROUTE('GET /products/', products); }; function products() { var model = { name: 'Shop', items: [{ name: 'Apple', price: 1.2 }, { name: 'Pear', price: 0.9 }] }; this.view('products', model); } ``` Without a name, `this.view(model)` renders the view named after the last part of the URL (`index` for `/`). A schema operation can render its result as a view. The result becomes the model: ```js ROUTE('GET /products/ *Products --> list', 'products'); ``` ## The model and the repository The model is the second argument of `this.view()`. In the view it is `model` (or `M`): ```html

@{model.name}

@{model.items.length} products

``` The **repository** is an object shared by the view, its partial views and the layout during one request. Use it to pass values that are not part of the model, like a page class. It is `controller.repository` in JavaScript and `repository` (or `R`) in the view: ```js function products() { this.repository.page = 'products'; this.view('products', model); } ``` ```html ``` A view can also assign values. The command prints nothing: ```html @{repository.page = 'products'} ``` Other variables you can use in a view: `user`, `session`, `query`, `body` (request body, see the layout section for `@{body}` alone), `config`, `language`, `url`, `controller`. ## Expressions and escaping `@{expression}` prints the value of any JavaScript expression, **HTML-encoded**. Put `!` in front to print it **raw**: ```html

@{model.name}

@{model.price.format(2)}

@{!model.html}
``` With `model.name = 'Peter'`, `@{model.name}` prints `<b>Peter</b>`, and `@{!model.name}` prints the bold tag. `null` and `undefined` print nothing. Use the raw form only for HTML you trust. The output of helpers, `@{json()}` and the form commands is not encoded again. Text that starts with `@{{` is not a command; it is left in the page as it is. ## Conditions ```html @{if model.items.length}

@{model.items.length} products

@{else if model.loading}

Loading…

@{else}

No products.

@{fi} ``` The condition is JavaScript. Close it with `@{fi}` or `@{endif}`. ## Loops ```html ``` `index` is the position of the item, from `0`. An empty array prints nothing. When you loop over an object, each item has `key` and `value`: ```html @{foreach item in model.prices}
  • @{item.key}: @{item.value}
  • @{end} ``` `@{continue}` and `@{break}` work inside the loop, usually in an `@{if}`. ## Layouts Every view is rendered inside a layout. The default layout is `views/layout.html` (`default_layout` in the config). `@{body}` prints the rendered view: ```html @{import('meta', 'head', 'default.css', 'default.js')} @{body} ``` If the layout file does not exist, the request ends with an error 500. Create it, or turn the layout off. Change the layout in the controller or in the view: ```js function admin() { this.layout('admin'); // views/admin.html this.view('dashboard'); } function plain() { this.layout(''); // no layout this.view('plain'); } ``` ```html @{layout('admin')} ``` The layout gets the same model and repository as the view. ## Partial views `@{view(name, [model])}` renders another view in place, without a layout. Pass the model if the partial needs it: ```html @{foreach item in model.items} @{view('partials/product', item)} @{end} ``` The name is resolved like any view, so `partials/product` is `views/partials/product.html` (or inside the folder of the controller). Add an expiration and a key to cache the output: `@{view('menu', model, '5 minutes', 'menu')}`. ## Sections A section is HTML written in the view and printed in the layout, for example scripts of one page: ```html @{section scripts} @{end}

    Statistics

    ``` ```html @{body} @{section('scripts')} ``` Several blocks with the same name are joined. From a controller use `this.section('scripts', '')`. ## Helpers Total.js has view helpers for common HTML: `@{import()}`, `@{options()}`, `@{checked()}`, `@{text()}`, `@{json()}` and more. They are listed in the [Views reference](../../reference/views/). Define your own helpers in `DEF.helpers`, usually in a file in `definitions/`. In a helper `this` is the controller: ```js // definitions/helpers.js DEF.helpers.price = function(value, currency) { return value.format(2) + ' ' + (currency || 'EUR'); }; ``` Call it by its name: ```html @{price(item.price, 'USD')} ``` The output of a helper is not encoded; encode the values yourself when they come from users. `@{helper('price', item.price)}` does the same call. A helper used by only one view can be written inside it: ```html @{helper badge(text)} @{text} @{end} @{badge('New')} ``` ## Localization Text in `@(...)` is translated when the view is compiled, with the language of the request (`controller.language`, set by `DEF.onLocale`): ```html

    @(Products)

    ``` The translation comes from the resource file of the language. When there is none, the text stays as it is. `@(#key)` reads the key `key` from the resource directly. `@{resource('key')}` prints a key of `default.resource`, and `@{resource('en', 'key')}` a key of `en.resource`. ## CSS, JavaScript and images `@{import()}` writes the tags for static files. Relative names go to the static folders (`/css/`, `/js/`, `/img/`): ```html @{import('meta', 'head', 'default.css', 'ui.css', 'default.js', 'favicon.ico')} ``` `meta` prints the title and meta tags, `head` the tags added with `@{head()}`. Join files with `+` to merge them into one: `@{import('default.css + ui.css')}`. ## Title and meta tags Set the title and the description in the controller or in the view, and print them with `@{meta}` (or `@{import('meta')}`) in the layout: ```js function detail() { this.title('Apple'); this.description('Fresh apples from our farm'); this.view('detail', model); } ``` ```html @{title(model.name)} @{description(model.summary)} ``` The title gets ` - ` and the name of the app (`CONF.name`) at the end, unless `allow_custom_titles` is `true` in the config. ## Compilation and caching The first time a view is used, Total.js reads it, removes HTML comments, minifies the HTML with its inline CSS and JavaScript, translates `@(...)` and compiles it. In **release** mode the compiled view is kept in memory, once per language. In **debug** mode it is compiled on every request, so your changes appear without a restart. Put `@{nocompress html}` at the top of a view to keep its HTML as written (`css`, `js` and `all` also work). ## Render a view to a string `VIEW(name, [model], [layout], [repository], [language])` renders a view anywhere and returns HTML, without a layout unless you name one: ```js var html = VIEW('emails/order', order); ``` --- title: Configuration project: Total.js V4 version: 0.0.99 section: guides language: en license: MIT url: https://totaljs.es/docs/total-js-v4/0-0-99/guides/configuration/ updated: 2026-11-16T15:41:00.817Z --- # Configuration > How Total.js loads the config files and .env files, how values are parsed, and how to read and change them through CONF. Total.js reads the configuration of an application from plain text files in its root directory. Every value ends up in the global object `CONF`, which you can read from any file of the application. ## The config files Total.js loads up to two files when the application starts: | File | When | | --- | --- | | `config` | always | | `config-debug` | only in debug mode | | `config-release` | only in release mode | The mode-specific file is read after `config`, so its values replace the values from `config`. Keep the common settings in `config` and put only the differences in `config-debug` or `config-release`. ```text config config-debug config-release controllers/ definitions/ index.js ``` Before the config files, Total.js loads the `.env` files (see below). In debug mode the watcher restarts the application when you save one of the config files. ## Syntax Each line is `key : value`. Total.js splits the line at the first `:`, so a value can contain more colons, for example a URL. Spaces around the key and the value are removed. ```text // Application name : My Shop version : 1.2.0 author : Peter # Server default_port : 8000 default_timezone : Europe/Bratislava default_request_timeout : 5000 url : https://www.example.com ``` Rules: - Empty lines are skipped. - A line that starts with `#` or `//` is a comment. Do not put comments at the end of a line, they become part of the value. - A line without `:` is skipped. - The keys `debug` and `resources` are ignored in the file. ## How values are parsed Without a type, Total.js guesses the type from the value: | Value | Result | | --- | --- | | `8000` | the number `8000` | | `0.5` | the number `0.5` | | `true`, `false` | a boolean | | `0042` | the string `"0042"` (a leading zero keeps the string) | | `1,5` | the string `"1,5"` | | `-1` | the string `"-1"` | | anything else | a string | Many built-in keys have a fixed type. Keys like `default_request_timeout` or `default_request_maxlength` are always parsed as integers, and keys like `allow_gzip` or `allow_compile` are booleans: `true`, `1` and `on` mean `true`, everything else means `false`. `version`, `secret`, `secret_uid` and `secret_encryption` always stay strings. ## Typed values Put the type in brackets after the key to control the parsing: ```text limit (number) : -1 price (currency) : 9.90 code (string) : 0042 newsletter (bool) : enabled languages (array) : en, sk, de api (json) : { "url": "https://api.example.com", "retries": 3 } smtp (object) : { port: 465, secure: true } started (date) : 2024-01-01 database (env) : DATABASE_URL token (random) : 20 password (generate) : 16 ``` | Type | Result | | --- | --- | | `string` | the raw text | | `number`, `float`, `double`, `currency` | a number | | `boolean`, `bool` | `true` when the value contains `true`, `on`, `1` or `enabled` | | `array` | a list split by commas, trimmed | | `json` | parsed JSON | | `object`, `eval` | a JavaScript expression, evaluated | | `date`, `datetime`, `time` | a `Date` | | `env`, `environment` | the value of the environment variable with that name | | `random` | a new random string of the given length (default 10) on every start | | `generate`, `hash` | a random string that is created once and kept | Values for `generate` and `hash` are stored in `databases/config.json`, so they stay the same after a restart. Use them for secrets that must not change, but that you do not want to write into the file. A value that starts with `base64 ` or `hex ` is decoded first: ```text mail_password : base64 c2VjcmV0 ``` ## Environment variables Next to the config files you can keep `.env` files with `KEY=value` lines. Total.js loads `.env` and then `.env-debug` or `.env-release`. A variable that already exists in `process.env` is never replaced, so the real environment wins. ```text # .env DATABASE_URL=postgresql://user:pass@localhost:5432/shop APP_ROOT=/shop/ WELCOME="Hello\nworld" ``` Quotes around a value are removed and `\n` becomes a new line. Lines starting with `#` or `//` are comments. Read a variable in the config with the `(env)` type: ```text database (env) : DATABASE_URL default_root (env) : APP_ROOT ``` In code you can also use `process.env` directly. ## Reading the configuration `CONF` is a plain object. Read keys as properties: ```js exports.install = function() { ROUTE('GET /api/info/', info); }; function info() { this.json({ name: CONF.name, version: CONF.version, url: CONF.url }); } ``` Keys with a dot or other characters need the bracket notation, for example `CONF['security.txt']`. In views, `CONF` is available too: `@{CONF.name}`. You can assign a value in code, but the change is not written to the files and some keys are only read once at start (`default_port`, `directory_*`, `default_timezone`): ```js CONF.allow_gzip = false; ``` ## Changing the configuration at runtime `LOADCONFIG()` merges new values into `CONF`. It accepts an object, a string in the config syntax or an array of `{ id, type, value }` items, which is handy when the settings are stored in a database: ```js LOADCONFIG({ name: 'My Shop', allow_tms: true }); LOADCONFIG('name : My Shop\nlimit (number) : 50'); LOADCONFIG([ { id: 'mail_smtp', type: 'string', value: 'smtp.example.com' }, { id: 'limit', type: 'number', value: '50' }, { id: 'languages', type: '[string]', value: 'en, sk' } ]); ``` ## Options of the start script The start script can pass values with `options.config`. They are applied before the config files are read, so a key in `config` replaces them: ```js var options = {}; options.config = { name: 'Total.js' }; require('total4/debug')(options); ``` ## Threads An application started with threads loads `/threads//.env`, `/threads//config` and the mode-specific files of that folder after the files of the root. ## Common keys ```text name : My Shop version : 1.0.0 url : https://www.example.com secret : replace-me default_timezone : utc default_root : /shop/ default_request_maxlength: 1024 default_cors : example.com, app.example.com allow_tms : true mail_smtp : smtp.example.com mail_smtp_options : { port: 465, secure: true, user: 'info@example.com', password: '***' } mail_from : info@example.com logger : true ``` The reference lists every key with its default value. --- title: Authorization and sessions project: Total.js V4 version: 0.0.99 section: guides language: en license: MIT url: https://totaljs.es/docs/total-js-v4/0-0-99/guides/authorization/ updated: 2026-11-16T15:41:00.817Z --- # Authorization and sessions > Sign in requests with the AUTH() delegate, limit routes with the + and - flags, and keep sessions in cookies, tokens or the SESSION() store. Total.js signs in requests with one delegate. You register it with `AUTH()`, the framework calls it for every request (and for every WebSocket connection), and the delegate answers either "this is the user" or "nobody is signed in". Routes then decide with a flag whether they run for signed-in visitors, for anonymous visitors or for both. Put the delegate in a file in the `definitions/` folder, for example `definitions/auth.js`. ## The AUTH() delegate `AUTH(function($) { ... })` receives a `$` object with the request data: `$.cookie(name)`, `$.headers`, `$.query`, `$.ip`, `$.ua`, `$.url`, `$.websocket` and more. Call `$.success(user)` when the request belongs to a user, or `$.invalid()` when it does not: ```js // definitions/auth.js AUTH(function($) { var token = $.cookie('token'); if (!token) { $.invalid(); return; } var userid = DECRYPTREQ($.req, token, 'auth'); if (!userid) { $.invalid(); return; } NOSQL('users').one().where('id', userid).callback(function(err, user) { if (user) $.success(user); else $.invalid(); }); }); ``` The object you pass to `$.success()` becomes `controller.user` in actions, `$.user` in schemas and `client.user` in WebSockets. Keep it small: it is the same object for the whole request. `$.cancel()` stops the processing when you have already answered the request yourself, for example with a redirect from `$.res`. ## Route flags: + and - Start the URL with `+` for routes that need a signed-in user, and with `-` for routes only anonymous visitors can see. A route without a flag runs for both: ```js exports.install = function() { ROUTE('+GET /account/', account); // signed in ROUTE('-GET /login/', 'login'); // not signed in ROUTE('-POST /login/', login); ROUTE('+GET /logout/', logout); ROUTE('GET /', 'index'); // everybody }; ``` The prefix `🔒` works like `+`. In the flags array you can write `'authorize'`, `'authorized'` or `'logged'` instead of `+`, and `'unauthorize'`, `'unauthorized'` or `'unlogged'` instead of `-`. WebSocket routes accept the same prefixes. You can declare the same URL twice, once with `+` and once with `-`, and Total.js picks the route that matches the visitor. When a route exists only for the other state, the visitor gets `401`; when no route exists at all, `404`. A WebSocket that does not match is closed with `4001`. The flags only take effect when an `AUTH()` delegate is registered. Without one, the framework does not check them. ## Roles A flag that starts with `@` is a role. Total.js keeps it in `controller.route.flags` and treats the route as one that needs a signed-in user, but it does not compare roles for you. Check them in the action, for example with `UNAUTHORIZED()`: ```js exports.install = function() { ROUTE('GET /admin/', admin, ['@admin']); }; function admin() { var self = this; if (UNAUTHORIZED(self, 'admin')) return; self.view('admin'); } ``` `UNAUTHORIZED($, role1, role2, ...)` looks for the roles in `user.permissions` or `user.roles` (an array or an object). It returns `false` when the user has one of them, or has `sa` or `su` set to a truthy value. Otherwise it calls `$.invalid(401)` and returns `true`. ## Signing in and out with cookies A cookie holds an encrypted token. `ENCRYPTREQ()` encrypts a value together with the browser's user agent (and the IP address in strict mode), so a stolen cookie does not work in another browser: ```js function login() { var self = this; NOSQL('users').one().where('email', self.body.email).callback(function(err, user) { if (!user || user.password !== self.body.password.sha256()) { self.invalid('error-credentials'); return; } self.cookie('token', ENCRYPTREQ(self, user.id, 'auth'), '1 month', { httponly: true }); self.redirect('/account/'); }); } function logout() { var self = this; self.cookie('token', '', '-1 day'); self.redirect('/'); } ``` `controller.cookie(name)` reads a cookie and `controller.cookie(name, value, expires, [options])` writes one. Options are `domain`, `path` (default `/`), `secure`, `httponly` and `samesite`. `CONF.default_cookies_samesite` (default `'Lax'`) and `CONF.default_cookies_secure` (default `false`) set the defaults. ## The built-in session mechanism Pass an object to `AUTH()` instead of a function, and Total.js runs a cookie session for you. It decrypts the cookie, keeps the user data in memory and calls `onread` only when the data is not cached: ```js var opt = {}; opt.secret = 'a-long-random-key'; opt.cookie = 'session'; opt.expire = '10 minutes'; // how long user data stays in memory opt.ddos = 10; // failed attempts per IP before blocking opt.onread = function(meta, next) { // meta = { sessionid, userid, ip, ua } NOSQL('sessions').one().where('id', meta.sessionid).where('userid', meta.userid).callback(function(err, session) { if (!session) return next(); NOSQL('users').one().where('id', meta.userid).callback(next); }); }; opt.onlogout = function(session) { NOSQL('sessions').remove().where('id', session.sessionid); }; AUTH(opt); MAIN.auth = opt; ``` `AUTH()` adds methods to the object you pass, so keep a reference to it. Sign the user in with `opt.authcookie()`, and sign out with `opt.logout()`: ```js function login() { var self = this; // ... check the credentials, then: var sessionid = UID(); NOSQL('sessions').insert({ id: sessionid, userid: user.id, dtcreated: NOW }); MAIN.auth.authcookie(self, sessionid, user.id, '1 month'); self.redirect('/account/'); } function logout() { var self = this; MAIN.auth.logout(self); self.redirect('/'); } ``` After you change a user in the database, call `opt.refresh(userid)` to drop the cached data, so the next request reads it again, or `opt.update(userid, fn)` to change the cached data in place. ## SESSION(): a session store `SESSION([name])` returns a named session store (the default name is `default`). It keeps sessions in memory, writes their metadata to `databases/sessions.txt` and loads it again after a restart. The user data is not written to the file: after a restart, or after the data is released, the store asks the `ondata` delegate for it: ```js var session = SESSION(); session.ondata = function(meta, next) { // meta.sessionid, meta.id (user ID), meta.note, meta.settings NOSQL('users').one().where('id', meta.id).callback(next); }; AUTH(function($) { session.getcookie($, { name: 'sid', expire: '1 month', key: 'session-key', ddos: 5 }, function(err, user) { if (user) $.success(user); else $.invalid(); }); }); ``` Create the session when the user signs in, and remove it when the user signs out: ```js function login() { var self = this; // ... check the credentials, then: session.setcookie(self, { name: 'sid', id: user.id, data: user, expire: '1 month', key: 'session-key', note: self.ua }, function() { self.redirect('/account/'); }); } function logout() { var self = this; session.remove(self.sessionid); self.cookie('sid', '', '-1 day'); self.redirect('/'); } ``` For an API with tokens instead of cookies, use `session.settoken()` and `session.gettoken()`. Methods that end with `2` (`get2`, `set2`, `update2`, `remove2`, `release2`, `has2`, `contains2`) work with the user ID instead of the session ID, so you can update or end all sessions of a user at once. Every 10 minutes the framework removes expired sessions and releases the data of sessions unused for `CONF.allow_sessions_unused` (default `'-20 minutes'`). --- title: Encryption project: Total.js V4 version: 0.0.99 section: guides language: en license: MIT url: https://totaljs.es/docs/total-js-v4/0-0-99/guides/encryption/ updated: 2026-11-16T15:41:05.817Z --- # Encryption > Encrypt values with ENCRYPT() and DECRYPT(), bind them to the browser of a request with ENCRYPTREQ() and DECRYPTREQ(), and set the secret. `ENCRYPT(value, key)` and `DECRYPT(value, key)` encrypt any value with `CONF.secret` and your key. Objects are serialized to JSON, and `DECRYPT()` parses JSON by default; pass `false` as the third argument to get the plain string back. --- title: Middleware project: Total.js V4 version: 0.0.99 section: guides language: en license: MIT url: https://totaljs.es/docs/total-js-v4/0-0-99/guides/middleware/ updated: 2026-11-16T15:50:00.282Z --- # Middleware > Run code before routes and files with MIDDLEWARE(), in a route or for many routes at once with USE(). ## Defining a middleware `MIDDLEWARE(name, fn)` registers a function under a name. The function receives one argument, `$`, an instance of [MiddlewareOptions](../../reference/middleware/). Call `$.next()` to continue, or answer the request with `$.res` and do not call it: ```js MIDDLEWARE('apikey', function($) { if ($.headers['x-api-key'] === CONF.apikey) $.next(); else $.res.throw401(); }); ``` A middleware must always call `$.next()`, `$.cancel()`, or respond. If it does none of them, the request waits until it times out. `$.next(err)` with an `Error` or an `ErrorBuilder` responds with an error 500. `$.next(false)` and `$.cancel()` stop the chain without running the action. `NEWMIDDLEWARE()` is the same function under its newer name. Passing `null` as the function removes the middleware and unassigns it from all routes: ```js MIDDLEWARE('apikey', null); ``` Put middleware into the `/middleware/` directory (the config key `directory_middleware`). Each file is loaded like a controller, so register the middleware in `exports.install`: ```js // /middleware/apikey.js exports.install = function() { MIDDLEWARE('apikey', function($) { $.next(); }); }; ``` ## Using a middleware in a route Add the name with `#` (or `&`) to the flags of a route. The middleware runs after the route has been matched and before the action, in the order of the flags: ```js exports.install = function() { ROUTE('GET /api/products/', products, ['#apikey']); ROUTE('POST /api/orders/', orders, ['#apikey', '#logger']); }; ``` HTTP routes also accept the inline form in the URL: ```js ROUTE('GET /api/products/ &apikey', products); ``` An object in the flags becomes `$.options` in the middleware. In this way, one middleware can be configured for each route: ```js MIDDLEWARE('role', function($) { if ($.user && $.user.roles.includes($.options.role)) $.next(); else $.res.throw403(); }); exports.install = function() { ROUTE('GET /admin/', admin, ['#role', { role: 'admin' }]); }; ``` For routes, `$.controller` is the controller of the request and `$.params` holds the route parameters. See [Routing](../routing/) for the other flags. ## Global middleware `USE(name, [url], [types], [first])` assigns a middleware to many routes at once. Without `url` and `types`, it runs for **every** request, static files included, before the routing: ```js MIDDLEWARE('poweredby', function($) { $.res.setHeader('X-Server', 'MyApp'); $.next(); }); USE('poweredby'); ``` With `types`, the middleware runs only for one kind of request. `web` means dynamic routes, `file` means static files and file routes, and `websocket` means WebSocket routes (`all` or `*` means every request): ```js // Only dynamic routes USE('apikey', ['web']); // Only routes whose URL starts with /api/ USE('apikey', '/api/', ['web']); ``` With a `url`, the middleware is added to the routes that already exist and whose URL starts with it. `USE()` waits until the application is loaded, so it sees all the routes from controllers. `first: true` puts the middleware before the others. The third argument of `MIDDLEWARE(name, fn, types, first)` calls `USE(name, '', types, first)` for you: ```js MIDDLEWARE('cors', function($) { $.res.setHeader('Access-Control-Allow-Origin', '*'); $.next(); }, ['file']); ``` The order is: middleware of all requests, then middleware of static files (for files), or for routes the middleware of the route, then the middleware of all dynamic routes, then the action. --- title: Static files project: Total.js V4 version: 0.0.99 section: guides language: en license: MIT url: https://totaljs.es/docs/total-js-v4/0-0-99/guides/static-files/ updated: 2026-11-16T15:41:05.817Z --- # Static files > Serve the public directory, build the URLs of static files, map, merge and resize files, answer with file routes and localize static files. ## The public directory Every request whose path ends with a file extension is a static-file request. The framework looks for the file in `/public/` (the config key `directory_public`) and serves it when the extension is allowed in `static_accepts`. Other extensions answer 404. Paths that contain `../` are refused. ```text /public/css/default.css --> GET /css/default.css /public/img/logo.png --> GET /img/logo.png ``` Add an extension with `ACCEPT()`, or with `static_accepts_custom` in the config file: ```js ACCEPT('.glb', 'model/gltf-binary'); ``` ```text static_accepts_custom : glb, usdz ``` What happens to a file before it is sent: - `.js`, `.mjs` and `.css` files are minified when `allow_compile` is on (default). Files named like `*.min.js` or `*-min.css` are sent as they are. - Text types (HTML, CSS, JavaScript, JSON, XML, SVG, Markdown, plain text) are compressed with GZIP when `allow_gzip` is on and the client accepts it. - `.html` and `.htm` files are localized when `allow_localize` is on (default). - In release mode, the responses have `Cache-Control: public, max-age=11111111`, an `Expires` header one year ahead, `Last-Modified`, and an `ETag` built from `etag_version`. A request with a matching `If-Modified-Since` gets 304. In debug mode, files are sent with `no-cache`. The framework keeps the processed files in `/tmp/`. `TOUCH(url)` forgets one cached file, and `TOUCH()` forgets all: ```js TOUCH('/css/default.css'); ``` ## URLs of static files `F.public_js()`, `F.public_css()`, `F.public_image()` and the others build URLs from the config keys `static_url_script`, `static_url_style`, `static_url_image`, and so on. They also apply the `/versions` file, so you can change the URL of a file without changing your views: ```js F.public_js('app.js'); // /js/app.js F.public_image('logo.png'); // /img/logo.png ``` ```text // /versions /js/app.js : /js/app-2.js /css/style.css : auto ``` `auto` adds a hash of the file content to its name when the application starts. `PATH.public(filename)` gives the absolute path of a file in the public directory. ## Mapping, merging and resizing ```js // A URL served from another file or directory MAP('/favicon.ico', '~/assets/favicon.ico'); // Several files served as one MERGE('/js/bundle.js', '/js/a.js', '/js/b.js'); // /img/small/*.jpg is made from /public/img/*.jpg RESIZE('/img/small/*.jpg', function(image) { image.resize(200, 200); image.quality(80); }, ['/img/']); ``` ## File routes A file route answers static-file requests with your own function. Use `ROUTE('FILE ...')` or `FILE()`. The action receives `req` and `res`, not a controller: ```js exports.install = function() { ROUTE('FILE /docs/*.pdf', pdf, ['#apikey']); ROUTE('FILE /thumbnails/*.jpg', thumbnail); ROUTE('FILE /favicon.ico', PATH.public('img/favicon.ico')); }; function pdf(req, res) { res.file(PATH.root('documents/' + U.getName(req.uri.pathname)), 'document.pdf'); } function thumbnail(req, res) { res.image(PATH.public('photos/' + U.getName(req.uri.pathname)), function(image) { image.resize(150, 150); }); } ``` The URL can end with `*.ext` (one extension), `*` or `*.*` (any file under the path), or a full file name. When the second argument is a string, the route sends that file (an absolute path) with `res.file()`, or proxies an `http(s)://` URL. In a file route, use `res.file()`, `res.image()`, `res.filefs()`, `res.imagefs()`, `res.stream()`, or `res.continue()` to serve the file from `public/` as usual. Middleware in file routes goes in the flags array (`['#name']`). `FILE404(fn)` handles static files that do not exist: ```js FILE404(function(req, res) { if (req.extension === 'png') { res.file(PATH.public('img/empty.png')); return true; } }); ``` ## Localized static files `LOCALIZE(url)` sends the files under `url` through the translator, so `@(Text)` markers become texts in the language of the request. Set the language with `LOCALIZE(fn)`: ```js LOCALIZE(function(req, res) { return (req.headers['accept-language'] || 'en').substring(0, 2); }); LOCALIZE('/templates/*.html'); LOCALIZE('/texts/*.md', ['nocompress']); ``` ## Change content before compiling `MODIFY([filename], fn)` registers a function that changes the content of views, styles, scripts and localized static files before Total.js compiles them. It changes only the copy in memory, never the file on the disk. Return the new content: ```js MODIFY(function(type, filename, value) { if (type === 'view') return value.replace('{year}', NOW.getFullYear() + ''); }); ``` --- title: WebSockets project: Total.js V4 version: 0.0.99 section: guides language: en license: MIT url: https://totaljs.es/docs/total-js-v4/0-0-99/guides/websockets/ updated: 2026-11-16T15:41:05.817Z --- # WebSockets > Declare WebSocket routes, handle clients and messages in the WebSocket controller, and connect to WebSocket servers with WEBSOCKETCLIENT(). A WebSocket route keeps a connection open between the browser and the server. In Total.js you declare it with `ROUTE()` and the `SOCKET` method. The action of the route does not answer a request: it runs **once**, when the first client connects, and its `this` is a **WebSocket controller** shared by every client of that route. ```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) { // Send the message to everybody self.send({ type: 'message', from: client.id, body: message.body }); }); self.on('close', function(client) { self.send({ type: 'leave', id: client.id }); }); } ``` The full list of properties and methods is in the reference of [WebSockets](../../reference/websockets/). ## Declaring a route `ROUTE('SOCKET /path/', action, [flags], [length])` registers the route. `WS` and `WSS` are accepted as aliases of `SOCKET`. A `+` before the method allows only signed-in users and a `-` only anonymous users, as in other routes: ```js exports.install = function() { ROUTE('+SOCKET /notifications/', notifications); ROUTE('SOCKET /live/{room}/', live, ['json'], 64); }; function live(room) { // room === this.params.room } ``` Dynamic parts of the URL arrive as arguments of the action and in `this.params`. The `length` argument (or a number in the flags) is the maximum size of one message in **kB**. The default comes from `CONF.default_websocket_maxlength` (`2` kB). A bigger frame closes the connection with code `1009`. ## Flags | Flag | Meaning | | --- | --- | | `json` | Messages are JSON (the default). Incoming messages are parsed, outgoing objects are serialized. | | `text` or `plain` | Messages are strings. | | `binary` | Messages are binary; `message` receives a `Buffer`. | | `raw` | Turns off `json` and `binary`; messages are handled as text. | | `buffer` | The `message` event always receives the raw `Buffer`. | | `authorize`, `logged` | Only signed-in users (the same as `+`). | | `unauthorize`, `unlogged` | Only anonymous users (the same as `-`). | | `@role` | Marks a role; the route also becomes `authorize`. | | `http://…`, `https://…` | Allowed origins. The `Origin` header must contain one of them. | | `#name` or `&name` | Middleware run before the connection is accepted. | | `id:name` | An identifier of the route. | | `debug`, `release`, `http`, `https` | Limit the route to a mode or a protocol. | | any other word | A required sub-protocol: the client must send it in `Sec-WebSocket-Protocol`. | | a number | The maximum message size in kB. | | an object | Options passed to the middleware. | ```js ROUTE('SOCKET /api/', api, ['json', 'https://www.example.com', 'chat'], 128); ``` This route accepts only clients from `https://www.example.com` that ask for the `chat` sub-protocol, and messages up to 128 kB. ## How connections are grouped Every route has one controller per URL. The first client creates it and runs the action; later clients on the same URL join the existing controller, and the action is not called again. That is why the action registers events instead of answering. ```js function counter() { var self = this; self.on('open', function() { self.send({ online: self.online }); }); self.on('close', function() { self.send({ online: self.online }); }); } ``` Without more code the controller stays in memory after the last client leaves. Call `this.autodestroy()` to destroy it 5 seconds after the last client disconnects; the next client creates a new one and the action runs again: ```js function room() { var self = this; self.autodestroy(function() { console.log('Room closed:', self.url); }); } ``` ## Receiving and sending With the default `json` flag, `message` receives a parsed object; invalid JSON is ignored. `client.send(obj)` sends to one client and `this.send(obj)` sends to all clients of the controller. The second argument of `this.send()` filters the receivers: ```js function chat() { var self = this; self.on('message', function(client, message) { // Everybody except the sender self.send(message, function(c) { return c !== client; }); // Only users of one company self.send(message, function(c, msg, params) { return c.user && c.user.companyid === params.companyid; }, { companyid: client.user.companyid }); }); } ``` `this.find(fn)` returns the first client for which `fn` returns `true`, and `this.clients()` returns all clients as an array. `this.online` is the number of connected clients and `this.connections` maps client ids to clients. ## The client of a connection Every connected client has `id`, `ip`, `query`, `headers`, `url`, `ua`, `user`, `session`, `language`, `mobile` and `protocol`. `user` is the value accepted by your `AUTH()` delegate: ```js // definitions/auth.js AUTH(function($) { // $.websocket is true for WebSocket connections var token = $.query.token || $.cookie('token'); if (token === 'secret') $.success({ id: 1, name: 'Peter' }); else $.invalid(); }); // controllers/default.js exports.install = function() { ROUTE('+SOCKET /private/', privatechannel); }; function privatechannel() { this.on('open', function(client) { client.send({ hello: client.user.name }); }); } ``` A client that fails authorization is closed with code `4001`, a URL without a route with `4004`, and invalid URL parameters with `4000`. `client.close([message], [code])` closes one client and `this.close([message], [code])` closes all of them. The default code is `1000`. ## Ping and stale connections The framework pings every connected client every `CONF.default_interval_websocket_ping` milliseconds (default `20000`). The answer sets `client.latency`. A client that did not answer, or whose latency is higher than `CONF.default_websocket_maxlatency` (default `2000` ms), is closed at the next round. Set `default_websocket_maxlatency` to `0` to turn the pinger off. ## WebSocket API A route can process `API` routes over the socket. Declare the API with `@name` and use the same name in the socket route: ```js exports.install = function() { ROUTE('API @chat -messages_list *Messages --> list'); ROUTE('API @chat +messages_create *Messages --> create'); ROUTE('SOCKET /chat/ @chat'); }; ``` A `SOCKET` route with `@name` and no action calls `this.api('@name')` and `this.autodestroy()` for you. The client sends `{ TYPE: 'api', callbackid: '1', data: { schema: 'messages_list', data: {} } }` and gets the same object back with `success: true` and `data`, or `error: true` and the errors. ## Connecting from the server `WEBSOCKETCLIENT()` creates a WebSocket client, for example to connect one Total.js app to another: ```js WEBSOCKETCLIENT(function(client) { client.options.reconnect = 5000; client.headers['x-token'] = 'secret'; client.on('open', function() { client.send({ type: 'hello' }); }); client.on('message', function(message) { console.log(message); }); client.on('close', function(code, message) { console.log('Closed', code, message); }); client.connect('ws://127.0.0.1:8000/chat/'); }); ``` `client.options.type` is `json` by default; use `text`, `binary` or `buffer` for other data. The client reconnects 3 seconds after the connection is lost (`options.reconnect`); `client.close()` stops reconnecting and `client.destroy()` frees the client. `client.api(schema, data, callback)` calls the WebSocket API of the server: ```js client.api('messages_list', { page: 1 }, function(err, response) { console.log(err, response); }); ``` ## Configuration | Key | Default | Meaning | | --- | --- | --- | | `allow_websocket` | `true` | Enables WebSocket routes. | | `allow_websocket_compression` | `true` | Allows `permessage-deflate` compression. | | `default_websocket_maxlength` | `2` | Maximum message size in kB. | | `default_websocket_maxlatency` | `2000` | Maximum ping latency in ms; `0` disables the pinger. | | `default_interval_websocket_ping` | `20000` | Interval of the ping in ms. | | `default_websocket_encodedecode` | `false` | Encodes messages with `encodeURIComponent()` and decodes them. | --- title: NoSQL database project: Total.js V4 version: 0.0.99 section: guides language: en license: MIT url: https://totaljs.es/docs/total-js-v4/0-0-99/guides/nosql/ updated: 2026-11-16T15:41:05.817Z --- # NoSQL database > The embedded file database of Total.js 4: NOSQL() for JSON documents and TABLE() for rows with a schema, both stored in the databases/ folder and queried with the same builder. Total.js 4 has an embedded file database. `NOSQL(name)` stores JSON documents, `TABLE(name)` stores rows with a fixed set of columns. Both need no server and no installation: the data lives in plain text files in the `databases/` folder of the app, and both use the same query builder. ## Files and storage | Call | File | | --- | --- | | `NOSQL('users')` | `databases/users.nosql` (one JSON document per line) | | `TABLE('users')` | `databases/users.table` (a header with the columns, then one row per line, values separated by `\|`) | Next to the data file the engine can create `users.nosql.bk` with backups of changed documents (see `builder.backup()`). The folder comes from the `directory_databases` config key (`/databases/` by default) and is created when it is needed. A name that starts with `~` is an absolute path: `NOSQL('~/www/data/logs.nosql')`. Such an instance is not cached, so every call creates a new one. Other instances are created once and then reused. Operations are queued and run one after another, so you can call them from anywhere without locking. Every call returns at once; the work starts in the next tick, which gives you time to add conditions to the builder. ## Inserting documents ```js NOSQL('users').insert({ id: UID(), name: 'Peter', email: 'peter@example.com', age: 32, created: NOW }).callback(function(err, count) { // count: 1 }); ``` With `true` as the second argument the document is inserted only when no document matches the conditions you add to the returned builder. The response is `0` when it already exists: ```js NOSQL('users').insert(model, true).where('email', model.email).callback(function(err, count) { if (!count) console.log('The email is already registered'); }); ``` ## Reading `find()` returns an array, `read()` one document, `count()` an object `{ count: Number }` and `list()` a page of results: ```js NOSQL('users').find().where('age', '>', 18).sort('name').fields('id,name,email').take(20).callback(function(err, items, meta) { // meta: { count, counter, scanned, duration } }); NOSQL('users').read().id('3ab5k001pt51d').callback(function(err, user) { // user is the document or nothing }); NOSQL('users').count().where('active', true).callback(function(err, response) { // response.count }); ``` `read()` reads the file from the end, so with several matches it returns the newest one. `find2()` also reads from the end and returns the newest documents first. ## Conditions All conditions are joined with AND. Field names can use dots for nested objects (`address.city`). ```js var builder = NOSQL('products').find(); builder.where('price', '>=', 10); // =, ==, !=, <>, >, <, >=, <= builder.where('category', 'books'); // two arguments: equality builder.in('tags', ['new', 'sale']); // the field (or one of its items) is in the array builder.notin('status', ['deleted']); builder.between('price', 10, 100); builder.search('name', 'total'); // case-insensitive substring builder.search('code', 'AB', 'beg'); // 'beg' = starts with, 'end' = ends with builder.contains('photos'); // not empty builder.empty('note'); // empty, null or an empty array builder.year('created', 2022); builder.month('created', '>=', 6); builder.or(function() { builder.where('stock', '>', 0); builder.where('preorder', true); }); builder.callback(console.log); ``` `rule(code, [arg])` adds a raw JavaScript condition. The code sees `doc` and `arg`: ```js NOSQL('users').find().rule('doc.age > arg.min && doc.roles.includes(\'admin\')', { min: 18 }).callback(console.log); ``` ## Sorting, fields and pages `sort('name')` sorts ascending, `sort('created_desc')` descending, `sort('country,name_desc')` by several fields. `fields('id,name')` returns only these fields, `fields('-password')` removes a field, and `fields('name as title')` renames one. `take()` and `skip()` limit the result. `paginate(page, limit, [maxlimit])` takes a page number that starts at `1`, which fits values from the query string. `list()` returns everything a grid needs: ```js NOSQL('users').list().where('active', true).sort('name').paginate($.query.page, $.query.limit, 50).callback(function(err, response) { // response: { page, pages, limit, count, items } }); ``` ## Updating `update()` (aliases `modify()` and `mod()`) changes only the fields you pass; other fields of the document stay. A prefix in the key performs an operation with the stored value: | Key | Operation | | --- | --- | | `name` | Set the value | | `+count`, `-count`, `*count`, `/count` | Add, subtract, multiply, divide | | `!active` | Toggle a boolean (the value is ignored) | | `>max`, ``, or call `alter()`: ``` table_users : id:string(20)|name:string(50)|age:number|active:boolean|created:date ``` ```js TABLE('users').alter('id:string(20)|name:string(50)|age:number|active:boolean|created:date'); TABLE('users').insert({ id: UID(), name: 'Anna', age: 28, active: true, created: NOW }); TABLE('users').find().where('active', true).callback(console.log); ``` Types are `string`, `string(length)`, `number`, `boolean` (or `bool`), `date` and `object`. Columns can be separated with `|`, `,` or `;`. Only declared columns are stored. When every column has a size (a `string` with a length, `number`, `boolean`, `date`), rows have a fixed width and updates are written in place. Changing the schema with `alter()` rewrites existing rows; `newname=oldname:type` copies values from an old column. ## Performance options `textdb_inmemory` in the config keeps databases smaller than the given number of megabytes in memory for reading. `textdb_worker : true` runs the engine in a worker thread while the web server is running. --- title: Localization project: Total.js V4 version: 0.0.99 section: guides language: en license: MIT url: https://totaljs.es/docs/total-js-v4/0-0-99/guides/localization/ updated: 2026-11-16T15:41:05.817Z --- # Localization > Translate views, static files, errors and e-mails with resource files and a language for each request. Total.js translates text with **resource files**. A resource file is a plain text file with `key : value` lines in the `resources/` directory. The name of the file is the name of a language: `resources/sk.resource` holds the Slovak texts, `resources/de.resource` the German ones. `resources/default.resource` is the fallback for every language. You mark text in views with `@(Text)`, choose the language of each request in a delegate, and the framework does the rest: it translates views, static HTML files, error messages and e-mail subjects. The exact reference is in [Localization](../../reference/localization/). ## Resource files ```text // resources/sk.resource # Comments start with // or # title : Moja stránka welcome : Vitajte error-email : Zadajte platnú e-mailovú adresu ``` Rules of the format: - One key and one value per line, separated by ` : `. Keep a space after the colon: the parser skips the first character after `:`. - Lines that start with `//` or `#` are comments; empty lines are ignored. - The value is one line. Leading and trailing spaces are removed. - Keys made of `T` and a base-36 hash of the text are translations of `@(Text)`. You do not write them by hand: the `total4 translate` command creates them (see below). `RESOURCE()` reads a value by its key: ```js var title = RESOURCE('sk', 'title'); // "Moja stránka" var name = RESOURCE('title'); // reads resources/default.resource ``` When a key is missing in `sk.resource`, the value from `default.resource` is used. When it is missing there too, the result is an empty string. A resource with one name can come from several places. The framework joins them in this order, and a later line with the same key wins: 1. files registered with `F.register('/path/to/sk.resource')` (useful for packages and modules), 2. `tmp/sk.resource`, written by `LOADRESOURCE()`, 3. `resources/sk.resource`. Parsed resources are cached in `F.resources`. The cache is cleared every 20 minutes (`default_interval_clear_resources`), so changed files are read again without a restart. ## Choosing the language of a request The language is a string: the name of the resource file without the extension. You set it with `LOCALIZE()` and a function; the function becomes `DEF.onLocale`: ```js // definitions/localization.js LOCALIZE(function(req, res) { var lang = req.query.language || req.cookie('language') || (req.headers['accept-language'] || '').substring(0, 2); switch (lang) { case 'sk': case 'de': return lang; } return 'en'; }); ``` The function is called once per request and must return the language. The framework calls it: - for static files, with `true` as the third argument, - for routes, after authorization, so `req.user` is already known when you use `AUTH()`, - for WebSocket connections, with `req` only. The returned value is stored in `req.$language`. From there it goes to `controller.language`, `client.language` in WebSockets and `$.language` in schemas, operations and middleware. With the built-in session authorization of `AUTH()`, use the `locale` option to take the language from the user: ```js AUTH({ secret: 'my-secret', cookie: 'session', onread: function(meta, next) { NOSQL('users').one().id(meta.userid).callback(next); }, locale: function(user, req) { return user ? user.language : 'en'; } }); ``` ## Translating views Write the text of the default language inside `@(...)`: ```html

    @(Products)

    @(#welcome)

    @{resource(language, 'title')}

    Language: @{language}

    ``` - `@(Text)` is replaced with the translation from the resource of `controller.language`. The key is `T` plus a hash of the text. When there is no translation, the original text stays. - `@(#key)` reads `key` from the resource directly. - `@{resource([name], key)}` prints a resource value, HTML-encoded. In views, `language` holds the current language. - When `@(...)` is inside quotes, quotes in the translation are escaped, so it is safe in attributes and in inline scripts. - `@{notranslate}` (or `@{nolocalize}`) anywhere in a view turns translation off for that view. Translation happens when the view is compiled, so a view is compiled once for each language. In release mode the compiled views are cached; in debug mode they are compiled again on every render. When no file exists for the language (for example `fr.resource` is missing), `@(Text)` keeps the original text. You can change the language for one response before you render the view: ```js exports.install = function() { ROUTE('GET /{lang}/', home); }; function home(lang) { this.language = lang; this.view('index'); } ``` ## Static files With `allow_localize: true` (the default), `.html` and `.htm` files from `public/` are translated like views: `@(Text)` is replaced and the result is cached per language in release mode. `LOCALIZE(url, [flags], [minify])` translates other files too: ```js LOCALIZE('/docs/*.md'); LOCALIZE('/templates/*.html', ['nocompress']); ``` ## Translating in code ```js TRANSLATE('sk', 'Add to cart'); // the translation of @(Add to cart), or the text TRANSLATE('sk', '#welcome'); // the same as RESOURCE('sk', 'welcome') TRANSLATOR('sk', '@(Products)'); // replaces every @(...) in a string ``` Dates use resources for the names of months and days. `new Date().format('dddd d. MMMM yyyy', 'sk')` reads `January`…`December` and `Sunday`…`Saturday` as keys from `sk.resource`. ## Error messages Errors of schemas and operations are translated with the language of the request: ```js // resources/en.resource // error-email : Please enter a valid e-mail address NEWSCHEMA('Contact', function(schema) { schema.define('email', 'Email', true); schema.addWorkflow('send', function($) { if (!$.model.email.endsWith('.com')) { $.invalid('error-email'); return; } $.success(); }); }); ``` - A short name without spaces, colons or commas (`error-email`) is a resource key. - `@(Text)` is translated like in views: `$.invalid('@(The e-mail is taken)')`. - Any other text is sent as it is. Without a translation the message is `The field "name" is invalid`. Use `schema.setResource()` and `schema.setPrefix()` to read errors from a fixed resource or with a key prefix, and `ErrorBuilder.resource()` for your own `ErrorBuilder`. ## E-mails `MAIL()` and `HTMLMAIL()` take a language. The subject is translated, and the view of `MAIL()` is rendered in that language: ```js MAIL(user.email, '@(Order confirmation)', 'mails/order', order, user.language, function(err) { err && console.log(err); }); ``` `controller.mail()` uses the language of the controller. ## Loading translations at runtime `LOADRESOURCE()` writes a resource into `tmp/` and clears its cache. You can pass an object, an array or a URL: ```js LOADRESOURCE('sk', { title: 'Moja stránka', welcome: 'Vitajte' }); LOADRESOURCE('sk', 'https://example.com/translations/sk.json'); LOADRESOURCE('https://example.com/translations/'); // { sk: {...}, de: {...} } ``` ## The translate tool The `total4` command creates and maintains resource files. Run it in the root of the application: | Command | What it does | | --- | --- | | `total4 translate` | Finds every `@(Text)` in `.html`, `.js` and sitemap files, and keys of `$.invalid('key')`, and writes `translate.resource` | | `total4 translate "Text"` | Prints the key of one text | | `total4 translate ` | Creates `translate.resource` from a text file, one text per line | | `total4 translatecsv` | Writes the texts into `translate.csv` (`Hash;Text;Translation`) | | `total4 csv ` | Creates a resource from the first two columns of a CSV | | `total4 diff ` | Writes `-diff.txt` with keys to add to and to remove from the target | | `total4 merge ` | Writes `-merged.txt`: the target with values taken from the source | | `total4 clean ` | Writes `-cleaned.txt` with aligned keys | A typical workflow: run `total4 translate`, copy `translate.resource` to `resources/sk.resource`, translate the values, and after the next change run `total4 diff translate.resource resources/sk.resource` to find new texts. --- title: HTTP requests project: Total.js V4 version: 0.0.99 section: guides language: en license: MIT url: https://totaljs.es/docs/total-js-v4/0-0-99/guides/http-requests/ updated: 2026-11-16T15:41:20.819Z --- # HTTP requests > Call other HTTP services with RESTBuilder, REQUEST() and DOWNLOAD(). Total.js has three tools for calling other HTTP services from your application: - **`RESTBuilder`** builds a request step by step, sends it and parses the answer (JSON, XML or URL-encoded). Use it for REST APIs. - **`REQUEST(options, [callback])`** is the low-level HTTP client that `RESTBuilder` uses. It returns the raw body, or a stream. - **`DOWNLOAD(url, filename, [callback], [timeout])`** saves a response straight into a file. All three are global: you can use them in controllers, schemas, definitions and modules without `require()`. ## RESTBuilder A static method creates the builder for the HTTP method you need. The data you pass to `POST`, `PUT`, `PATCH` and `DELETE` is sent as JSON; the data of `GET` becomes the query string. ```js RESTBuilder.GET('https://api.example.com/products/', { page: 1 }).callback(function(err, response, output) { if (err) { console.log('Error:', err); return; } console.log(response); // the parsed body console.log(output.status); // the HTTP status code }); RESTBuilder.POST('https://api.example.com/orders/', { product: 'P01', count: 2 }).callback(function(err, response) { console.log(response); }); ``` The callback receives three arguments: | Argument | What it contains | | --- | --- | | `err` | An error, or `null` | | `response` | The parsed body: an object for JSON, XML and URL-encoded answers, otherwise an empty object | | `output` | Details: `value`, `response` (the raw body), `status`, `headers`, `hostname`, `origin`, `cache` and the method `cookie(name)` | A status code `400` or higher is **not** an error by default: check `output.status`, or call `strict()` to get the status code as `err`. When the service answers with a Total.js error array (`[{ name, error }]`), `err` is an `ErrorBuilder` with those errors. ### Promises `promise()` sends the request and returns a promise of the parsed body. Pass `$` (the options of a schema operation) and the error goes to `$.invalid()` instead of rejecting the promise. ```js NEWSCHEMA('Weather', function(schema) { schema.action('current', { name: 'Current weather', action: async function($) { var data = await RESTBuilder.GET('https://api.example.com/weather/', { city: 'Bratislava' }).promise($); $.callback(data); } }); }); ``` `callback()` without a function also returns a promise. ### Building the request Every method returns the builder, so you can chain them. Nothing is sent until you call `callback()`, `exec()`, `promise()` or `stream()`. ```js RESTBuilder.make(function(builder) { builder.url('https://api.example.com/invoices/'); builder.method('POST'); builder.header('X-Token', CONF.token); builder.auth('user', 'password'); builder.timeout(5000); builder.json({ number: '2024001', total: 120 }); builder.callback(function(err, response, output) { console.log(output.status, response); }); }); ``` | Area | Methods | | --- | --- | | Address and method | `url()`, `method()`, `get()`, `post()`, `put()`, `patch()`, `delete()`, `head()` | | Headers | `header()`, `type()`, `accept()`, `auth()`, `referrer()`, `xhr()` | | Body | `json()`, `urlencoded()`, `xml()`, `plain()`, `raw()`, `set()`, `rem()`, `file()` | | Cookies | `cookie()`, `cookies()`, `cook()` | | Connection | `timeout()`, `keepalive()`, `proxy()`, `cert()`, `insecure()`, `nodnscache()`, `redirect()`, `unixsocket()` | | Response | `strict()`, `noparse()`, `schema()`, `map()`, `convert()`, `cache()`, `progress()` | | Sending | `callback()`, `exec()`, `promise()`, `stream()` | The default timeout is 10 seconds. The builder sends `User-Agent: Total.js/v...` and accepts JSON, text and XML. ### Uploading files `file()` adds a file and switches the request to `multipart/form-data` (a `GET` becomes a `POST`). The content can be a path, a `Buffer` or a URL that the framework downloads and forwards. `set()` adds plain form fields. ```js RESTBuilder.POST('https://api.example.com/upload/') .file('file', 'report.pdf', PATH.databases('report.pdf')) .set('folder', 'reports') .callback(function(err, response) { console.log(err, response); }); ``` ### Shaping the response - `schema(name)` validates the response with a schema and returns the model. A status code `400` or higher is an error here. - `map('id:number,name:string')` keeps only the listed fields and converts them; `id:number:itemid` also renames `id` to `itemid`. - `convert('price:number,date:date')` converts fields of the response with `CONVERT()`. - `cache('5 minutes')` caches a successful (`200`) response in `F.cache`. ```js RESTBuilder.GET('https://api.example.com/users/').map('id:number,name:string').callback(function(err, users) { // users === [{ id: 1, name: 'Peter' }, ...] }); ``` ### Calling Total.js API endpoints `RESTBuilder.API(url, operation, [data])` sends a `POST` with the JSON `{ schema: operation, data: data }`, the format of Total.js API routes: ```js RESTBuilder.API('https://app.example.com/admin/', 'products_list', { search: 'Bike' }).callback(function(err, response) { console.log(response); }); ``` ### Global changes `RESTBuilder.upgrade(fn)` runs `fn(builder)` for every builder before it sends the request, for example to add a header to all requests. `RESTBuilder.addTransform(name, fn, [isDefault])` registers a function that changes every parsed response. ## REQUEST() `REQUEST(options, [callback])` sends one HTTP request. The body you send must be a string or a `Buffer`; the response body is a string for text and `application/*` types, otherwise a `Buffer`. Without a callback it returns a promise. ```js REQUEST({ url: 'https://api.example.com/status/', method: 'GET', timeout: 5000 }, function(err, response) { if (err) return; console.log(response.status, response.headers, response.body); }); var response = await REQUEST({ url: 'https://api.example.com/items/', method: 'POST', type: 'json', body: JSON.stringify({ name: 'Item' }) }); ``` With `custom: true` you get `response.stream` (the incoming message) instead of the body. The framework follows `301` and `302` redirects and copies their cookies to the next request; `noredirect: true` turns that off. ## DOWNLOAD() `DOWNLOAD(url, filename, [callback], [timeout])` writes the response into a file. A relative URL (`/sitemap.xml`) is requested from your own running application. ```js DOWNLOAD('https://www.example.com/logo.png', PATH.public('img/logo.png'), function(err, response) { console.log(err, response.status); }); ``` ## Proxy `CONF.default_proxy` sends every request through a proxy server, except requests to `localhost`, `127.0.0.1` and `0.0.0.0`. `proxy(url)` and the `proxy` option set a proxy for one request. The value can contain credentials: `http://user:password@proxy.example.com:8080`. The configuration key `default_restbuilder_timeout` (default `10000`) is the timeout of `REQUEST()` calls without their own `timeout`. --- title: Sending email project: Total.js V4 version: 0.0.99 section: guides language: en license: MIT url: https://totaljs.es/docs/total-js-v4/0-0-99/guides/mail/ updated: 2026-11-16T15:41:20.819Z --- # Sending email > Send email from views, HTML or logs with the SMTP server of the configuration, and send messages to any server with the Mail module. Total.js sends email over SMTP with its own client, the `Mail` module. The global functions `MAIL()`, `HTMLMAIL()` and `LOGMAIL()` and the controller method `controller.mail()` create a message from the configuration, send it on the next tick and return it, so you can still add recipients or attachments. The full list of functions, options and message methods is in the reference of [Mail](../../reference/mail/). ## Configuration Put the SMTP server and the sender in the `config` file: ```text mail_smtp : smtp.example.com mail_smtp_options : { port: 465, secure: true, user: 'info@example.com', password: 'secret' } mail_from : info@example.com mail_reply : support@example.com ``` | Key | What it does | | --- | --- | | `mail_smtp` | The host name of the SMTP server | | `mail_smtp_options` | The connection options, a JavaScript object written as text | | `mail_from` | The sender address; the sender name is the `name` key of the configuration | | `mail_reply` | A `Reply-To` address added to every message | | `mail_cc`, `mail_bcc` | A copy of every message for this address | | `mail_smtp_keepalive` | How long a connection stays open for the next messages (default `10 minutes`) | The options of `mail_smtp_options`: | Option | Default | Description | | --- | --- | --- | | `port` | `25`, or `465` with `secure` | The port of the server | | `secure` | `false` | Connects with TLS from the start (SMTPS) | | `user`, `password` | `''` | The login; the client uses `AUTH LOGIN` or `AUTH PLAIN`, as the server offers | | `token` | `''` | An OAuth 2.0 access token, sent with `AUTH XOAUTH2` together with `user` | | `tls` | `null` | Options for the TLS connection; the client upgrades the connection with `STARTTLS` | | `timeout` | `10000` | The socket timeout in milliseconds | When the server announces ESMTP and you set `user` and `password`, the client upgrades a plain connection with `STARTTLS` before it signs in, so port `587` works without `secure`: ```text mail_smtp_options : { port: 587, user: 'info@example.com', password: 'secret' } ``` Without `mail_smtp`, the framework uses `smtp.` plus the domain of the sender address. You can also check a server and save it at run time with `Mail.use()`: ```js Mail.use('smtp.example.com', { port: 465, secure: true, user: 'info@example.com', password: 'secret' }, function(err) { // On success, CONF.mail_smtp and CONF.mail_smtp_options are set err && console.log('SMTP is not available', err); }); ``` ## A message from a view `MAIL(address, subject, view, [model], [language], [callback])` renders a view from `views/` without a layout and sends the result as HTML. The model is available as `model` in the view: ```js MAIL('peter@example.com', 'Welcome', 'mails/welcome', { name: 'Peter' }, function(err) { err && console.log('Not sent', err); }); ``` ```html

    Hello @{model.name},

    @(your account is ready.)

    ``` With `language`, the subject and the `@(...)` texts of the view are translated to this language. A view name such as `=green/mails/welcome` takes the view from the theme `green`. Inside an action, `this.mail()` does the same with the language of the request: ```js exports.install = function() { ROUTE('POST /api/orders/', order); }; function order() { var self = this; self.mail(self.body.email, '@(Your order)', 'mails/order', self.body); self.success(); } ``` `address` can be one address or an array of addresses. Each address in the array becomes a `To` recipient. ## Raw HTML and logs `HTMLMAIL()` sends HTML that you already have. When the body has no `` element, it is wrapped in a full HTML document with the subject as the title: ```js HTMLMAIL('peter@example.com', 'Reset password', '

    Your code is ' + code + '.

    '); ``` `LOGMAIL()` is for notifications to yourself. An object is serialized as JSON, and the subject defaults to the name and the version of the application: ```js LOGMAIL('admin@example.com', 'New order', { id: order.id, price: order.price }); ``` ## Changing the message All these functions return the message. It is sent on the next tick, so you can change it in the same call stack: ```js MAIL('peter@example.com', 'Invoice', 'mails/invoice', invoice) .cc('accounting@example.com') .bcc('archive@example.com') .reply('billing@example.com', true) .attachment(PATH.root('invoices/' + invoice.id + '.pdf'), 'invoice.pdf'); ``` An address can contain a name: `'Peter Sirka '`, or pass the name as the second argument of `to()` and `cc()`. The `clear` argument of `to()`, `cc()`, `bcc()` and `reply()` removes the addresses added before, for example the `mail_reply` address from the configuration. `attachment(filename, [name], [contentid])` adds a file from the disk; `attachmentfs(storage, id, [name], [contentid])` adds a file from a `FILESTORAGE()`. With `contentid`, the file is an inline attachment that the HTML refers to as `cid:`: ```js var message = HTMLMAIL('peter@example.com', 'Report', ''); message.attachment(PATH.public('img/chart.png'), 'chart.png', 'chart1'); ``` To prepare a message asynchronously, stop the automatic sending with `manually()` and call `send2()` when it is ready: ```js var message = HTMLMAIL('peter@example.com', 'Your export', '

    The file is attached.

    '); message.manually(); createexport(function(filename) { message.attachment(filename, 'export.csv'); message.send2(); }); ``` ## Callbacks and errors The callback of `MAIL()`, `HTMLMAIL()`, `LOGMAIL()` and `controller.mail()` is the callback of the message: `function(err, message)`. When the SMTP server rejects the message, `err` is its reply line, for example `550 MAILBOX UNAVAILABLE`. Connection errors are logged with `F.error()` and emitted as the `error` event of `Mail`: ```js Mail.on('error', function(err) { console.log('SMTP error', err); }); ``` Every message emits the global event `mail` before it is written to the server, which you can use to log or audit outgoing email: ```js ON('mail', function(message) { console.log('Mail to', message.address_to, message.subject); }); ``` To debug the conversation with the server, set `Mail.debug = true`; every SMTP command and reply is printed to the console. ## Sending without the configuration The `Mail` module also sends messages to any server. `Mail.create()` creates an empty message, and `Mail.send()` sends one message or an array of messages over one connection: ```js var message = Mail.create('Hello', '

    Hello from the server.

    '); message.from('info@example.com', 'My app'); message.to('peter@example.com'); Mail.send('smtp.example.com', { port: 465, secure: true, user: 'info@example.com', password: 'secret' }, [message], function(err) { err && console.log('Not sent', err); }); ``` `Mail.send2(messages, callback)` does the same with `mail_smtp` and `mail_smtp_options`. `Mail.try(smtp, [options], [callback])` only connects, signs in and quits, and returns a promise without a callback: ```js Mail.try('smtp.example.com', { port: 587, user: 'info@example.com', password: 'secret' }).then(function() { console.log('SMTP works'); }).catch(function(err) { console.log('SMTP failed', err); }); ``` ## Connections While the application runs a web server, messages sent with the configuration reuse one connection per SMTP host for `mail_smtp_keepalive`. Set `mail_smtp_keepalive : false` to open a new connection for every message. After you change `CONF.mail_smtp` or `CONF.mail_smtp_options` in code, run `CMD('clear_smtpcache')` so the next message reads them again; `Mail.use()` and `LOADCONFIG()` do it for you. ## Message-ID Every message has a `Message-ID` header generated by the framework. The identifier ends with the domain of the sender address, as mail servers expect, for example ``. --- title: Scheduling and events project: Total.js V4 version: 0.0.99 section: guides language: en license: MIT url: https://totaljs.es/docs/total-js-v4/0-0-99/guides/scheduling-and-events/ updated: 2026-11-16T15:41:15.818Z --- # Scheduling and events > Run jobs at a time, by cron or every few minutes, and react to framework events with ON() and EMIT(). Total.js 4 runs a **service** once a minute. It clears caches, fires the `service` event and starts the jobs you registered with `SCHEDULE()`. Framework events let your code react to the life of the application: start, requests, errors, exit. This guide shows both. The exact signatures are in the reference [Scheduling and events](../../reference/scheduling-and-events/). ## Run code at a set time `SCHEDULE(date, [repeat], fn)` registers a job. The `date` can be a time, a `Date`, a timestamp in milliseconds or a cron expression. ```js // definitions/jobs.js // Every day at 03:00 SCHEDULE('03:00', '1 day', function() { console.log('Nightly cleanup'); }); // Once, in ten minutes SCHEDULE(Date.now() + 1000 * 60 * 10, function() { console.log('Ten minutes later'); }); ``` - A time such as `'03:00'` is today at that time. If that time has already passed and you set `repeat`, the first run moves forward by one `repeat` (here to tomorrow). - `repeat` is a period that `Date.add()` understands: `'5 minutes'`, `'2 hours'`, `'1 day'`, `'1 week'`. You can write `'each'` for one: `'each day'` is the same as `'1 day'`. - Without `repeat` the job runs once and then removes itself. - Times are read in the time zone of the application, which is the `default_timezone` setting (`utc` by default). The service checks the jobs once a minute, so a job runs on the first check at or after its time. Do not expect precision below one minute. A string that contains a space is always read as a cron expression. To run a job once at a specific date, pass a `Date` object or a timestamp: ```js SCHEDULE(new Date(2026, 11, 24, 8, 0), function() { console.log('Christmas Eve, 08:00'); }); ``` ## Cron expressions A cron expression has five fields separated by spaces: **minute**, **hour**, **day of month**, **month** (1-12) and **day of week**. ```js // At 02:30 every day SCHEDULE('30 2 * * *', backup); // At 08:00 from Monday to Friday SCHEDULE('0 8 * * mo-fr', report); // At 00 and 30 minutes of every hour SCHEDULE('0,30 * * * *', sync); ``` | Field value | Meaning | | --- | --- | | `*` | any value | | `5` | exactly 5 | | `1,15,30` | one of the listed values | | `9-17` | any value between 9 and 17, both included | Days of the week are numbers from `0` (Sunday) to `6` (Saturday), or names. Only the first two letters of a name count: `su`, `mo`, `tu`, `we`, `th`, `fr`, `sa` (so `monday` also works). A cron job has no `repeat` argument. It runs at every minute that matches the expression, until you remove it. To run a job every few minutes, list the minutes (`'0,15,30,45 * * * *'`) or use a time with `repeat` (`SCHEDULE('00:00', '15 minutes', fn)`). ## Stop or trigger a job `SCHEDULE()` returns the job. Keep it to stop the job later or to run it at once: ```js var job = SCHEDULE('0 * * * *', function() { console.log('Every full hour'); }); // Run it now, outside its time job.exec(); // Stop it job.remove(); ``` ## The service event If you need something every minute, listen to `service`. The argument is the number of runs since the application started, so you can derive longer periods: ```js ON('service', function(counter) { // Every 5 minutes if (counter % 5 === 0) refreshrates(); // Every hour if (counter % 60 === 0) cleanold(); }); ``` The same tick clears the internal caches. `default_interval_clear_cache` (10), `default_interval_clear_resources` (20) and `default_interval_clear_dnscache` (30) set how many minutes pass between those clean-ups, and each one emits the `clear` event. ## Listen to events `ON(name, fn)` adds a listener. `ONCE(name, fn)` adds one that is removed after its first call. `OFF(name, [fn])` removes listeners. `this` inside a listener is the framework (`F`). ```js ON('ready', function() { console.log('The application is ready'); }); ON('request_end', function(req, res) { // every finished request }); ONCE('service', function() { console.log('The first service tick'); }); ``` `init`, `load` and `ready` are special: if the application has already loaded when you call `ON()`, the function runs immediately. So a plugin or a module that is installed late still gets its `ready` call. To remove one listener, pass the same function you added: ```js function onrequest(req, res) { console.log(req.method, req.url); } ON('request', onrequest); // later OFF('request', onrequest); ``` `OFF(name)` without a function removes every listener of that event, including the framework's own. Call `OFF()` with no arguments only if you really mean to remove all listeners of all events. ## Your own events Any name works with `EMIT()`. Use events to let parts of the app talk without requiring each other: ```js // schemas/orders.js EMIT('order_created', order); // definitions/notify.js ON('order_created', function(order) { MAIL(order.email, 'Thank you', '@mail/order', order); }); ``` `EMIT(name, [a], [b], ...)` passes up to seven arguments and calls the listeners synchronously, in the order they were added. `EMIT2(name, [a], ...)` sends the event to the **other** processes of the application: the threads, the cluster, or the parent process of a worker. It passes up to five arguments, so they must be serialisable values. In a single process without threads or a cluster it does nothing; use `EMIT()` there. ## Built-in events | Event | Arguments | When | | --- | --- | --- | | `init` | | Configuration is loaded, before the app files load | | `load`, `ready` | | All files are loaded; `ready` comes right after `load` | | `service` | `counter` | Every minute | | `request` | `req, res` | A request arrives, before routing | | `request_begin` | `req, res` | The request is prepared for routing | | `request_end` | `req, res` | The response has finished | | `controller` | `controller, name, options` | Before a route action runs | | `errorNNN` | `req, res, exception` | An error page is sent, for example `error404` | | `error` | `obj` | The framework logs an error | | `route` | `type, route` | A route is registered | | `install` | `type, name, module` | A file (controller, model, plugin...) is installed | | `configure` | `CONF` | Configuration has been (re)loaded | | `websocket` | `req, socket, head` | A WebSocket upgrade request arrives | | `websocket_begin`, `websocket_end` | `controller, client` | A WebSocket client connects or disconnects | | `clear` | `type, [value]` | An internal cache is cleared | | `cache_set`, `cache_expired` | `key, value, ...` | A `CACHE` value is set or expires | | `mail` | `message` | An email is being sent | | `message` | `msg, handle` | The process receives an IPC message | | `exit` | `signal` | The application stops | Each event has its own entry in the reference with the exact arguments. ## Clean up streams `CLEANUP(stream, [callback])` waits until a stream has finished, destroys it and then calls the callback. Without a callback it returns a Promise. Use it to release file handles after you pipe a stream: ```js var stream = F.Fs.createReadStream(PATH.public('big.zip')); stream.pipe(F.Fs.createWriteStream(PATH.temp('big.zip'))); CLEANUP(stream, function() { console.log('The file is closed'); }); ``` ## Wait and delay `WAIT(validator, callback, [timeout], [interval])` checks `validator()` every `interval` ms (500) until it returns `true`, or fails after `timeout` ms (5000): ```js WAIT(() => MAIN.db != null, function(err) { if (err) console.log('The database did not connect in time'); else console.log('Connected'); }, 10000, 200); ``` `setTimeout2(name, fn, timeout, [limit], [param])` is a named timeout. Calling it again with the same name cancels the previous timer, so the function runs once after the last call (a debounce). With `limit`, after that many postponements the function runs at once. `clearTimeout2(name)` cancels it. ```js ON('request_end', function() { // write statistics 5 s after the last request, // but at least every 100 requests setTimeout2('stats', savestats, 5000, 100); }); ``` `PAUSESERVER(name, [enable])` makes the server answer every request with `503` while at least one name is paused, for example during a migration. --- title: File storage project: Total.js V4 version: 0.0.99 section: guides language: en license: MIT url: https://totaljs.es/docs/total-js-v4/0-0-99/guides/file-storage/ updated: 2026-11-16T15:41:20.819Z --- # File storage > Save, read, serve and manage binary files with FILESTORAGE(). `FILESTORAGE(name)` returns a file storage: a folder on the disk that keeps binary files under an ID, together with their name, content type, size and other metadata. Use it for uploads, attachments, photos and exports that the application stores itself. The full list of methods is in the reference of [File storage](../../reference/file-storage/). ```js var fs = FILESTORAGE('photos'); fs.save(UID(), 'logo.png', PATH.public('img/logo.png'), function(err, meta) { // meta.id, meta.name, meta.size, meta.type, meta.width, meta.height console.log(meta); }); ``` The first call creates the storage object; later calls with the same name return the same object. ## Where the files live A storage named `photos` lives in `databases/fs-photos/` (`PATH.filestorage('photos')`, inside the folder set by `directory_databases`). Files are spread into subfolders with four-digit names, computed from a hash of the ID, so one folder never holds too many files: ``` databases/ fs-photos/ files.log 0384/ 1fs3001xb41f.file 7712/ 1fs3002xb41f.file ``` - Each `.file` has a header of 2000 bytes with the metadata as JSON, followed by the content of the file. - `files.log` is a NoSQL text database with the metadata of all files. `browse()` and `count()` read it; `save()`, `rename()`, `remove()` and `clean()` keep it up to date; `rebuild()` creates it again from the files. The ID is part of the file name on the disk. Use IDs that you generate (`UID()`), and never pass an unchecked value from a request as the ID. ## Saving files `save(id, name, data, [callback], [custom], [expire], [headers])` stores `data` under `id`. `name` is the file name with its extension; the extension sets the content type. `data` can be: - a path to a file on the disk, - a `Buffer`, - a readable stream, - a URL (`http://` or `https://`): the file is downloaded first; `headers` are sent with that request. ```js var fs = FILESTORAGE('documents'); // From a buffer, with custom data and an expiration fs.save(UID(), 'report.txt', Buffer.from('Hello'), function(err, meta) { console.log(meta.id, meta.expire); }, { user: 'admin' }, '7 days'); // From a URL, as a promise var meta = await fs.save(UID(), 'avatar.jpg', 'https://example.com/avatar.jpg'); ``` `custom` is any value you want to keep with the file; it comes back as `meta.custom`. `expire` is a period such as `'1 hour'` or `'7 days'`: after it, the file can no longer be read and `clean()` removes it. `savejson(id, value)` saves an object as a JSON file and `readjson(id, callback)` reads it back. ## The meta object Every read returns the metadata of the file: | Property | What it contains | | --- | --- | | `id` | The ID of the file | | `name` | The file name (at most 250 characters) | | `ext` | The extension, without the dot | | `type` | The content type, from the extension | | `size` | The size of the content in bytes | | `date` | When the file was saved | | `width`, `height` | The dimensions of a GIF, PNG, JPEG or SVG image | | `custom` | The `custom` value given to `save()` | | `expire` | The expiration date, when `expire` was given to `save()` | ## Reading files ```js var fs = FILESTORAGE('documents'); // A stream of the content fs.read(id, function(err, meta) { if (err) return; meta.stream.pipe(F.Fs.createWriteStream(PATH.temp(meta.name))); }); // Only the metadata fs.readmeta(id, function(err, meta) { console.log(meta.name, meta.size); }); // The whole content in memory fs.readbuffer(id, function(err, buffer, meta) { console.log(buffer.length); }); ``` `read()` gives an error `File not found`, `Invalid file` or `File is expired`, or the error of the file system when the file does not exist. Pass `true` as the third argument of `read()` to get the metadata without opening a stream. `readbase64()` returns the content as a Base64 string, and `image(id, callback)` returns an `Image` object to resize or convert the stored picture. Without a callback, most methods return a promise: ```js var meta = await FILESTORAGE('documents').read(id, null, true); var buffer = await FILESTORAGE('documents').readbuffer(id); ``` ## Serving files over HTTP A controller sends a stored file with `this.filefs(name, id, [download], [headers], [callback], [checkmeta])`: ```js exports.install = function() { ROUTE('GET /download/{id}/', download); ROUTE('GET /photos/{id}/', photo); }; function download(id) { // true: the browser downloads the file with its stored name this.filefs('documents', id, true); } function photo(id) { this.imagefs('photos', id, function(image) { image.resize(300, 300); image.quality(85); }); } ``` The response has the stored content type, the `Last-Modified` header and the headers `X-Size`, `X-Width` and `X-Height`. A request with `If-Modified-Since` gets `304 Not Modified`, and a request with a `Range` header gets a part of the file (`206`), so audio and video can be played from the storage. A file that does not exist or has expired gives `404`. `checkmeta(meta)` decides whether the file may be sent; return `false` to answer with `404`: ```js function privatefile(id) { var user = this.user; this.filefs('documents', id, false, null, null, function(meta) { return meta.custom && meta.custom.user === user.id; }); } ``` `imagefs()` processes the image with GraphicsMagick (or ImageMagick, see `default_image_converter`) and caches the result in the temporary folder, so the processing runs once per URL. The same methods exist on the response object as `res.filefs()` and `res.imagefs()`, for routes that work with `req` and `res`. ## Uploaded files Every file in `controller.files` has the method `fs(storage, id, [custom], [expire], [callback])`. It saves the uploaded file into the storage with its original file name: ```js exports.install = function() { ROUTE('POST /api/upload/', upload, ['upload'], 1024 * 5); }; function upload() { var self = this; var output = []; self.files.wait(function(file, next) { file.fs('documents', UID(), function(err, meta) { !err && output.push({ id: meta.id, name: meta.name, size: meta.size }); next(); }); }, function() { self.json(output); }); } ``` ## Changing and removing files ```js var fs = FILESTORAGE('documents'); fs.rename(id, 'new-name.pdf'); // changes the stored name fs.move(id, newid); // changes the ID fs.remove(id); // removes one file fs.clean(); // removes expired files fs.clear(); // removes all files (also drop()) ``` `copy(id, path, [callback])` writes the content of a file to a path on the disk, and `clone(id, [newid], [callback])` makes a copy of a file inside the storage under a new ID. ```js // Export to a folder: the file keeps its stored name fs.copy(id, PATH.temp(), function(err, meta) { console.log('Saved', meta.name); }); // A second copy under a new ID fs.clone(id, UID(), function(err, meta) { console.log(meta.id); }); ``` ## Listing and maintenance `browse()` returns a NoSQL query builder over `files.log`, so you filter, sort and page the files like any other NoSQL query: ```js FILESTORAGE('photos').browse().where('ext', 'png').sort('date_desc').take(20).callback(function(err, files) { console.log(files); }); ``` - `count(callback)` returns the number and total size of files from `files.log` and updates `fs.total` and `fs.size`. - `browse2()`, `stream()` and `count2()` read the files on the disk instead of `files.log`. - `rebuild()` creates `files.log` again from the files on the disk. - `backup(filename)` writes all files into one backup file and `restore(filename)` replaces the content of the storage with a backup. --- title: Operations and tasks project: Total.js V4 version: 0.0.99 section: guides language: en license: MIT url: https://totaljs.es/docs/total-js-v4/0-0-99/guides/operations-and-tasks/ updated: 2026-11-16T15:41:15.818Z --- # Operations and tasks > Reusable business logic with operations, chained operations, tasks with steps, commands, extensions and PROMISIFY(). Operations and tasks are small units of business logic that are not tied to a route. You declare them once and call them from controllers, schemas, schedulers or other operations. An **operation** is one function with a callback. A **task** is a named set of steps that jump from one to another. Both receive a `$` object that carries the value, the errors and, when there is one, the controller of the current request. ## Declare an operation `NEWOPERATION(name, fn)` registers a function. The function receives `$` and the value. It must finish with `$.callback()`, `$.success()` or `$.invalid()`. ```js NEWOPERATION('users_count', function($, value) { NOSQL('users').count().callback(function(err, count) { if (err) $.invalid(err); else $.callback(count); }); }); ``` Put operations in files in the `/operations/` directory. The framework loads them when the app starts. ## Call an operation `OPERATION(name, [value], callback, [options], [controller])` runs one operation. The callback receives `err` (an `ErrorBuilder` or `null`), the response and the `options` argument. ```js OPERATION('users_count', function(err, response) { console.log(err, response); }); ``` From a route, pass the controller. Then `$.user`, `$.query`, `$.params`, `$.body` and the other request properties work inside the operation, and the controller callback sends the answer: ```js exports.install = function() { ROUTE('GET /api/users/count/', count); }; function count() { var self = this; OPERATION('users_count', self.query, self.callback(), self); } ``` Without a controller, request properties such as `$.user` or `$.query` are `null`. ### Repeat, stop and bind errors `NEWOPERATION(name, fn, [repeat], [stop], [binderror], [filter])` takes extra options: - `repeat {Number}` runs the operation again when it ends with an error, up to this number of times. - `stop {Boolean}` (default `true`) stops a `RUN()` chain when this operation fails. - `binderror {Boolean}` (default `false`) stores the error output as the response of this operation in a `RUN()` chain. - `filter {String}` is a schema for the query string. `$.filter` then returns the converted query. ```js NEWOPERATION('newsletter', function($) { MAIL($.value.email, 'Newsletter', '=?/mails/newsletter', $.value, $.done()); }, 3); ``` ## Chain operations with RUN() `RUN(names, [value], callback, [options], [controller], [response_name])` runs several operations one after another. `names` is a comma-separated string or an array. All operations share the same `$.value`, so one operation can prepare data for the next. ```js NEWOPERATION('check', function($) { if (!$.value.email) { $.invalid('email'); return; } $.value.email = $.value.email.toLowerCase(); $.success(); }); NEWOPERATION('save', function($) { NOSQL('contacts').insert($.value).callback($.done()); }); RUN('check, save', { email: 'Peter@Example.com' }, function(err, response) { // response.check = { success: true } // response.save = { success: true } console.log(err, response); }); ``` The response is an object with one key per operation. With `response_name`, the callback receives only the response of that operation: ```js RUN('check, save', model, function(err, response) { // response = { success: true } from "save" }, 'save'); ``` Inside a chain, `$.response` holds the results so far, `$.meta.current` and `$.meta.prev` hold the operation names, and `$.repeated` counts the repeats of the current one. When an operation fails and its `stop` option is `true` (the default), the chain stops and the callback receives the error. An operation name that does not exist is skipped. ## Declare a task `NEWTASK(name, fn)` declares a set of steps. `fn` receives a `push(step, fn)` function. Each step receives `$` and the value. A step moves on with `$.next(step)` and finishes the task with `$.end()`, `$.success()` or `$.invalid()`. ```js NEWTASK('order', function(push) { push('check', function($, value) { if (!value.items || !value.items.length) { $.invalid('items'); return; } $.next('price'); }); push('price', function($, value) { value.price = 0; for (var item of value.items) value.price += item.price * item.count; $.next('save'); }); push('save', function($, value) { NOSQL('orders').insert(value).callback($.done(true)); }); }); ``` Put tasks in files in the `/tasks/` directory. ## Run a task `TASK(name, step, callback, [options], [value])` creates the task and starts it at `step`. You can also write the name and the step together as `'name/step'`: ```js TASK('order', 'check', function(err, response) { console.log(err, response); }, { items: [{ price: 10, count: 2 }] }); // The same with "name/step" TASK('order/check', function(err, response) { console.log(err, response); }, $, $.value); ``` Pass a controller or the `$` of a schema, operation or task as `options` to share its request and its errors. Anything else in `options` is used as the value. `TASK()` returns the task, so you can add steps with `$.push()` before it starts. `$.next(a, b, ...)` runs the first step that exists, and ends the task when none exists. `$.next2(step)` and `$.done()` return callbacks for asynchronous functions: ```js push('load', function($, value) { NOSQL('orders').one().where('id', value.id).callback($.next2('send')); }); ``` ## Commands Commands are named handlers that any part of the app can trigger. `NEWCOMMAND(name, fn)` adds a handler, and the same name can have several handlers. `CMD(name, [a], [b], [c], [d])` calls all of them. ```js NEWCOMMAND('clear_prices', function(category) { MAIN.prices && delete MAIN.prices[category]; }); CMD('clear_prices', 'books'); ``` The framework itself uses commands such as `clear_viewscache`, `clear_smtpcache` and `refresh_tms`. ## Extensions `NEWEXTENSION(code, [callback], [extend])` installs code at runtime from a string or a URL. The code uses `exports` like a module: `exports.install(next)`, `exports.make()`, `exports.done()` and `exports.uninstall()` are optional. Files in the `/extensions/` directory are installed when the app starts. ## Promises `PROMISIFY(fn, [a], [b])` wraps a function that ends with a `callback(err, response)` in a `Promise`: ```js var count = await PROMISIFY(function(callback) { NOSQL('users').count().callback(callback); }); ``` The `$` of a schema has a similar `$.promisify()` method; see [Schemas](../../guides/schemas/). --- title: Utilities project: Total.js V4 version: 0.0.99 section: guides language: en license: MIT url: https://totaljs.es/docs/total-js-v4/0-0-99/guides/utilities/ updated: 2026-11-16T15:41:15.818Z --- # Utilities > Global helpers and the U object: identifiers, object copies, paths, files, queues and text functions. Total.js puts a set of helpers into the global scope. You do not `require()` them: they are available in controllers, schemas, definitions, modules and plugins. Most of them live in the object `U` (the file `utils.js`), the rest are global functions and objects. The full list is in the reference of [Utilities](../../reference/utilities/). ```js var id = UID(); var ext = U.getExtension('Photo.JPG'); // 'jpg' var copy = CLONE(model, { password: 1 }); ``` `U`, `Utils` and `utils` are the same object. `Total` is an alias of the framework instance `F`. ## Identifiers | Function | Result | | --- | --- | | `UID([type])` | A short time-based ID, for example `24j0y001xn51d` | | `UID16([type])` | The same with the time in base 16 | | `GUID()` | A UUID-like string `xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx` | | `GUID(length)` | Random lowercase letters and digits | | `U.random_text(length)` | Random letters and digits | | `U.random_number(length)` | Random digits as a string, never starting with `0` | | `U.random([max], [min])` | A random integer (`0` to `100000` by default) | `UID()` is the usual choice for primary keys: it is short, unique within the running instance and it sorts by time. The `type` argument keeps a separate counter for each collection. `CONF.default_uid` set to `r` switches `UID()` to random IDs. ```js function create(model) { model.id = UID('orders'); model.dtcreated = NOW; return model; } ``` When an ID goes to the client and comes back in a URL, sign it with `U.encrypt_uid()`. `U.decrypt_uid()` returns `null` when somebody changed it. The value is not hidden, only protected. ```js var link = '/invoice/' + U.encrypt_uid(invoice.id) + '/'; // later var id = U.decrypt_uid(this.params.id); ``` ## Objects | Function | What it does | | --- | --- | | `CLONE(obj, [skip])` | A deep copy; `skip` is `{ key: 1 }` of keys to leave out | | `COPY(source, [target])` | Copies all keys of `source` to `target` | | `U.copy(source, [target])` | Copies only keys that `target` already has | | `U.extend(target, source, [rewrite])` | Adds keys; with `rewrite = false` it fills only missing values | | `U.reduce(obj, keys, [reverse])` | Keeps the listed keys, or removes them with `reverse` | | `U.get(obj, path)` / `U.set(obj, path, value)` | Read and write by a path like `address.city` | | `U.trim(obj, [clean])` | Trims all strings; `clean` turns empty strings into `undefined` | | `DIFFARR(key, db, form)` | Compares two lists: `{ add, upd, rem }` | `U.copy()` is useful when you update a stored record from a form: only the fields the record already has are written. ```js var user = { name: '', email: '' }; U.copy(this.body, user); // extra keys of the body are ignored var output = U.reduce(user, ['password'], true); ``` `DIFFARR()` tells you what to insert, update and remove when a user saves an edited list. ```js var diff = DIFFARR('id', stored, model.items); diff.add.forEach(insert); diff.upd.forEach(function(item) { update(item.db, item.form); }); diff.rem.forEach(remove); ``` ## Shared state The framework creates empty global objects for your app: `MAIN`, `REPO` and `FUNC`. It never writes into them, so they are a safe place for shared data and helpers. `TEMP` is cleared regularly (every 10 minutes by default). `NOW` is a `Date` the framework refreshes about every minute; use it for timestamps where a precision of a minute is enough. `EMPTYOBJECT` and `EMPTYARRAY` are frozen defaults and `NOOP` is an empty callback. ```js // definitions/init.js FUNC.price = function(value) { return value.format(2) + ' EUR'; }; MAIN.countries = ['SK', 'CZ', 'AT']; ``` Loaded modules are in `MODS`, and `MODULE(name)` returns one of them or `null`. ## Paths and files `PATH` returns paths to the directories of the app. Each directory comes from its `CONF.directory_*` option. `PATH.temp()`, `PATH.databases()` and `PATH.logs()` also create the directory when it is missing. ```js PATH.root('data/countries.json'); PATH.public('img/logo.png'); PATH.temp('export.csv'); PATH.databases('settings.json'); PATH.mkdir(PATH.databases('uploads/2021/'), true); ``` `U.combine()` joins paths relative to the root of the app, `U.join()` joins parts of a URL path, and `U.path()` adds a trailing slash. `U.getExtension()`, `U.getName()` and `U.getContentType()` work with file names. `U.setContentType()` adds a new extension to the table the framework uses for static files. `U.ls()` lists a directory with all its subdirectories. Without a callback it returns a Promise. The `unified` argument gives paths with `/` on Windows. `U.ls2()` adds the `fs.Stats` of each file. ```js U.ls(PATH.public(), function(files, directories) { console.log(files); }, /\.(jpg|png)$/); var response = await U.ls2(PATH.temp()); response.files.forEach(function(file) { console.log(file.filename, file.stats.size); }); ``` `LOGGER(name, ...)` appends a line with a date to `/logs/{name}.log`. ```js LOGGER('payments', 'order', order.id, 'paid', order.price); ``` ## Asynchronous helpers `U.queue(name, max, fn)` runs at most `max` functions of one queue at the same time; each function calls `next()` when it is done. `WAIT(validator, callback, [timeout], [interval])` checks a condition until it is true or the time runs out. `PROMISIFY(fn, [a], [b], [c])` turns a function with a `callback(err, response)` into a Promise. ```js files.forEach(function(filename) { U.queue('resize', 2, function(next) { resize(filename, next); }); }); var text = await PROMISIFY(require('fs').readFile, PATH.root('readme.md'), 'utf8'); ``` ## Text and data | Function | Result | | --- | --- | | `U.encode(value)` / `U.decode(value)` | HTML entities | | `U.btoa(value)` / `U.atob(value)` | Base64 | | `HASH(value, [type])` | A numeric hash, or `md5`, `sha1`, `sha256`, `sha512`, `crc32` | | `U.keywords(text)` | Unique words for a search index | | `U.parseXML(xml)` | A flat object with dot paths as keys | | `U.parseInt(value, [def])` | A number from any value (also `U.parseFloat`, `U.parseBoolean`) | | `QUERIFY([url], obj)` | A URL with a query string | | `U.sortcomparer('price_desc,name')` | A compare function for `Array.sort()` | | `U.distance(lat1, lon1, lat2, lon2)` | Kilometres between two GPS points | | `U.minify_css/js/html(value)` | Code minified by the built-in compilers | ```js var keywords = U.keywords(product.name + ' ' + product.description).join(' '); products.sort(U.sortcomparer('price_desc,name')); var url = QUERIFY('/api/products/', { page: 2, q: 'book' }); ``` The methods of `String`, `Number`, `Date` and `Array` that the framework adds are described on their own page. --- title: Prototypes project: Total.js V4 version: 0.0.99 section: guides language: en license: MIT url: https://totaljs.es/docs/total-js-v4/0-0-99/guides/prototypes/ updated: 2026-11-16T15:41:15.818Z --- # Prototypes > Methods that Total.js 4 adds to strings, numbers, dates and arrays. Total.js 4 adds methods to the built-in prototypes of `String`, `Number`, `Date` and `Array`. They are available everywhere after the framework starts: in controllers, schemas, views, definitions and plugins. You call them on the value itself, so the code stays short. ```js var slug = model.name.slug(); var price = (model.price || 0).format(2); var expire = NOW.add('1 month'); var user = users.findItem('id', id); ``` The full list with every argument is in the reference of [Prototypes](../../reference/prototypes/). ## Strings ### Placeholders `String.format()` replaces indexed placeholders and `String.args()` named ones. `args()` can encode the values for HTML, URL or JSON. ```js '{0} of {1}'.format(3, 10); // 3 of 10 'Hello {name}'.args({ name: 'Peter' }); // Hello Peter '{name}'.args({ name: '' }, 'html'); // <x> ``` ### Converting values Values from a query string or a form are strings. The `parse*` methods convert them and never throw: | Method | Result | | --- | --- | | `'12'.parseInt()` | `12` (`0` or your default when the whole string is not a number) | | `'Size 12px'.parseInt2()` | `12` (the first number in the text) | | `'12,5'.parseFloat()` | `12.5` (a decimal comma is accepted) | | `'on'.parseBoolean()` | `true` for `true`, `1` and `on` | | `'2024-01-15'.parseDate()` | a `Date` | | `'{"a":1}'.parseJSON()` | an object, or `undefined` for invalid JSON | ```js function list() { var page = (this.query.page || '').parseInt(1); var limit = (this.query.limit || '').parseInt(20); this.json({ page: page, limit: limit }); } ``` ### Validation `String.isEmail()`, `String.isPhone()` and `String.isURL()` use the regular expressions in `DEF.validators`, so you can change them in one place. `String.isUID()` checks the format and the checksum of an identifier created by `UID()`. ```js function detail(id) { if (!id.isUID()) { this.throw404(); return; } // ... } ``` ### Text helpers - `String.slug()` makes a URL part from a title: `'Hello World'.slug()` gives `hello-world`. - `String.max(length)` shortens a text and adds `...`. - `String.capitalize()` upper-cases the first letter of each word. - `String.toASCII()` removes diacritics; `String.removeTags()` removes HTML tags. - `String.encode()` and `String.decode()` convert HTML special characters. - `String.padLeft()` and `String.padRight()` pad a string to a length. - `String.tslash()` removes trailing slashes from a URL. ### Hashes and encryption `String.md5()`, `String.sha1()`, `String.sha256()` and `String.sha512()` return hex hashes; each accepts a salt. `String.hash()` selects the algorithm by name and without a name returns a fast number hash, good for cache keys. `String.encrypt(key)` and `String.decrypt(key)` protect small values such as tokens. Decryption returns `null` when the key, the secret (`CONF.secret`) or the string does not match. ```js var token = JSON.stringify({ id: user.id }).encrypt('reset', true); // later var data = (this.query.token || '').decrypt('reset'); var obj = data ? data.parseJSON() : null; ``` ### Search `String.keywords()` returns the words of a text sorted by frequency and normalized for search. `String.toSearch()` normalizes a phrase in the same spirit. Store the keywords with the record and search by them. ```js item.search = (item.name + ' ' + item.description).keywords().join(' '); var q = (this.query.q || '').toSearch(); ``` ### Markdown and JSON schemas `String.markdown()` converts Markdown to HTML and `String.toJSONSchema()` turns an inline definition such as `'*name:string(50), email:email'` into a JSON schema object. ## Numbers `Number.format()` adds a thousands separator and decimals; `Number.round()` and `Number.floor()` work with decimals; `Number.padLeft()` adds leading zeros. ```js (1234567.891).format(2); // 1 234 567.89 (1234.5).format(2, '.'); // 1.234,50 (3.14159).round(2); // 3.14 (42).padLeft(6); // 000042 ``` `Number.pluralize()` picks a word form for 0, 1, 2-4 and other numbers, and replaces `#` with the number. The forms can also be one comma-separated string. ```js count.pluralize('no comments', '# comment', '# comments', '# comments'); count.pluralize('no comments,# comment,# comments,# comments'); ``` Prices have their own helpers: `Number.VAT()` adds or removes VAT, `Number.discount()` subtracts a percentage, and `Number.add('+20%')` applies an operation written as a string. `Number.filesize()` formats bytes as `KB`, `MB` and so on. `Number.between()` maps ranges to values. ## Dates `Date.add()` returns a new date moved by a period, and `Date.format()` writes the date with tokens such as `yyyy`, `MM`, `dd`, `HH` and `mm`. ```js var expire = NOW.add('7 days'); var label = NOW.format('dd.MM.yyyy HH:mm'); var left = expire.diff('hours'); ``` `Date.diff()` returns the difference in a unit, `Date.extend('12:00')` sets date or time parts, `Date.toUTC()` shifts the date by the timezone offset and `Date.setTimeZone()` converts it to an IANA timezone. `Date.add()` and `Date.extend()` never change the original date. ## Arrays ### Finding items `Array.findItem()`, `Array.findAll()`, `Array.findIndex()` and `Array.remove()` accept either a function or a property name with a value: ```js var user = users.findItem('id', id); var active = users.findAll('active', true); var index = users.findIndex(item => item.email === email); users = users.remove('id', id); ``` Total.js replaces the native `findIndex()` to support this form. Some NPM modules replace it again, so the same method is also available as `Array.TfindIndex()`. ### Paging, sorting and lookups ```js var items = all.skip((page - 1) * limit).take(limit); products.quicksort('price_desc'); var byid = users.toObject('id'); ``` `Array.quicksort()` sorts in place by one or more properties. `Array.toObject()` makes a lookup object, which is faster than repeated searches. ### Asynchronous processing `Array.wait()` calls an asynchronous function for each item, `Array.async()` runs a list of functions, and `Array.limit()` processes items in chunks. In each case you call `next()` to continue, and a final callback runs at the end. ```js users.wait(function(user, next) { MAIL(user.email, 'News', '=mails/news', user, next); }, function() { console.log('Done'); }); ``` `Number.async()` does the same for a number of runs. --- title: FlowStream project: Total.js V4 version: 0.0.99 section: guides language: en license: MIT url: https://totaljs.es/docs/total-js-v4/0-0-99/guides/flowstream/ updated: 2026-11-16T15:41:20.819Z --- # FlowStream > Run graphs of components from .flow files in /flowstreams/, write components and work with messages and FlowStream instances. A **FlowStream** is a graph of components connected through inputs and outputs. Data flows through it as **messages**. The Flow module is part of Total.js 4: put `.flow` files in `/flowstreams/` and the app loads them when it starts. The Flow designer edits a running FlowStream through a WebSocket. The exact list of methods is in the reference of [FlowStream](../../reference/flowstream/). ## The /flowstreams/ directory Each `.flow` file is a JSON schema. When the app starts, the files of `/flowstreams/` (and `plugins/{name}/flowstreams/`) are passed to `Flow.load()`. Names that contain `-bk` or `_bk` are skipped, so backups can stay in the same folder. In debug mode, a changed `.flow` file restarts the app. ```json { "id": "orders", "name": "Orders", "components": { "uppercase": "", "print": "" }, "design": { "a1": { "component": "uppercase", "config": { "field": "name" }, "connections": { "output": [{ "id": "b1", "index": "input" }] } }, "b1": { "component": "print", "config": {} } }, "variables": { "currency": "EUR" } } ``` - `components` maps a component id to the source of the component. - `design` maps an instance id to the component it uses, its `config` and its `connections`. A connection goes from an output id to `{ id: instance, index: input }`. - `variables` are values that components read with `instance.replace()` or `$.variables()`. - `worker: 'worker'` runs the FlowStream in a worker thread and another truthy value (for example `'fork'`) in a child process. The worker restarts itself when it crashes. You can also call `Flow.load(schema, callback)` from code. A schema with an `id` that is already loaded updates the running FlowStream. ## Components A component is an HTML file. Its ` Converts one field of the incoming object to upper case. ``` - `exports.inputs` and `exports.outputs` declare the ports. Connections to an input that the component does not declare are removed. - `exports.config` is the default configuration, merged with the `config` of each instance. - `exports.make(instance, config)` runs once for each instance in the design. - `exports.npm` lists NPM packages that are installed before the component is registered. Inside `make` you assign handlers to the instance: | Handler | When it runs | | --- | --- | | `instance.message($)` | A message arrived; `instance.message_INPUTID($)` for one input | | `instance.configure(config)` | The configuration changed | | `instance.trigger(data)` | `flowstream.trigger()` or the designer button | | `instance.close(removed)` | The instance stops; clear timers here | | `instance.init()`, `instance.refresh()` | After the design was created, and after each change | | `instance.variables(variables)` | The variables changed | And you call its methods: `instance.send(output, data)`, `instance.status(data, [delay])` and `instance.dashboard(data)` for the designer, `instance.throw(err)` for errors, `instance.replace(str)` for variables and `instance.save()` to store changed configuration. ## Messages `$` is the message. `$.data` is its data. `$.send(output)` passes it to the next instances and `$.destroy()` ends it. Every message must end in one of these two ways; a message sent from an output with no connection ends by itself. ```js exports.make = function(instance) { instance.message = function($) { console.log($.data); $.destroy(); }; }; ``` When a message goes to several connections, each one gets its own copy of `$.data`, objects and Buffers alike (set `cloning: false` in the schema to turn it off). `$.repo` is one object shared by all copies, useful to carry values along the chain. `$.on('end', fn)` runs when the last copy ends; `$.timeout()` and `$.totaltimeout()` end slow messages with `$.error = 408`. A component without inputs starts messages itself: ```js exports.outputs = [{ id: 'output', name: 'Tick' }]; exports.make = function(instance, config) { var timer = setInterval(() => instance.send('output', { ts: new Date() }), config.interval || 5000); instance.close = function() { clearInterval(timer); }; }; ``` ## Using a FlowStream from the app `Flow.instances` holds the loaded FlowStreams by `id`. `send()` starts a message in one instance and calls back when the message ends: ```js exports.install = function() { ROUTE('POST /api/orders/', create); }; function create() { var self = this; Flow.instances.orders.send('a1', self.body, function(err, response) { if (err) self.invalid(err); else self.json(response.data); }); } ``` The target can be an instance id, `@componentid` or `#name` (the component name). The target must define `instance.message`. Other methods: - `exec({ id, data, repo, timeout }, callback)` sends to all matching instances, with a timeout. - `trigger(id, data)` calls `instance.trigger(data)`. - `reconfigure(id, config)` and `variables(variables)` change settings at runtime. - `pause([is])`, `export(callback)`, `components(callback)`, `add(id, html)` and `remove()`. - `stats` holds the counts of messages, pending messages and errors. ## Saving changes The framework reads `.flow` files but does not write them. When the designer or your code changes a FlowStream, `Flow` emits `save` with the whole schema about five seconds later. Store it yourself: ```js Flow.on('save', function(schema) { delete schema.unixsocket; F.Fs.writeFile(PATH.root('flowstreams/' + schema.id + '.flow'), JSON.stringify(schema, null, '\t'), NOOP); }); ``` A schema with `readonly: true` never emits `save`. `Flow.on('load', fn)` runs when a FlowStream is ready, and `Flow.onerror` receives the errors of all FlowStreams. ## The designer Connect a WebSocket route to a FlowStream with `Flow.socket(id, websocket, [check])`. Protect it, because the designer can change code: ```js exports.install = function() { ROUTE('+SOCKET /flowstreams/{id}/', designer); }; function designer(id) { var self = this; Flow.socket(id, self, function(client, next) { client.user.sa && next(); }); } ``` ## A local engine `FLOWSTREAM(name)` returns the engine without files, workers or the designer. Register components with `add()`, create instances with `use(design)` and send data with `trigger('instanceid__inputid', data)`. Most apps use `/flowstreams/` and `Flow` instead. --- title: QueryBuilder project: Total.js V4 version: 0.0.99 section: guides language: en license: MIT url: https://totaljs.es/docs/total-js-v4/0-0-99/guides/querybuilder/ updated: 2026-11-19T20:13:36.295Z --- # QueryBuilder > Query SQL databases with DATA, DB() and the QueryBuilder, and connect your database with an adapter registered by NEWDB(). Total.js 4 has a small, database-neutral **QueryBuilder** for SQL databases. You describe a query with chained methods (`find`, `where`, `sort`, `take`...) and the framework hands a plain description of it to an **adapter** that you register with `NEWDB()`. The adapter turns the description into SQL for your database and returns the rows. The framework itself does not ship an SQL driver: it ships the builder and the contract between the builder and the adapter. ## Register an adapter `NEWDB([name], fn)` registers the adapter for a connection name. Without a name it is `default`. The name `*` is the fallback for every name that has no adapter of its own. ```js // definitions/db.js NEWDB(function(filter, callback) { // filter.exec 'find', 'list', 'read', 'check', 'count', 'scalar', 'insert', 'update', 'remove', 'query', 'command', 'truncate' or 'drop' // filter.table the table name // filter.filter the conditions: [{ type: 'where', name: 'id', comparer: '=', value: 1 }, ...] // filter.fields, filter.sort, filter.take, filter.skip, filter.payload... mysqlbuilder(filter, function(err, rows) { callback(err, rows); }); }); ``` The adapter calls `callback(err, response)` once. The shape of `response` depends on `filter.exec`: | `exec` | What the adapter returns | | --- | --- | | `find` | An array of rows | | `read`, `check` | An array (the framework keeps the first item, or `null`) or one row | | `list` | `{ items: [...], count: Number }`. The framework adds `page`, `limit` and `pages` | | `count`, `scalar` | A number or the aggregated value | | `insert`, `update`, `remove` | The number of affected rows, or the rows of `returning` | | `query`, `command` | Whatever the database returns | All fields of `filter` are listed under *Adapter options* in the [reference](../../reference/querybuilder/). Register more databases with names, and pick them with a `name/` prefix in the table name: ```js NEWDB('logs', function(filter, callback) { ... }); DATA.find('logs/requests').where('status', 500).callback(console.log); ``` ## DATA and DB() There are two ways to start a query: - `DATA` is one global object. Each query you start on it runs on its own, at once. It is the fastest way for single queries. - `DB()` (alias `DATABASE()`) creates a new controller. Its queries run **one after another**, and one final callback receives the result. When one query fails, the rest do not run. ```js DATA.read('tbl_user').id(1).callback(function(err, user) { console.log(err, user); }); var db = DB(); db.insert('tbl_order', { id: UID(), userid: 1, price: 50 }); db.update('tbl_user', { '+orders': 1 }).id(1); db.callback(function(err, response) { // response is the response of the last query }); ``` On a `DB()` controller, `builder.set(name)` stores a response under a key of the final response instead of replacing it: ```js var db = DB(); db.read('tbl_user').id(1).set('user'); db.find('tbl_order').where('userid', 1).set('orders'); db.callback(function(err, response) { // response.user, response.orders }); ``` Every method of `DB()` or `DATA` returns the builder of that query, so chain the filters on it. To add another query, call the controller again. ## Filters ```js DATA.find('tbl_product') .fields('id,name,price') .where('isremoved', false) .where('price', '>', 10) .in('category', ['phones', 'tablets']) .search('name', 'iphone') .or(function(builder) { builder.where('stock', '>', 0); builder.where('ispreorder', true); }) .sort('price', true) .take(20) .callback(console.log); ``` Each filter adds an object to `filter.filter`; the adapter decides how to write it in SQL. `where()` accepts the comparers `=`, `<>`, `>`, `<`, `>=` and `<=` (`==` becomes `=`, `!=` becomes `<>`). `sort(name, true)` sorts in descending order; the adapter receives `name_desc`. ## Inserting, updating and removing ```js DATA.insert('tbl_user', { id: UID(), name: 'Peter', dtcreated: NOW }); DATA.update('tbl_user', { name: 'Lucia', dtupdated: NOW }).id(id).error('404'); DATA.remove('tbl_user').id(id).callback(console.log); ``` The third argument of `update(table, data, true)` is **upsert**. When the update finds nothing, the framework calls the function from `builder.insert(fn)` (for example to add `dtcreated`) and runs the same data again as `insert`. ```js DATA.update('tbl_counter', { id: 'visits', '+count': 1 }, true).id('visits').insert(function(model) { model.count = 1; model.dtcreated = NOW; }); ``` How keys such as `+count` are written in SQL is up to the adapter. ## Raw SQL `query([conn], sql, [params])` sends your own SQL to the adapter in `filter.query` and the arguments in `filter.params`. `DATA.query(sql, params)` uses the `default` connection when the second argument is an array or an object. ```js DATA.query('SELECT COUNT(1) AS count FROM tbl_user WHERE isremoved=$1', [false]).callback(console.log); DATA.query('logs', 'DELETE FROM tbl_request WHERE dtcreated $.success()); }); }); ``` ## Lists for grids `list()` returns one page of rows and the counts that a grid or a pager needs. `paginate(page, limit, maxlimit)` reads the values from the query string, and `autoquery()` builds the fields, filters, sort and paging from the query string by a list of allowed fields: ```js schema.setQuery(function($) { DATA.list('tbl_product').autoquery($.query, 'id,name,price:number,dtcreated:date', 'dtcreated_desc', 100).where('isremoved', false).callback($.callback); }); // GET /api/products/?name=phone&price=10 - 50&sort=price_asc&page=2&limit=20 ``` `gridfilter()` explains how one value of the query string becomes a filter: `10 - 50` is a range, `a,b` is a list, `>10` and `<10` compare, `!text` is an exact match and other text is a search. ## Schema shortcuts `$QUERY`, `$GET` (alias `$READ`), `$INSERT`, `$UPDATE`, `$PATCH`, `$SAVE`, `$REMOVE`, `$WORKFLOW`, `$CREATE`, `$MAKE` and `$ACTION` do not talk to a database. They run the operations of a schema by its name, and the schema usually calls `DATA` inside. They belong to [Schemas](../../guides/schemas/). --- title: JSON schemas project: Total.js V4 version: 0.0.99 section: guides language: en license: MIT url: https://totaljs.es/docs/total-js-v4/0-0-99/guides/json-schemas/ updated: 2026-11-16T15:41:05.817Z --- # JSON schemas > Validate and convert data with JSON schemas: files in jsonschemas/, inline declarations and actions. A **JSON schema** describes the shape of a JSON object: its properties, their types and the rules they must follow. Total.js 4 uses JSON schemas to **validate and convert** data: it reads a value, converts each property to its type, drops the properties that the schema does not know, and returns the errors. ```js NEWJSONSCHEMA('Contact', 'name:String(50), *email:Email, age:Number'); JSONSCHEMA('Contact', { name: 'Peter', email: ' PETER@example.com', age: '33', admin: true }, function(err, response) { // err === null // response === { name: 'Peter', email: 'peter@example.com', age: 33 } }); ``` A schema can come from three places: a `.json` file, a `.txt` file with the inline syntax, or code (`NEWJSONSCHEMA()` and `String.toJSONSchema()`). All of them are kept in `F.jsonschemas` under their name. ## The `jsonschemas/` directory At start the framework reads the `/jsonschemas/` directory (the `directory_jsonschemas` option), with its subdirectories: | File | How it is read | | --- | --- | | `jsonschemas/*.json` | A standard JSON schema object, parsed as JSON | | `jsonschemas/*.txt` | The inline syntax (see below), converted with `String.toJSONSchema()` | The name of a schema is the file name without the extension (`jsonschemas/users/address.json` gives `users/address`). A `.json` schema with an `$id` is also registered under its `$id`. Files whose names start with `.` or end with `-bk`/`_bk` are skipped. Packages read their own `jsonschemas/` directory. ```json { "$id": "https://example.com/product.json", "$schema": "https://json-schema.org/draft/2020-12/schema", "type": "object", "properties": { "name": { "type": "string", "maxLength": 100 }, "price": { "type": "number", "minimum": 0.01 }, "tags": { "type": "array", "items": { "type": "string" }, "uniqueItems": true } }, "required": ["name", "price"] } ``` A similar schema as `jsonschemas/product.txt`, one property per line (or separated by commas): ``` *name:String(100) *price:Number tags:[String] ``` ## The inline syntax `String.toJSONSchema()`, `NEWJSONSCHEMA(name, string)`, `.txt` files and the `input`, `output`, `params` and `query` options of actions share one syntax: `name:Type` pairs separated by commas or new lines. | Syntax | Result | | --- | --- | | `name` | A string (the default type) | | `*name` or `!name` | A required property | | `name:String(50)` | A string with `maxLength: 50` | | `tags:[String]` | An array of strings; works with any simple type | | `role:{admin\|user}` | A string enum; `;` also separates the values | | `address:{street:String, city:String}` | A nested object | | `items:[{name:String, qty:Number}]` | An array of nested objects | | `owner:@User` | Another schema: a Total.js schema, a JSON schema or the input of an action, looked up in this order | Type names are not case-sensitive. The string types are `String`, `UID`, `GUID`, `Email`, `Phone`, `Name`, `URL`, `ZIP`, `Lower`/`Lowercase`, `Upper`/`Uppercase`, `Capitalize`, `Capitalize2`, `Color`, `Icon` and `Base64`; each becomes `type: 'string'` with a `subtype`. The number types are `Number`, `Number2`, `Float`, `Decimal`, `Int`/`Integer`, `SmallInt` and `TinyInt`; each becomes `type: 'number'` with a `subtype`. The other types are `Boolean` (or `Bool`), `Date` and `Object`. An unknown type gives a string. ## Validating data `JSONSCHEMA(name, value, [callback], [error])` validates a value against a registered schema. Without a callback it returns a promise. An unknown schema gives the error `404`. ```js async function create() { var $ = this; try { var model = await JSONSCHEMA('product', $.body); // model is clean $.success(); } catch (err) { $.invalid(err); } } ``` Every schema object that the framework creates (files and `String.toJSONSchema()`) also has a `transform(value, [partial], [error])` method. It returns `{ error, response }` synchronously, where `error` is an `ErrorBuilder` or `null`: ```js var schema = 'name:String, *email:Email'.toJSONSchema('newsletter'); var res = schema.transform({ email: 'info@example.com' }); // res.error === null, res.response.email === 'info@example.com' ``` With `partial` set to `true`, only the properties present in the value are validated, so a missing required property is not an error. Use it for updates. ## What validation does - **Strings**: other values are converted to strings. `email` and `phone` remove spaces (and `email` is lower-cased) and check the format; `url`, `zip`, `guid`, `uid`, `base64`, `color` and `icon` check the format; `name` normalizes a person's name; `lower`, `upper`, `capitalize` and `capitalize2` change the case. An empty `uid` or `guid` becomes `null`. - **Numbers**: a string with digits is parsed with `String.parseFloat()`. `smallint` must be between -32767 and 32767, `tinyint` between 0 and 255. - **Booleans**: strings are parsed with `String.parseBoolean()`. - **Dates**: other values are parsed with `String.parseDate()`; an invalid date becomes `null`. - **Objects**: only the declared `properties` are copied. An object without `properties` is copied as it is. - **Arrays**: each item is checked by `items`; invalid items are left out and reported. An empty or invalid value of a required property is an error named after the property. Validation does not stop at the first error: all errors are collected. ## JSON schemas in actions The `input`, `output`, `params` and `query` options of `schema.action()` and `NEWACTION()` take an inline declaration (any string with `,`, `:` or `*`) or the name of a registered JSON schema (a `.json` suffix is removed). See [Schemas](../schemas/). ```js NEWACTION('Products/create', { name: 'Create a product', input: '*name:String(100), *price:Number, tags:[String]', action: function($, model) { // model is validated and converted $.success(); } }); NEWACTION('Products/update', { input: 'product', // jsonschemas/product.json action: function($, model) { $.success(); } }); ``` - `input` validates the model. It is validated as partial for `PATCH` requests and for actions marked with `#` in a route. - `query` and `params` validate `$.query` and `$.params`; their error names get the `query.` and `params.` prefix. - `output` converts the response of the action: properties that the schema does not declare are removed. Its errors are ignored. ## Total.js schemas and JSON schemas A Total.js schema (`NEWSCHEMA()`) can be converted to a JSON schema with `schema.toJSONSchema()`. The result is registered under the schema name, so actions, `JSONSCHEMA()` and `@Name` in inline declarations can use it. `schema.jsonschema_define()` adds fields that exist only in the converted JSON schema. ```js NEWSCHEMA('Order', function(schema) { schema.define('id', UID, true); schema.define('total', Number); }); ON('ready', function() { GETSCHEMA('Order').toJSONSchema(); JSONSCHEMA('Order', { id: UID(), total: '25' }).then(console.log); }); ``` `$CREATE()` and `$MAKE()` work with the Total.js schema itself: `$CREATE()` returns a model with default values and `$MAKE()` makes and validates a model synchronously. The Total.js Message Service functions `NEWPUBLISH()`, `NEWSUBSCRIBE()` and `NEWCALL()` take the same forms: an inline declaration, a schema name or a schema object. --- title: Workers, threads and cluster project: Total.js V4 version: 0.0.99 section: guides language: en license: MIT url: https://totaljs.es/docs/total-js-v4/0-0-99/guides/workers-and-threads/ updated: 2026-11-16T15:41:10.817Z --- # Workers, threads and cluster > Run code in worker threads and child processes, run shell commands, and run the app as a cluster or as separate threads. A Total.js 4 application runs in one Node.js process by default. When work is too heavy for that process, or when you want to use more CPU cores, the framework gives you four tools: | Tool | What it starts | Typical use | | --- | --- | --- | | `NEWTHREAD()` | A `worker_threads` thread from `/workers/` | CPU-heavy code that shares the process | | `NEWFORK()`, `WORKER()`, `WORKER2()` | A child process from `/workers/` | Isolated jobs, scripts that may crash | | `SHELL()` | A shell command | Running system tools (`convert`, `git`, `tar`) | | Cluster (`options.cluster`) | Several instances of the whole app | Serving HTTP on more cores | The `/threads/` directory is a different feature: it splits one project into several separate apps that run behind the main one (see the last part of this guide). ## The /workers/ directory Worker scripts live in `/workers/` (the config key `directory_workers`, default `/workers/`). `PATH.workers('resize.js')` returns the full path of a file in it. You pass the name without `.js`. A name that starts with `@` points to a package (`PATH.package()`), and for `NEWTHREAD()` and `NEWFORK()` a name that starts with `~` is an absolute path to the script. ## NEWTHREAD() and NEWFORK() `NEWTHREAD(name, [data])` runs `/workers/{name}.js` as a Node.js `worker_threads` thread and returns the `Worker`. `data` reaches the thread as `workerData`. `NEWFORK(name)` runs the same kind of file as a child process and returns the `ChildProcess`. Both objects get the same methods, so the calling code does not change when you switch: ```js var worker = NEWTHREAD('resize', { quality: 90 }); worker.on('message', function(msg) { console.log('Done', msg); worker.kill(); }); worker.postMessage({ filename: PATH.public('photo.jpg') }); ``` On a thread, `kill()` and `exit()` call `terminate()`. On a fork, `postMessage()` is `send()` and `terminate()` sends `SIGTERM`. ## The worker side Inside the worker file, require the framework and call `NEWTHREAD()` (or `NEWFORK()`) **without a name**. It returns a small helper object that works the same in a thread and in a fork: ```js // /workers/resize.js require('total4'); var worker = NEWTHREAD(); worker.message = function(msg) { // worker.data contains the "data" argument of NEWTHREAD() worker.send({ filename: msg.filename, quality: worker.data.quality }); worker.exit(); }; // Kill the worker if it runs longer than 30 seconds worker.setTimeout(30000); ``` | Member | What it does | | --- | --- | | `worker.data` | The `data` of `NEWTHREAD(name, data)`; an empty object in a fork | | `worker.message` | Assign a function; it receives every message from the parent | | `worker.send(msg)` | Sends a message to the parent (alias `postMessage`) | | `worker.exit([code])` | Ends the worker (aliases `kill`, `close`) | | `worker.setTimeout(ms)` | Ends the worker with code `1` after `ms` milliseconds | If the worker needs your schemas, modules or config, call `LOAD()` in it. `LOAD()` loads parts of the app without starting the HTTP server and sets `isWORKER` to `true`: ```js require('total4'); LOAD('config,modules,schemas', function() { var worker = NEWFORK(); worker.message = function(msg) { worker.send(msg); }; }); ``` ## Thread pools `NEWTHREADPOOL(name, count, [isfork])` starts `count` workers of the same file and lends one to each job. `pool.exec(fn)` calls `fn(worker, release)` when a worker is free. Call `release()` when the job is done, or the worker stays busy: ```js var pool = NEWTHREADPOOL('resize', 4); function resize(filename, callback) { pool.exec(function(worker, release) { worker.on('message', function(msg) { release(); callback(null, msg); }); worker.postMessage({ filename: filename }); }); } ``` The pool removes the `message` listeners of a worker before it gives it to the next job. ## WORKER() and WORKER2() `WORKER(name, [timeout], [args])` is the older way to fork `/workers/{name}.js`. It returns the `ChildProcess`, stores it in `F.workers` while it runs, and kills it with `SIGKILL` when `timeout` (milliseconds) passes. The worker uses `process.on('message')` and `process.send()`, or the helper of `NEWFORK()`. `WORKER2(name, [args], callback, [timeout])` runs the script silently, collects its standard output, and calls `callback(err, buffer)` when the process ends. Use it for scripts that print a result. ## SHELL() `SHELL(command, [callback], [cwd])` runs a command with `child_process.exec()` in the app directory (or `cwd`). The callback gets `(err, stdout, stderr)`. Without a callback it returns a promise of the standard output. The config key `default_shell` chooses the shell: ```js var output = await SHELL('git rev-parse HEAD'); ``` Never put user input into the command without escaping it. ## Cluster Set `options.cluster` in the start script to run several instances of the whole app behind one port. The value is a number of instances or `'auto'`: ```js // index.js const options = {}; options.cluster = 4; // options.cluster = 'auto'; // options.cluster_limit = 8; // options.tz = 'Europe/Bratislava'; require('total4/release')(options); ``` The main (master) process starts the instances one after the other. Each instance gets `F.id` (`'0'`, `'1'`, ...) and `F.isCluster === true`. An instance that exits is started again after one second. With `'auto'`, the master starts one instance, measures their response time every five seconds, adds an instance when the average is over 70 ms (up to `cluster_limit`) and removes the last one when there is free capacity. In cluster mode the master sets the time zone of all instances to `options.tz`, or to `'utc'` when you do not set it. Sessions are shared between instances automatically; the cache (`CACHE()`, `F.cache`) only when `allow_cache_cluster` is `true`. The master writes its state to `index.js.json` (the start script name plus `.json`) about every 50 seconds. To restart all instances without stopping the app, create an empty file named `restart` in the app directory; the master restarts the instances two seconds apart and deletes the file. ## Messages between instances `F.cluster.emit(name, [a], [b], [c], [d], [e])` raises the event `name` in **every** instance, the sender included. Listen with `ON()`: ```js ON('products_changed', function(id) { CACHE('products', null); }); F.cluster.emit('products_changed', '123'); ``` `EMIT2()` also reaches the other instances (see [Scheduling and events](../../guides/scheduling-and-events/)). `F.cluster.master(name, ...)` sends an event to the master process only, where `F.cluster.on(name, fn)` registers the listener. The arguments travel as IPC messages, so send only plain, serialisable values. ## The /threads/ directory Set `options.threads` in the start script, and each subdirectory of `/threads/` becomes its own app in its own process: ```js const options = {}; options.threads = '/api/'; // options.logs = 'isolated'; require('total4/release')(options); ``` For `/threads/users/` the main app forwards every request under `/api/users/` to that thread and removes the prefix, so the thread declares `ROUTE('GET /')` for `/api/users/`. With `options.threads = true` the prefix is only the thread name (`/users/`). The global `THREAD` holds the name inside the thread. A thread loads every `.js` file of its directory (also in subdirectories) the way it loads controllers, with `exports.install`. It skips the root `/controllers/` and `/middleware/` but loads the other shared directories (schemas, modules, definitions...). It reads its own `config`, `config-debug`, `config-release` and `.env` files from its directory, its views from `views/` and static files from `public/`. With `options.logs = 'isolated'` its output goes to `/threads/{name}/logs/debug.log`. When you also set `options.cluster`, every thread runs as a cluster of that size. --- title: Message Service and APIs project: Total.js V4 version: 0.0.99 section: guides language: en license: MIT url: https://totaljs.es/docs/total-js-v4/0-0-99/guides/message-service-and-apis/ updated: 2026-11-16T15:41:10.817Z --- # Message Service and APIs > Publish, receive and call over the Total.js Message Service, connect with TMSCLIENT(), call APIs with API() and NEWAPI(), and expose API routes. Total.js 4 has two ways to connect your app with other services: - the **Total.js Message Service (TMS)**, a WebSocket endpoint where your app publishes messages, receives messages and answers remote calls, all described by JSON schemas; - **APIs**, a small layer that sends named requests to an API provider you register with `NEWAPI()` (Total API is registered by default). The same app can also expose its own **API routes**, one URL that runs many actions chosen by name. ## Turning TMS on TMS is off by default. Enable it in `/config`: ``` allow_tms : true secret_tms : my-secret-token ``` The endpoint is `default_tms_url` (`/$tms/`); `default_tms_maxlength` sets the maximum size of a message in kB (default `1024`). With `secret_tms`, a client must send the token in the `x-token` header. A wrong token closes the connection with code `4001`, and an IP address with more than five failed attempts is refused until the daily reset. Without `secret_tms`, every client is accepted. See [Configuration](../../guides/configuration/) for the other options. ## Publishing messages A publish channel tells the clients which messages your app sends and how they look. Declare it with `NEWPUBLISH(name, schema)` and send messages with `PUBLISH(name, data)`: ```js // definitions/tms.js NEWPUBLISH('orders_created', 'id:UID, total:Number, email:Email'); NEWSCHEMA('Orders', function(schema) { schema.action('create', { input: '*email:Email, *total:Number', action: function($, model) { model.id = UID(); NOSQL('orders').insert(model); PUBLISH('orders_created', model); $.success(model.id); } }); }); ``` The schema can be an inline declaration (`'id:UID, total:Number'`), a JSON schema object with an `$id`, or the name of a JSON schema or a Total.js schema. A name that does not exist throws an error. `PUBLISH()` sends the message only to connected clients that subscribed to the channel. With no TMS client connected, or for a channel not declared with `NEWPUBLISH()`, it does nothing. The data is not validated on the server: the client converts it with the schema from the channel. ## Receiving messages A subscribe channel is the other direction: clients send messages and your app handles them. `NEWSUBSCRIBE(name, schema, [callback])` declares the channel and `SUBSCRIBE(name, callback)` adds handlers: ```js NEWSUBSCRIBE('products_updated', '*id:UID, price:Number', function(data, client) { NOSQL('products').modify({ price: data.price }).where('id', data.id); }); // another handler for the same channel SUBSCRIBE('products_updated', function(data) { console.log('Product updated', data.id); }); ``` Every incoming message is validated with the channel's schema; invalid messages are dropped. A handler receives the validated data and the WebSocket client. `UNSUBSCRIBE(name, [callback])` removes one handler, or all of them. ## Remote calls `NEWCALL(name, schema, callback)` registers a call that clients run like a remote procedure. The data is validated first; the callback answers with `next(err, response)`: ```js NEWCALL('products_detail', '*id:UID', function(data, next, client) { NOSQL('products').one().where('id', data.id).callback(next, 404); }); // or run a schema operation NEWCALL('orders_create', '*Orders --> create'); ``` ## Automatic synchronization When you add or remove channels, calls or handlers, the app sends a fresh `meta` message to all clients one second later. The meta lists the app `name`, the `publish`, `subscribe` and `call` channels with their JSON schemas, and the channels your app subscribes to. ## Publishing from actions `schema.action()` and `NEWACTION()` accept a `publish` option. It declares a publish channel named after the action (`Schema.action`, or the action name), and `$.publish(value)` in the action sends to it: ```js NEWACTION('Orders/create', { input: '*email:Email, *total:Number', publish: true, action: function($, model) { model.id = UID(); $.publish(model); $.success(model.id); } }); ``` `publish: true` uses the action's `input` (or `output`) as the channel schema. A string sets its own schema; a string that starts with `+` adds fields to the input. ## Connecting to TMS: TMSCLIENT() `TMSCLIENT(url, [token], [callback])` connects your app to the TMS endpoint of another Total.js app. It reconnects after the server restarts, and it resubscribes automatically: ```js TMSCLIENT('https://orders.example.com/$tms/', 'my-secret-token', function(err, client, meta) { client.subscribe('orders_created', function(data) { console.log('New order', data.id, data.total); }); client.publish('products_updated', { id: '1a2b3c', price: 99 }); client.call('products_detail', { id: '1a2b3c' }, function(err, response) { console.log(err, response); }); }); ``` `client.subscribe()` receives messages of the server's publish channels, converted by their schema. `client.publish()` sends to the server's subscribe channels. `client.call()` runs a remote call; without a callback it returns a promise, and it fails with `TMS is offline` before the connection is ready or `408: Timeout` after 10 seconds. ## APIs: NEWAPI() and API() `API(name, schema, [data])` sends a request to a registered API provider and returns a call object. You chain options and a callback; the request starts on the next tick: ```js API('TotalAPI', 'check').callback(function(err, response) { console.log(err, response); }); // service_name is a placeholder for a Total API service var base64 = await API('TotalAPI', 'service_name', { value: 'Hello' }).output('base64').promise(); ``` `NEWAPI(name, callback)` registers your own provider. The callback receives `opt` (`name`, `schema`, `data`, `controller`, `files`, `output`) and `next(err, response)`. The name `*` registers a fallback for every unknown name: ```js NEWAPI('Payments', function(opt, next) { RESTBuilder.POST('https://payments.example.com/' + opt.schema + '/', opt.data).callback(next); }); API('Payments', 'charge', { amount: 100 }).fail(console.error).data(console.log); ``` Names are not case-sensitive. The built-in provider `TotalAPI` (alias `TAPI`) posts to Total API with the token from `totalapi`; the older `TotalAPI(type, data, callback)` function does the same in one call. ## API routes An API route is one `POST` URL that runs many actions. The client sends `{ "schema": "name/param?query", "data": { ... } }`: ```js exports.install = function() { ROUTE('+API /api/ -orders_list *Orders --> list'); ROUTE('+API /api/ +orders_create *Orders --> create'); ROUTE('+API /api/ -orders_read/{id} *Orders --> read'); ROUTE('+API /api/ -ping', function() { this.success(); }); }; ``` The sign before the name sets the HTTP method used for the action: `+` validates the data like `POST`, `#` like `PATCH`, `-` sends no data like `GET`. URL parameters follow the name. A function instead of `*Schema --> action` handles the call with the controller as `this`. The whole route syntax is in [Routing](../../guides/routing/). --- title: Images project: Total.js V4 version: 0.0.99 section: guides language: en license: MIT url: https://totaljs.es/docs/total-js-v4/0-0-99/guides/images/ updated: 2026-11-16T15:50:05.282Z --- # Images > Resize, crop, convert and measure images with the Image module and GraphicsMagick or ImageMagick. The global `Image` object processes pictures: resizing, cropping, rotating, filters, watermarks and format conversion. It does not process the pixels itself. It builds a command line and runs **GraphicsMagick** or **ImageMagick**, so one of them must be installed on the server. ```js var image = Image.load(PATH.public('photos/beach.jpg')); image.resizeCenter(400, 300); image.quality(85); image.save(PATH.public('photos/beach-small.jpg'), function(err) { err && console.error(err); }); ``` The module also measures the size of images (JPG, PNG, GIF, WebP, SVG, BMP, PSD) from a buffer, in pure JavaScript, without any external tool. ## Requirements Install one of the tools and make it available in the `PATH` of the process: ```text # macOS brew install graphicsmagick # Debian / Ubuntu apt-get install graphicsmagick ``` The config key [`default_image_converter`](../../guides/configuration/) chooses the tool: | Value | Tool | Command that runs | | --- | --- | --- | | `gm` (default) | GraphicsMagick | `gm convert ...` | | `im` | ImageMagick 6 | `convert ...` | | `magick` | ImageMagick 7 | `magick ...` | ```text // /config default_image_converter : im ``` The second argument of `Image.load()` overrides the config for one image. ## Loading an image `Image.load(source, [converter], [width], [height])` creates an `Image` object; `Image.init()` is the same function. The source is a file name, a readable stream or a `Buffer`: ```js var a = Image.load('/www/photos/cat.png'); // file var b = Image.load(Fs.createReadStream(path)); // stream var c = Image.load(buffer, 'magick'); // Buffer, ImageMagick 7 ``` For a file, the output format is its extension. For a stream or a buffer, the output format is `jpg` until you call `image.output()`. ## Building the operations Each method adds a command-line option and returns the image, so calls can be chained. Nothing runs until `save()`, `pipe()` or `stream()`: ```js Image.load(filename) .resize(800) .grayscale() .quality(70) .save(PATH.temp('gray.jpg'), function(err, saved) { console.log(saved); }); ``` The options do not run in the order of your calls. Each one has a fixed priority, and the framework sorts them before it builds the command: | Priority | Methods | | --- | --- | | 1 | `resize()`, `thumbnail()`, `scale()`, `filter()`, `limit()` | | 2 | `background()`, `fill()` | | 3 | `align()` (`-gravity`) | | 4 | `crop()`, `extent()`, first part of `sepia()` | | 5 | `quality()`, second part of `sepia()` | | 6 | `watermark()` | | 8 | `rotate()` | | 10 | `blur()`, `flip()`, `flop()`, `grayscale()`, `normalize()`, `colors()`, `bitdepth()`, `command()` (default) | So `rotate()` always runs after `crop()`. Use `command()` with your own priority when you need another order. ### Resizing | Method | Result | | --- | --- | | `resize(w, h, [options])` | Fits the image into `w` x `h` and keeps the aspect ratio. Omit one side to compute it. | | `resizeCenter(w, h, [color])` | Fills `w` x `h` and crops the overflow around the center. | | `resizeAlign(w, h, [align], [color])` | Like `resizeCenter()`, but crops around `align` (`top`, `bottom left`...). | | `miniature(w, h, [color], [filter])` | Fits the whole image into `w` x `h` and fills the rest with `color`. | | `thumbnail(w, h, [options])` | Like `resize()`, with the `-thumbnail` option of the tool. | | `scale(w, h, [options])` | Fast resize without a filter. | `options` is a string appended to the size, with the meaning the tool gives it: `!` ignores the aspect ratio, `>` only shrinks, `<` only enlarges, `^` fills the area, `%` reads the numbers as percentages: ```js image.resize(1200, 1200, '>'); // never upscale image.resize(50, 50, '%'); // half the size ``` ### Other operations ```js image.crop(200, 200, 10, 10); // w, h, x, y image.rotate(90); image.flip(); // vertical mirror image.flop(); // horizontal mirror image.blur(3); image.grayscale(); image.sepia(); image.watermark(PATH.public('img/logo.png'), 10, 10); image.background('#FFFFFF'); image.minify(); // removes EXIF and other profiles ``` `make(fn)` calls `fn` with the image, so you can group operations in a function and reuse it: ```js function avatar(image) { image.resizeCenter(128, 128); image.quality(80); } Image.load(filename).make(avatar).save(target); ``` ## Quality `quality(percentage)` sets the compression quality (`-quality`). Without an argument it uses **80**. An image without `quality()` gets the default quality of GraphicsMagick or ImageMagick. ## Output `save([filename], [callback])` runs the command and writes the result. Without a file name, it overwrites the source file. The format of the saved file comes from the extension of `filename`: ```js Image.load(PATH.public('photo.jpg')).resize(300).save(PATH.public('photo.webp')); ``` `pipe(stream, [type])` sends the result into a writable stream, and `stream([type])` returns a readable stream. Here the format is `type`, or the value of `output()`, or the extension of the source file. Supported types are `jpg`, `jpeg`, `png`, `gif`, `apng`, `heif`, `heic`, `webp` and `ico`: ```js var file = Fs.createWriteStream(PATH.temp('out.png')); Image.load(buffer).resize(100).pipe(file, 'png'); ``` When an image has no operation at all, `save()`, `pipe()` and `stream()` add `minify()` on their own. ## Measuring images `Image.measure(type, buffer)` reads the width and height from the first bytes of a file. `type` is an extension (`.png` or `png`) or a MIME type (`image/png`): ```js var size = Image.measure('.png', buffer); // { width: 800, height: 600 } ``` There are also functions for each format: `Image.measureJPG()`, `Image.measurePNG()`, `Image.measureGIF()`, `Image.measureWEBP()`, `Image.measureSVG()`, `Image.measureBMP()` and `Image.measurePSD()`. The framework uses them for uploaded files, which is why `file.width` and `file.height` are filled for images. To measure a file on disk, use `image.measure(callback)` (JPG, PNG, GIF, WebP) or `image.identify(callback)`, which asks the external tool and works for any format it knows. ## Images in responses In a route, `controller.image()` and `res.image()` load an image, let you set the operations and send the result with a cache. `RESIZE()` creates resized copies of static images on demand: ```js RESIZE('/img/small/*.jpg', function(image) { image.resize(200, 200); image.quality(80); }, ['/img/']); ``` Both are described in [Static files](../../guides/static-files/). Images from a FileStorage are loaded with `FILESTORAGE(name).image()`, see [File storage](../../guides/file-storage/). ## Output middleware `Image.middleware(type, fn)` registers a function that returns a transform stream. Every output of that type passes through it, for example a PNG optimizer: ```js // a stream that receives all PNG output Image.middleware('png', function() { var Stream = require('stream'); return new Stream.PassThrough(); }); ``` The function must return a new stream on each call. With `save()`, the result is written to the file first, then passed through the stream and written again. --- title: HTTP server: CORS, proxy and errors project: Total.js V4 version: 0.0.99 section: guides language: en license: MIT url: https://totaljs.es/docs/total-js-v4/0-0-99/guides/http-server/ updated: 2026-11-16T15:41:10.817Z --- # HTTP server: CORS, proxy and errors > Start the HTTP server, allow cross-origin requests, forward and redirect requests, and design error pages. This page covers the parts of the HTTP server that are not routes: starting the server, CORS, reverse proxies, redirects, the sitemap and error pages. Routes themselves are explained in [Routing](../routing/). ## Starting the server The start script calls `HTTP()` (or `HTTPS()` when you pass `https` keys). You can also call it yourself: ```js require('total4'); HTTP('release', { port: 8000, ip: '127.0.0.1', config: { name: 'My app' } }); ``` The first argument is the mode: `'debug'` or `'release'`. The options are: | Option | What it does | | --- | --- | | `port` | The port. Without it, the config key `default_port` is used, and then `8000` | | `ip` | The address to listen on. Without it, `default_ip`, and then `0.0.0.0` | | `unixsocket` | Listens on a Unix socket instead of a port | | `unixsocket777` | Sets the permissions of the socket file to `0777` | | `config` | An object whose values are written into `CONF` | | `https` | `{ key, cert }` for an HTTPS server | | `middleware` | `function(listen)` that decides when the server starts listening | | `id` | The identifier of the instance, kept in `F.id` | A number on the command line (`node index.js 8080`) sets the port when the options do not have one. Any other argument that does not start with `--` and is not a URL is used as a Unix socket path. ```js require('total4'); HTTPS('release', { port: 443, https: { key: 'keys/server.key', cert: 'keys/server.crt' } }); ``` A `key` or `cert` that contains a dot is read as a file. Without a dot, it is decoded from base64. After the start, `F.server` is the Node.js server and `F.port` and `F.ip` hold the address. ## CORS `CORS()` lets browsers on other origins call your routes. It answers the preflight `OPTIONS` request itself with status `200`. ```js exports.install = function() { // All paths below /api/, from two origins, with cookies CORS('/api/*', ['https://app.example.com', 'https://admin.example.com', 'credentials']); ROUTE('GET /api/products/', products); }; ``` The flags in the array are: - Origins: `'https://example.com'`, `'http://example.com'` or `'//example.com'`. - HTTP methods: `'get'`, `'post'`, `'put'`, `'patch'`, `'delete'`, `'head'`, `'options'`. Without them, all methods are allowed. - A number: the `Access-Control-Max-Age` in seconds (otherwise `default_cors_maxage`, `120`). - `true` or `'credentials'`: sends `Access-Control-Allow-Credentials: true`. Without origins, the config key `default_cors` gives the list. Without that, any origin is allowed. A request from an origin that is not on the list gets an empty `404`. Two short forms cover the whole application: ```js CORS(); // every path, every origin CORS('https://app.example.com, https://example.com'); // every path, these origins ``` The routing flag `cors` (`ROUTE('POST /api/orders/', fn, ['cors'])`) registers a CORS rule for that one URL. `CORS()` returns an object with `remove()`, which deletes the rule again. ## Reverse proxy `PROXY(url, target)` sends every request whose path starts with `url` to another server and streams its answer back. The `url` must end with `/`. ```js exports.install = function() { PROXY('/api/', 'http://127.0.0.1:8001'); }; ``` The target can be an `http://` or `https://` address or the path of a Unix socket. Proxies run before redirects, middleware and routes, and also forward WebSocket connections. The third argument says how the path is passed on: | `copypath` | `/api/users/?page=2` to `http://server/v1` becomes | | --- | --- | | not set | `/v1/api/users/?page=2` | | `true`, `'replace'` or `'extend'` | `/v1/users/?page=2` (the prefix is removed) | | `false` | `/v1` | With a target without a path (`http://server`), `'replace'` removes the prefix and `true` keeps it. The framework adds the headers `X-Forwarded-For`, `X-Forwarded-Url` and `X-Forwarded-Host`. If the target does not answer, the client gets the error page `503`. ```js PROXY('/files/', 'http://127.0.0.1:8002', 'replace', function(uri, req, res) { uri.headers['x-token'] = CONF.filestoken; }, null, req => req.method === 'GET', 5000); ``` ## Redirects `REDIRECT()` has two forms. With full addresses it redirects a whole host, before routing: ```js // http://example.com/anything -> https://www.example.com/anything REDIRECT('http://example.com', 'https://www.example.com', true, true); ``` The third argument keeps the path and the query, the fourth makes the redirect permanent (`301`). With paths, it creates a route that redirects one URL and keeps the query string: ```js REDIRECT('/old-shop/', '/shop/', true); // 301 Moved Permanently REDIRECT('/docs.pdf', 'https://cdn.example.com/docs.pdf'); ``` ## Error pages Every error status first looks for a status route: `#400`, `#401`, `#403`, `#404`, `#408`, `#409`, `#431`, `#500`, `#501` and `#503`. ```js exports.install = function() { ROUTE('#404', notfound); ROUTE('#500', servererror); }; function notfound() { this.status = 404; this.view('404'); } function servererror() { this.status = 500; this.view('500', { error: this.exception }); } ``` Without such a route, the framework answers with its built-in HTML page. For XHR requests (`default_errorbuilder_forxhr`) and when `default_errorbuilder_errors` is on, it answers with JSON errors instead. In middleware and file handlers, `res.throw404()` and its siblings start the same process. See also [Controllers](../controllers/). `F.error(err, name)` logs an error, and `ERROR(name)` returns a callback that does it: ```js F.Fs.unlink(PATH.temp('export.csv'), ERROR('unlink export')); ``` `SUCCESS()` builds the `{ success: true }` object that `$.success()` also returns. `FINISHED(stream, fn)` calls `fn` when a request, response or stream ends, and `DESTROY(stream)` closes a stream. --- title: Sitemap project: Total.js V4 version: 0.0.99 section: guides language: en license: MIT url: https://totaljs.es/docs/total-js-v4/0-0-99/guides/sitemap/ updated: 2026-11-16T15:41:10.817Z --- # Sitemap > Describe the pages of a website in the sitemap file and use it for navigation and breadcrumbs. The file `sitemap` in the root of the application describes the pages of a website. Each line is `id : title --> url --> parent`: ```text // sitemap homepage : Homepage --> / products : Products --> /products/ --> homepage detail : {0} --> /products/{0}/ --> products contact : @(Contact) --> /contact/ --> homepage ``` Lines that start with `#` or `// ` are comments. `@(...)` around a title or URL translates it with the [localization](../localization/) resources. `{0}` is a placeholder that you fill later, and a URL that ends with `*` is a wildcard. A route can use the ID instead of the URL. Without an action, the route renders the view with the name of the ID (`index` for `/`): ```js exports.install = function() { ROUTE('#homepage'); ROUTE('#products', 'products/list'); ROUTE('GET #detail', detail); }; function detail(id) { this.sitemap(); this.sitemap_change('detail', 'name', 'Product ' + id); this.view('products/detail'); } ``` `#id` also works in `WEBSOCKET()`, `MERGE()`, `MAP()` and `LOCALIZE()`. A route with an unknown ID throws an error. For an ID route with a view name or no action, the framework loads the breadcrumb itself; in your own action call `this.sitemap()`. It also sets the page title to the name of the current item. Views read the breadcrumb as `sitemap`: ```html @{sitemap_name('products')} ``` `SITEMAP(id)` returns the breadcrumb outside a controller, and `F.sitemap_navigation(parent)` the items with one parent, for menus. --- title: Cache, counters and small stores project: Total.js V4 version: 0.0.99 section: guides language: en license: MIT url: https://totaljs.es/docs/total-js-v4/0-0-99/guides/caching-and-small-stores/ updated: 2026-11-16T15:41:10.817Z --- # Cache, counters and small stores > Keep values in the in-memory cache, in files and in preferences, count statistics, and back up folders. Total.js has several small stores for data that does not need a full database: an in-memory cache, preferences, a persistent object, file caches, counters and two extra text databases. All of them are global functions, so every file of an app can use them. | Function | Where the data lives | Use it for | | --- | --- | --- | | `CACHE()` / `F.cache` | Memory of the process | Values that expire, for example results of slow queries | | `FILECACHE()` | A file in the `tmp/` folder | Results that should survive a restart and expire | | `PREF` | `databases/preferences.json` | Settings that the app changes at run time | | `MEMORIZE()` | `databases/memorize_{name}.json` | A plain object saved to a file | | `COUNTER()` | `databases/{name}.counter` | Daily statistics of hits or amounts | | `INMEMORY()` | Memory, saved to `databases/{name}.inmemory` | A small NoSQL collection kept in memory | | `TEXTDB()` | Files in `databases/textdb-{name}/` | A NoSQL collection split into several files | `BACKUP()` and `RESTORE()` pack files of a folder into one file and unpack them again. `MODIFY()` changes the content of views, styles, scripts and localized static files before Total.js compiles them. ## The in-memory cache `CACHE(key, value, [expire])` saves a value and `CACHE(key)` reads it. The value is kept in the memory of the process, so it is lost after a restart. The expiration is a text such as `'5 minutes'` or `'1 hour'`, or a `Date`. Without it the value expires in 5 minutes. ```js CACHE('products', items, '10 minutes'); var items = CACHE('products'); // undefined after 10 minutes ``` `F.cache` is the object behind `CACHE()`. It has more methods: ```js F.cache.set('user_' + id, user, '1 hour'); F.cache.get('user_' + id, null); // the second argument is a default value F.cache.setExpire('user_' + id, '2 hours'); // a new expiration F.cache.remove('user_' + id); F.cache.removeAll('user_'); // every key that contains "user_" F.cache.clear(); // everything ``` Total.js checks the cache once a minute and removes expired items. It emits the events `cache_set` and `cache_expired` (see [Scheduling and events](../../guides/scheduling-and-events/)). The option `allow_cache_snapshot` saves the whole cache to `databases/cache.json` every minute and loads it at start, and `allow_cache_cluster` copies changes to the other processes of a cluster (see [Configuration](../../guides/configuration/)). ### Read or create a value `F.cache.fn()` returns a cached value or calls your function to make it. The function receives `next(value, [expire])`: ```js F.cache.fn('stats', function(next) { NOSQL('orders').count().callback(function(err, count) { next({ count: count }, '5 minutes'); }); }, function(value, fromcache) { console.log(value.count, fromcache); }); ``` A value that is `false`, `0`, `''` or `null` does not count as cached, so the function runs again. ## A cache in a file `FILECACHE(id, expire, callback, maker, [encoding])` works like `F.cache.fn()`, but it saves the value to a file in the `tmp/` folder. The file stays valid until it is older than `expire`, even after a restart. The `maker` function receives `next(err, value)`: ```js FILECACHE('exchange-rates', '1 hour', function(err, rates) { console.log(rates); }, function(next) { RESTBuilder.GET('https://example.com/rates.json').callback(next); }); ``` The value is saved as JSON. Pass `'utf8'` as `encoding` to keep a text as it is. See [HTTP requests](../../guides/http-requests/) for `RESTBuilder`. ## Preferences `PREF` holds values that the app sets at run time and that must survive a restart, for example a token or the date of the last import. Total.js loads them at start from `databases/preferences.json`. Read a value as a property and write it with `PREF.set()`: ```js PREF.set('last_import', NOW); PREF.inc('imports'); // adds 1 and returns the new value if (PREF.last_import) console.log(PREF.last_import); ``` Changes are written to the file one second after the last change. To keep the preferences somewhere else (for example in SQL), replace the delegates `DEF.onPrefLoad` and `DEF.onPrefSave` in a definition file. ## A persistent object `MEMORIZE([name], [delay], [skip])` reads `databases/memorize_{name}.json` (or `databases/memorize.json` without a name) and returns it as an object. Change the object and call `save()`: Total.js writes it after `delay` milliseconds (10 seconds by default), so many changes give one write. ```js var settings = MEMORIZE('settings'); settings.theme = 'dark'; settings.save(); ``` Every call reads the file again and returns a new object: call `MEMORIZE()` once and keep the object. The `skip` argument lists keys that are not saved, for example temporary data. ## Counters `COUNTER(name)` counts hits or amounts per day. `hit(id, [value])` adds a value in memory; about every five minutes Total.js writes the sums to `databases/{name}.counter`, one document per id and day with `sum`, `min` and `max`. ```js COUNTER('visits').hit('homepage'); COUNTER('sales').hit('eshop', 49.90); COUNTER('visits').monthly('homepage', function(err, months) { // [{ date: '202611', year: 2026, month: 11, sum: 1520, count: 15, min: 1, max: 1 }] }); ``` Hits that are not written yet are lost if the process stops; call `flush()` to write them earlier. ## INMEMORY and TEXTDB `INMEMORY(name)` and `TEXTDB(name)` return a database with the same methods as `NOSQL()` (see [NoSQL database](../../guides/nosql/)). - `INMEMORY()` keeps all documents in memory and writes them to `databases/{name}.inmemory` 5 seconds after a change. It is fast for a small collection that is read often. It supports `insert()`, `find()`, `read()`, `list()`, `count()`, `scalar()`, `modify()` and `remove()`. - `TEXTDB()` keeps documents in the folder `databases/textdb-{name}/`, in several files of about 512 kB. Use it for a collection that grows. ```js INMEMORY('sessions').insert({ id: UID(), userid: user.id, created: NOW }); INMEMORY('sessions').find().where('userid', user.id).callback(console.log); ``` ## Backup and restore of files `BACKUP(filename, path, [callback], [filter])` packs all files of a folder (or a list of files) into one text file. Each file is compressed with GZIP. `RESTORE(filename, target, [callback], [filter])` unpacks it into a folder. ```js BACKUP(PATH.temp('public.backup'), PATH.public(), function(err, meta) { console.log(meta.files, meta.size); }); RESTORE(PATH.temp('public.backup'), PATH.root('public2'), function(err, meta) { console.log(meta.files); }); ``` --- title: Application structure and modes project: Total.js V4 version: 0.0.99 section: guides language: en license: MIT url: https://totaljs.es/docs/total-js-v4/0-0-99/guides/application-structure/ updated: 2026-11-16T15:41:15.818Z --- # Application structure and modes > Which directories Total.js 4 loads and in which order, debug and release modes, bundles, packages and workers. A Total.js 4 application is a directory. You do not register files: the framework reads well-known directories when it starts, `require()`s every script it finds and calls its `exports.install()`. This page explains which directories are read and in which order, how the debug and release modes differ, how bundles and packages work, and how to test the application. ## Starting the application The start script (usually `index.js`) loads `total4/debug` or `total4/release` and passes an options object. Both modules export a function: ```js var options = {}; // options.port = 8000; // options.ip = '127.0.0.1'; // options.watch = ['adminer']; // options.livereload = true; require('total4/debug')(options); ``` For production, use `require('total4/release')(options)`. A free command-line argument is read as the port (`node index.js 8001`), as `http://ip:port`, or otherwise as the path of a Unix socket. | | `total4/debug` | `total4/release` | | --- | --- | --- | | `DEBUG` / `RELEASE` | `true` / `false` | `false` / `true` | | Process | A watcher process forks the app | The app runs in the same process, unless `--watcher` or `options.watcher` is set | | Restart | On every change in the watched directories | Only when the app exits or asks for a restart | | Files `*-debug.js` | Loaded | Skipped | | Files `*-release.js` | Skipped | Loaded | | Source maps | Generated (unless `CONF.nosourcemap`) | Not generated | Both modes write a `.pid` file named like the start script (`index.pid`). Delete it and the process ends within about four seconds. That is a simple way for a deployment script to stop the app. ## What the watcher watches In debug mode the watcher looks every few seconds at `.js`, `.ts`, `.resource`, `.package`, `.bundle`, `.build`, `.flow` and `.url` files, at `jsonschemas/*.json` and at the configuration files in the root (`config`, `config-debug`, `config-release`, `versions`, `sitemap`, `bundles.debug`). It reads the directories `components`, `controllers`, `definitions`, `operations`, `extensions`, `modules`, `models`, `builds`, `jsonschemas`, `schemas`, `actions`, `tasks`, `resources`, `source`, `workers`, `packages`, `themes`, `middleware`, `configs`, `bundles`, `flowstreams`, `startup`, `threads` and `plugins`, plus the directories in `options.watch`. Views and public files do not cause a restart. With `options.livereload` the watcher also watches them and tells the browser to reload. Each change prints a line (`ADD`, `UPD`, `REM`) and restarts the app. The event `ON('watcher', process)` runs in the watcher process; `ON('debug_start')` and `ON('debug_restart')` run in the app (see [Scheduling and events](../scheduling-and-events/)). ## The load order When the server starts, the framework reads the directories below in this order. Every directory has a `CONF.directory_*` key (see [Configuration](../configuration/)), and scripts in subdirectories are loaded too. | # | Directory | What is loaded | | --- | --- | --- | | 1 | `/jsonschemas/` | `*.json` and `*.txt` JSON schemas | | 2 | `/modules/` | Modules, available through `MODULE()` and `MODS` | | 3 | `/packages/` | `.package` files or directories | | 4 | `/models/` | Models, available through `MODEL()` | | 5 | `/schemas/` | Schemas (see [Schemas](../schemas/)) | | 6 | `/actions/` | Actions | | 7 | `/tasks/` | Tasks | | 8 | `/operations/` | Operations (see [Operations and tasks](../operations-and-tasks/)) | | 9 | `/themes/` | Each subdirectory is a theme, its `index.js` is installed | | 10 | `/definitions/` | Definitions: global code, delegates, `AUTH()` | | 11 | `/controllers/` | Controllers with routes | | 12 | `/components/` | `.html` components | | 13 | `/middleware/` | Middleware | | 14 | `/builds/` | `.build` and `.url` files of UI Builder | | 15 | `/extensions/` | Extensions, through `NEWEXTENSION()` | | 16 | `/plugins/` | `plugins/{name}/index.js` and `plugins/{name}.html` | | 17 | `/flowstreams/` | `.flow` files (see [FlowStream](../flowstream/)) | The order is the order of installation, not of `require()` only. Everything you declare in a definition already sees the models, schemas and operations. When all files are installed, the framework sorts the routes, loads the preferences and emits `load` and `ready`. A plugin is a small application inside `plugins/{name}/`. Besides its `index.js`, the framework loads its own `definitions`, `operations`, `actions`, `schemas`, `tasks` and `flowstreams` directories. Some files are always skipped: names that start with a dot, and names that end with `-bk.js` or `_bk.js`. Use these suffixes to keep an old copy next to the new one. ## exports.install Each file can export `install(options)`. The framework calls it once, right after `require()`. The argument is the configuration key `{type}_{name}`, for example `module_mail` for `/modules/mail.js`: ```js // /modules/mail.js exports.install = function(options) { // options === CONF.module_mail }; exports.send = function(to, subject, body) { // ... }; ``` After installation the framework emits `ON('install', type, name, module)`. ## Using installed code ```js // A module MODULE('mail').send('info@example.com', 'Hello', 'Body'); MODS.mail.send('info@example.com', 'Hello', 'Body'); // A model var Product = MODEL('product'); // A plugin PLUGINS.dashboard.id; // 'dashboard' // A source file (/source/helpers.js), loaded the first time you ask for it var helpers = INCLUDE('helpers'); // Any script relative to the application directory var tools = REQUIRE('lib/tools.js'); ``` ## Bundles A bundle is one `.bundle` file that contains a whole application or a part of it. Put bundles into `/bundles/`. On start the framework extracts every bundle into the hidden directory `/.src/`, then copies the files of the application over it, and runs the application from `/.src/`. - Files of the application win over files of the bundle, so you can override a single view or a script. - `config`, `config-debug`, `config-release`, `sitemap`, `versions`, `workflows`, `dependencies` and `.resource` files are merged, not replaced. - A file whose name starts with `--` is appended to the file without the prefix: `/public/css/--custom.css` is appended to `/public/css/custom.css`. - Existing files in `/databases/` and `/updates/` are never overwritten. - A `.url` file in `/bundles/` contains a URL; the bundle is downloaded from it. - `.bundleignore` in the root lists paths that are not copied. Create a bundle with the command line: `total4 bundle app.bundle`. Extract one with `total4 extract app.bundle`. ## Packages A package is a `.package` file (or a directory named `name.package`) in `/packages/`. It is extracted into the temporary directory and its `index.js` is installed. Read its files with `PATH.package('name/file.txt')`. ## Loading without a server `LOAD()` installs the application without starting the HTTP server. Use it in scripts, workers and tests: ```js require('total4'); LOAD('config,definitions,models,schemas,operations', function() { // the code is installed }); ``` ## Workers `/workers/` contains scripts that run in a separate process (`WORKER()`, `NEWFORK()`) or a worker thread (`NEWTHREAD()`). They are not installed on start. --- title: Testing project: Total.js V4 version: 0.0.99 section: guides language: en license: MIT url: https://totaljs.es/docs/total-js-v4/0-0-99/guides/testing/ updated: 2026-11-16T15:41:15.818Z --- # Testing > Run groups of tests with TESTER() and send virtual requests to your routes with TEST() and ACTION(). There are two tools. `TESTER()` runs groups of tests in order and stops at the first failure. `TEST()` sends virtual requests to your routes with `ACTION()`, without any HTTP connection: ```js require('total4'); LOAD('config,definitions,schemas,controllers', function() { TESTER(function(group, start) { group('Products', function(test) { test('List', function(next) { ACTION('GET /api/products/', function(err, response) { next(err); }); }); }); start(); }); }); ``` `TEST()` collects many requests and reports the result as an object, as JSON or as an HTML page. --- title: LDAP project: Total.js V4 version: 0.0.99 section: guides language: en license: MIT url: https://totaljs.es/docs/total-js-v4/0-0-99/guides/ldap/ updated: 2026-11-16T15:41:10.817Z --- # LDAP > Read entries from an LDAP server such as Active Directory with LDAP(). `LDAP(opt, [callback])` reads entries from an LDAP server such as Active Directory. It binds with a user and a password, then searches a base DN for entries of one `objectClass`. ```js LDAP({ ldap: { host: '10.0.0.5', port: 389 }, user: 'CN=reader,OU=Services,DC=company,DC=local', password: CONF.ldap_password, type: 'person', dn: 'OU=Users,DC=company,DC=local' }, function(err, users) { if (err) return; for (var user of users) console.log(user.sAMAccountName, user.mail); }); ``` | Option | Meaning | | --- | --- | | `ldap` | `{ host, port }`, the port defaults to `389` | | `user`, `password` | The account used to bind | | `type` | `person`, `group` or `profile` | | `dn` | The base DN of the search | | `login` | The `sAMAccountName` searched by the `profile` type | | `noauth` | `true` searches without binding | Each entry is a plain object with attribute names as keys. When an attribute has more values (for example `memberOf`), its value is an array. The `profile` type returns one object or `null`. Without a callback the function returns a Promise: ```js var user = await LDAP({ ldap: { host: '10.0.0.5' }, user: 'reader@company.local', password: CONF.ldap_password, type: 'profile', dn: 'DC=company,DC=local', login: 'peter' }); ``` The connection is not encrypted (plain LDAP), so use it in a trusted network. --- title: Markdown project: Total.js V4 version: 0.0.99 section: guides language: en license: MIT url: https://totaljs.es/docs/total-js-v4/0-0-99/guides/markdown/ updated: 2026-11-16T15:41:20.819Z --- # Markdown > Convert Markdown to HTML with String.markdown() and choose what it produces with its options. Every string has the method `markdown([opt])`, which returns HTML: ```js var html = '# Hello\n\nThis is **bold**, _underlined_ and `code`.\n\n- one\n- two\n\t- nested'.markdown(); ``` The parser supports headlines (`#` to `#####`), lists with `-`, `*` or `+` and ordered lists (`1.` or `a.`), task lists (`- [x] done`), tables with alignment, code blocks with a language, blockquotes (`> `), sections (`< `), collapsible blocks between `:::` lines, horizontal lines (`---`, `***`), images (`![alt](url)`, `![+alt](url)` without the responsive class, `![-alt](url)` for a gallery), links, footnotes (`[1](#1)` and `#1: text`), keywords (`{text}(type)`), icons (`:ti-home:` or `:fa fa-home:`), and links detected in plain text. Links to an e-mail address or a phone number become `mailto:` and `tel:` links. HTML in the source is always encoded, so the output is safe to put into a page. Every block has the class `markdown-line` and its line number, which helps you style the output and map it back to the source. Options change the output: ```js var html = text.markdown({ wrap: false, // no
    linetag: 'div', // tag of normal lines (default 'p') bookmarks: true, // id="..." for headlines (default true) prefix: 'help-', // prefix of those ids tables: false, // turn off a feature html: function(line, type) { return type === '#' ? line.toUpperCase() : line; } }); ``` Every feature can be turned off with `false`: `headlines`, `ul`, `code`, `images`, `links`, `formatting`, `icons`, `tables`, `br`, `hr`, `blockquotes`, `sections`, `blocks`, `footnotes`, `urlify`, `keywords` and `emptynewline`. The `custom` function changes each raw line before formatting, so you can add your own syntax. --- title: HTML parser project: Total.js V4 version: 0.0.99 section: guides language: en license: MIT url: https://totaljs.es/docs/total-js-v4/0-0-99/guides/html-parser/ updated: 2026-11-16T15:41:20.819Z --- # HTML parser > Parse HTML on the server into a tree of nodes that you can search and change. `String.parseHTML([trim])` turns HTML into a tree of nodes. It is a small parser for reading and editing documents on the server, not a full browser DOM. ```js var dom = ''.parseHTML(true); var links = dom.find('a'); for (var a of links) { if (a.attr('href').indexOf('http') === 0) a.attr('target', '_blank').aclass('external'); } console.log(dom.html()); ``` `find()` supports tag names, `*`, `#id`, `.class`, `[attr="value"]`, descendants (`ul li`), direct children (`ul > li`) and more selectors separated by commas. `closest()` searches the ancestors. The result is an array with a few extra methods (`aclass()`, `rclass()`, `tclass()`, `attr()`, `attrd()` and `html()`) that apply to all found elements. A node has `tagName` (upper case), `attrs`, `children`, `parentNode` and, for text nodes, `textContent`. You can change it with `attr()`, `attrd()`, `aclass()`, `rclass()`, `tclass()`, `css()`, `append()`, `prepend()` and `remove()`, and serialize it with `html([formatted])`. `text()` returns the text without tags and with decoded entities: ```js var dom = '

    News & updates

    Text

    '.parseHTML(); for (var script of dom.find('script')) script.remove(); var title = dom.find('h1')[0].text(); // News & updates var clean = dom.html(true); ``` Comments are removed and `` is skipped. --- title: Macros project: Total.js V4 version: 0.0.99 section: guides language: en license: MIT url: https://totaljs.es/docs/total-js-v4/0-0-99/guides/macros/ updated: 2026-11-16T15:41:10.817Z --- # Macros > Compile a small rule language into a function with NEWMACRO(), for rules that users write. `NEWMACRO(str, [nocompile], [isasync])` compiles a small rule language into a function. It is useful when users write rules in your application (prices, discounts, validations) and you do not want to run their JavaScript. ```js var macro = NEWMACRO([ '// discount rule', 'IF total > 1000 AND vip', ' RETURN discount(total, 15)', 'ELSE IF total > 500', ' RETURN discount(total, 5)', 'FI', 'RETURN total' ].join('\n')); var helpers = {}; helpers.discount = function(value, percentage) { return value - (value / 100 * percentage); }; macro({ total: 1200, vip: true }, helpers); // 1020 ``` The language has `IF`, `ELSE IF`, `ELSE`, `FI`, `RETURN`, `AND`, `OR`, the values `TRUE`, `FALSE`, `YES`, `NO`, `OK` and `NULL`, quoted values, comments with `//` and private variables with `#`: ```js var macro = NEWMACRO('#price = price * count\nIF #price > 100\nRETURN "big"\nFI\nRETURN "small"'); ``` Names are converted to lower case, so properties of the model and names of helpers must be lower case. Avoid property names that contain the words `if` or `else`, because the compiler replaces them as keywords. With `isasync` the helpers can be async functions and the macro returns a Promise. With `nocompile` you get the generated JavaScript, which helps when you debug a rule. --- title: CMS compiler project: Total.js V4 version: 0.0.99 section: guides language: en license: MIT url: https://totaljs.es/docs/total-js-v4/0-0-99/guides/cms/ updated: 2026-11-16T15:41:10.817Z --- # CMS compiler > Compile pages made with the Total.js CMS editor and render them with their widgets. `CMSCOMPILER(html, widgets, [used])` compiles a page made with the Total.js CMS editor. Widgets in the HTML are marked with `data-cms="id__config"`. The compiler removes the editor markup, keeps static parts as strings and prepares widgets for rendering, so one page can be compiled once and rendered many times. ```js var widgets = []; widgets.push({ id: 'contact', css: '.contact{padding:20px}', render: function(opt, next) { // opt.config is the widget configuration from the editor next('' + opt.config.email + ''); } }); var page = CMSCOMPILER(html, widgets); page.importcss().importjs().importmeta('Contact'); exports.install = function() { ROUTE('GET /contact/', function() { var $ = this; page.render({ url: $.url }, function(err, html) { $.html(html); }); }); }; ``` `render(meta, [layout], [callback])` calls the widgets and builds the HTML. A widget calls `next(html, [replace], [cache])`; with `cache` its output is stored in the compiled page and reused. A layout is a compiled page with an element `id="CMS"`; pass it as the second argument and the page is inserted into it. Navigations (` @{end}

    Statistics

    ``` Example: In the layout ```html @{body} @{section('scripts')} ``` ### @{helper name(arguments)} ... @{end} Type: `command` Defines a helper inside the view. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `name` | `String` | yes | | The name of the helper. | | `arguments` | `String` | yes | | Names of the arguments, as in a JavaScript function. | The helper exists only in this view. Call it by its name; its output is not encoded again. For helpers shared by all views use `DEF.helpers`. Example: Inline helper ```html @{helper badge(text, color)} @{text} @{end} @{badge('New', 'green')} @{badge('Sale', 'red')} ``` ### DEF.helpers.name = function(...args) {} Type: `property` Defines view helpers available in all views. Add the functions before the views are compiled, for example in `definitions/`. In a view, call the helper by its name: `@{name(arguments)}`; `@{helpers.name(arguments)}` and `@{helper('name', arguments)}` work too. Inside the function `this` is the controller. The returned value is printed without encoding. Example: Define ```js // definitions/helpers.js DEF.helpers.price = function(value, currency) { return value.format(2) + ' ' + (currency || 'EUR'); }; DEF.helpers.active = function(path) { return this.url === path ? ' class="active"' : ''; }; ``` Example: Use ```html @{price(item.price, 'USD')} Products ``` ### @(Text) Type: `command` Marks text for translation; it is replaced when the view is compiled. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `Text` | `String` | yes | | The text in the default language, or `#key`. | The text is translated with the language of the controller (`controller.language`, which comes from `DEF.onLocale`). The translation is read from the resource file of the language under a key made from the hash of the text; when there is none, the original text stays. `@(#key)` reads `key` from the resource directly. Inside quotes, quotes in the translation are escaped. Each language gets its own compiled view. Example: Translated text ```html

    @(Products)

    @(#footer_note)

    ``` ### @{resource([name], key)} Type: `command` Prints a value from a resource file, HTML-encoded. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `name` | `String` | no | `default` | The resource file without extension. | | `key` | `String` | yes | | The key. | Returns: `String` The value, or an empty string. Without `name` the value comes from `default.resource`. When a key is missing in another file, the value from `default.resource` is used. `@{!resource(...)}` prints it raw. Example: Resource values ```html

    @{resource('welcome')}

    @{resource('en', 'welcome')}

    ``` ### @{import(file1, [file2], ...)} Type: `command` Writes the HTML tags for static files and for the head of the page. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `file` | `String` | yes | | A file name or one of the keywords. As many as you need. | Returns: `String` HTML tags. Each argument is one of: | Argument | Output | | --- | --- | | `'meta'` | Title and meta tags, see `@{meta}` | | `'head'` | The author meta tag and the tags added with `@{head()}` | | `'file.css'` | `` from `/css/` | | `'file.js'` | ` ``` ### @{meta} / @{meta(title, [description], [keywords], [image])} Type: `command` Prints the title and meta tags of the page, or sets them. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `title` | `String` | no | | The title. | | `description` | `String` | no | | The description. | | `keywords` | `String|Array` | no | | Keywords. | | `image` | `String` | no | | An image for social networks, an absolute URL or a file in `/img/`. | Returns: `String` HTML tags, or an empty string when setting. Without arguments it prints ``, the description and keywords meta tags, and `og:image` and `twitter:image` when an image is set. With arguments it sets the values and prints nothing. The title gets ` - ` and `CONF.name` at the end unless `allow_custom_titles` is `true`. To change the output, replace `DEF.onMeta`. Example: Set in the view, print in the layout ```html @{meta(model.name, model.summary, model.tags, model.picture)} <!-- layout.html --> <head> @{meta} </head> ``` ### @{title} / @{title(value)} / @{title2(value)} Type: `command` Prints or sets the title of the page. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `value` | `String` | no | | The title. | Returns: `String` The title, or an empty string when setting. `@{title(value)}` sets the title and prints nothing; `@{title2(value)}` appends to the current title. `@{title}` prints the title alone. The value is HTML-encoded when it is set, so `@{!title}` prints it without encoding it twice. To print the whole `<title>` tag, use `@{meta}`. Example: Title ```html @{title(model.name)} <h1>@{!title}</h1> ``` ### @{description(value)} @{keywords(value)} @{author(value)} Type: `command` Sets the description, keywords or author of the page. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `value` | `String|Array` | no | | The value. | Returns: `String` The value, or an empty string when setting. With an argument they set the value and print nothing. `@{description}`, `@{keywords}` and `@{author}` print the value. `@{meta}` prints the description and keywords; `@{import('head')}` prints the author (or `CONF.author`). Keywords can be an array. Example: Meta values ```html @{description('Fresh apples from our farm')} @{keywords(['apples', 'fruit'])} @{author('Peter')} ``` ### @{head} / @{head(value1, [value2], ...)} Type: `command` Adds CSS, JavaScript or HTML to the head of the page, or prints it. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `value` | `String` | no | | A file name, a URL or HTML. | Returns: `String` HTML, or an empty string when adding. With arguments it adds tags and prints nothing: `.css` files become `<link>`, `.js` files `<script>`, and a value that starts with `<` is added as HTML. Each value is added once. `@{head}` (or `@{import('head')}`) prints the author meta tag and everything added. Example: Add from a view ```html @{head('chart.css', 'chart.js', '<meta name="robots" content="noindex" />')} ``` Example: Print in the layout ```html <head> @{import('meta', 'head')} </head> ``` ### @{place(name)} / @{place(name, value1, [value2], ...)} Type: `command` Adds content to a named place, or prints it. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `name` | `String` | yes | | The name of the place. | | `value` | `String` | no | | A file path or HTML. | Returns: `String` The content, or an empty string when adding. With values it appends them and prints nothing: `.js` and `.mjs` files become `<script>`, `.css` files `<link>`, anything else is added as it is. With the name only it prints the content. Values are not resolved to the static folders, so write full paths. Example: Place for scripts ```html @{place('scripts', '/js/chart.js')} <!-- layout.html --> @{place('scripts')} ``` ### @{json(value, [id], [beautify])} Type: `command` Serializes a value to JSON. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `value` | `Any` | yes | | The value to serialize. | | `id` | `String` | no | | The id of a `<script>` element. | | `beautify` | `Boolean` | no | `false` | Indents the JSON. | Returns: `String` JSON, or a `<script>` element. With `id` the JSON is wrapped in `<script type="application/json" id="...">`, so client-side code can read it. The output is not HTML-encoded. Example: Data for the browser ```html @{json(model.items, 'items')} <script> var items = JSON.parse(document.getElementById('items').innerHTML); </script> ``` ### @{options(items, [selected], [name], [value], [disabled])} Type: `command` Writes `<option>` elements for a `<select>`. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `items` | `Array|Object` | yes | | The options. | | `selected` | `Any` | no | | The value of the selected option. | | `name` | `String` | no | `name` | The property with the text. | | `value` | `String` | no | `value` | The property with the value. | | `disabled` | `String` | no | `disabled` | The property that disables an option. | Returns: `String` HTML. For an array of objects, `name` is the property of the text (default `name`) and `value` the property of the value (default: the same as `name` when you give a name, otherwise `value`). The property `disabled` disables an option. For an array of strings or numbers, each item is both text and value. For an object, keys are values and values are texts. The option equal to `selected` gets `selected="selected"`. Texts and values are encoded. Example: Select ```html <select name="country"> @{options(model.countries, model.country, 'name', 'id')} </select> ``` Example: Strings ```html <select name="size"> @{options(['S', 'M', 'L'], 'M')} </select> ``` ### @{checked(condition)} @{selected(condition)} @{disabled(condition)} @{readonly(condition)} Type: `command` Prints an HTML attribute when a condition is true. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `condition` | `Any` | yes | | When truthy, the attribute is printed. | Returns: `String` The attribute or an empty string. They print ` checked="checked"`, ` selected="selected"`, ` disabled="disabled"` or ` readonly="readonly"`, with a space in front, or nothing. Example: Attributes ```html <input type="checkbox" name="newsletter"@{checked(model.newsletter)} /> <button@{disabled(!model.items.length)}>Order</button> ``` ### @{text(name, [attributes])} @{password(name, [attributes])} @{hidden(name, [attributes])} Type: `command` Writes an `<input>` for a field of the model. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `name` | `String` | yes | | The name of the field. | | `attributes` | `Object` | no | | Extra attributes, e.g. `{ placeholder: 'Name', required: true }`. | Returns: `String` An `<input>` element. The model of the view is added automatically: the value of the input is `model[name]`, encoded. The attributes are added to the element; `required`, `disabled`, `readonly` and `autofocus` are written as boolean attributes, and `autocomplete: true` writes `autocomplete="on"` (any other truthy value writes `off`). `value` in the attributes is used when the model has no such field. Example: Form fields ```html <form method="POST"> @{text('name', { placeholder: 'Your name', required: true })} @{password('password')} @{hidden('id')} </form> ``` ### @{input(type, name, [attributes])} Type: `command` · Since: `0.0.53` Writes an `<input>` of any type for a field of the model. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `type` | `String` | yes | | The type of the input. | | `name` | `String` | yes | | The name of the field. | | `attributes` | `Object` | no | | Extra attributes. | Returns: `String` An `<input>` element. Works like `@{text()}` with the type you choose, for example `email`, `number` or `date`. Example: Email ```html @{input('email', 'email', { placeholder: 'you@example.com' })} ``` ### @{checkbox(name, [label|attributes])} @{radio(name, value, [label|attributes])} Type: `command` Writes a checkbox or a radio button for a field of the model. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `name` | `String` | yes | | The name of the field. | | `value` | `String` | yes | | Radio only: the value of this button. | | `label` | `String|Object` | no | | A label, or extra attributes (`label` is one of them). | Returns: `String` An `<input>`, wrapped in `<label>` when there is a label. A checkbox is checked when `model[name]` is `true`, `1`, `'true'` or `'on'`; its value is `1`. A radio button is checked when `model[name]` equals `value`. A string as the last argument is a label: the input is wrapped in `<label>` with the text in a `<span>`. `@{radio()}` needs this last argument, a label or an object. Example: Checkbox and radio ```html @{checkbox('newsletter', 'Send me news')} @{radio('size', 'S', 'Small')} @{radio('size', 'L', 'Large')} ``` ### @{textarea(name, [attributes])} Type: `command` Writes a `<textarea>` with the value of a field of the model. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `name` | `String` | yes | | The name of the field. | | `attributes` | `Object` | no | | Extra attributes, e.g. `{ rows: 5 }`. | Returns: `String` A `<textarea>` element. The content is `model[name]`, or `value` from the attributes. The content is not encoded, so encode values typed by users first. Example: Textarea ```html @{textarea('note', { rows: 5, placeholder: 'Note' })} ``` ### @{image(name, [width], [height], [alt], [class])} Type: `command` Writes an `<img>` for a file in `/img/`. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `name` | `String` | yes | | The image file. | | `width` | `Number|Object` | no | | The width, or an object with all attributes. | | `height` | `Number` | no | | The height. | | `alt` | `String` | no | | The alternative text. | | `class` | `String` | no | | CSS classes. | Returns: `String` An `<img>` element. Instead of the arguments you can pass an object: `{ width, height, alt, class, style }`. `alt` is encoded. Example: Image ```html @{image('logo.png', 120, 40, 'Logo')} @{image('photo.jpg', { alt: model.name, class: 'photo' })} ``` ### @{csrf} Type: `command` · Since: `0.0.37` Prints a CSRF token for the current request. Returns: `String` The token. A route with the `csrf` flag checks the token in the `X-CSRF-Token` header or in the `csrf` query parameter. It needs `secret_csrf` in the config. The token is made by `DEF.onCSRFcreate(req)` and checked by `DEF.onCSRFcheck(req)`. Example: Form and AJAX ```html <form method="POST" action="/contact/?csrf=@{csrf}"> ... </form> <meta name="csrf-token" content="@{csrf}" /> ``` ### @{href()} / @{href(key, value)} Type: `command` Prints the current query string, optionally with one key changed. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `key` | `String` | no | | The parameter to set. | | `value` | `Any` | no | | Its new value. | Returns: `String` A query string. The result starts with `?`, or is empty. Use it for paging and filters that keep the other parameters. Example: Paging ```html <a href="@{href('page', model.page + 1)}">Next</a> ``` ### @{url} / @{url(true)} Type: `command` Prints the path of the current request. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `host` | `Boolean` | no | `false` | Adds the protocol and the host. | Returns: `String` The URL. `@{url(true)}` prints the full address with the protocol and the host. Example: Canonical link ```html <link rel="canonical" href="@{url(true)}" /> ``` ### @{compile name} ... @{end} Type: `command` Passes a rendered block of the view to `DEF.onCompileView()`. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `name` | `String` | yes | | A name that tells your function what to do. | The function gets the name, the HTML of the block and the model, and returns the HTML to print. By default it returns the HTML unchanged; replace it to run another template language or a Markdown parser. The block is not minified. Example: A hook ```js DEF.onCompileView = function(name, html, model) { return name === 'markdown' ? html.markdown() : html; }; ``` Example: In a view ```html @{compile markdown} # Title Some **text**. @{end} ``` ### @{nocompress html|css|js|all} Type: `command` Turns off the minification of a view. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `type` | `String` | yes | | `html`, `css`, `js` or `all`. | By default Total.js minifies the HTML of a view and its inline CSS and JavaScript. Put this command anywhere in the view to keep one part as written: `html`, `css` (or `style`), `js` (or `script`, `javascript`) or `all`. HTML comments are removed in any case, except conditional comments. Example: Keep the HTML as written ```html @{nocompress html} <pre> Indented text </pre> ``` ### controller.view([name], [model], [headers], [partial]) Type: `method` Renders a view with its layout and sends it as the response. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `name` | `String` | no | `from the URL` | The name of the view without `.html`. | | `model` | `Object` | no | | The model of the view. | | `headers` | `Object` | no | | Extra HTTP headers. | | `partial` | `Boolean` | no | `false` | `true` returns the HTML instead of sending it. | Returns: `Controller|String` The controller, or the HTML when `partial` is `true`. Without `name` the view is named after the last part of the URL (`index` for `/`). The name is looked up in `views/<controller>/` first, then in `views/`; prefixes `~`, `=theme/`, `@`, `#plugin/` and `.` change that (see the guide). With `partial` set to `true`, the method returns the HTML instead of sending it; the layout is still applied unless you set `controller.layout('')`. When the view does not exist, the response is an error 500. Example: Render a view ```js exports.install = function() { ROUTE('GET /products/', products); }; function products() { this.view('products', { items: [] }); } ``` Example: Get the HTML ```js function preview() { this.layout(''); var html = this.view('card', model, true); this.json({ html: html }); } ``` ### controller.view_compile(body, [model], [headers], [partial], [key]) Type: `method` Compiles an HTML string as a view, renders it and sends it. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `body` | `String` | yes | | The template. | | `model` | `Object` | no | | The model. | | `headers` | `Object` | no | | Extra HTTP headers. | | `partial` | `Boolean` | no | `false` | `true` returns the HTML instead of sending it. | | `key` | `String` | no | | A cache key for the compiled template. | Returns: `Controller|String` The controller, or the HTML when `partial` is `true`. The string uses the same syntax as a view file. With `key` the compiled template is kept in memory in release mode. Example: Template from a database ```js function page() { this.layout(''); this.view_compile('<h1>@{model.title}</h1>', { title: 'Hello' }); } ``` ### controller.layout(name) Type: `method` Sets the layout for the next view. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `name` | `String` | yes | | The name of the layout, or `''`. | Returns: `Controller` The controller. The default is `default_layout` from the config (`layout`). An empty string renders without a layout. The view can change it again with `@{layout()}`. Example: Admin layout ```js function dashboard() { this.layout('admin'); this.view('dashboard'); } ``` ### controller.meta(title, [description], [keywords], [image]) Type: `method` Sets the title and meta tags that `@{meta}` prints. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `title` | `String` | yes | | The title. | | `description` | `String` | no | | The description. | | `keywords` | `String|Array` | no | | Keywords. | | `image` | `String` | no | | An image for social networks. | Returns: `Controller` The controller. `controller.title()`, `controller.description()`, `controller.keywords()` and `controller.author()` set one value each. Example: Meta tags ```js function detail() { this.meta('Apple', 'Fresh apples', ['apple', 'fruit'], 'apple.jpg'); this.view('detail'); } ``` ### controller.section(name, [value], [replace]) Type: `method` Adds content to a section of the view, or reads it. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `name` | `String` | yes | | The name of the section. | | `value` | `String` | no | | HTML to add. | | `replace` | `Boolean` | no | `false` | Replaces the content instead of appending. | Returns: `Controller|String` The controller, or the content when reading. Without `value` it returns the content. Otherwise it appends the value, or replaces the content when `replace` is `true`. Print the section with `@{section('name')}`. Example: Section from a controller ```js function stats() { this.section('scripts', '<script src="/js/chart.js"></script>'); this.view('stats'); } ``` ### controller.repository Type: `property` An object shared by the view, its partial views and the layout. In the view it is `repository` or `R`. Example: Pass a value to the layout ```js function products() { this.repository.page = 'products'; this.view('products'); } ``` ### VIEW(name, [model], [layout], [repository], [language]) Type: `method` Renders a view outside a request and returns the HTML. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `name` | `String` | yes | | The name of the view. | | `model` | `Object` | no | | The model. | | `layout` | `String` | no | `''` | A layout. | | `repository` | `Object` | no | | The repository. | | `language` | `String` | no | | The language for `@(...)`. | Returns: `String` The HTML. There is no layout unless you name one. Use it for emails, files or responses built by hand. A name like `=theme/view` reads the view from a theme. Example: Render to a string ```js var html = VIEW('emails/order', order, null, null, 'en'); ``` ### VIEWCOMPILE(body, [model], [layout], [repository], [language]) Type: `method` Compiles an HTML string as a view, outside a request, and returns the HTML. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `body` | `String` | yes | | The template. | | `model` | `Object` | no | | The model. | | `layout` | `String` | no | `''` | A layout. | | `repository` | `Object` | no | | The repository. | | `language` | `String` | no | | The language for `@(...)`. | Returns: `String` The HTML. It is `VIEW()` for a template in a string, for example from a database. The string uses the same syntax as a view file. There is no layout unless you name one, and `layout` and `repository` can switch places. The template is compiled on every call. Example: Template from a string ```js var html = VIEWCOMPILE('<h1>@{model.title}</h1>', { title: 'Hello' }); ``` --- title: Configuration project: Total.js V4 version: 0.0.99 section: reference language: en license: MIT url: https://totaljs.es/docs/total-js-v4/0-0-99/reference/configuration/ updated: 2026-11-16T15:41:00.817Z --- # Configuration > The CONF object, every built-in config key and the functions for loading configuration. The configuration lives in the files `config`, `config-debug` and `config-release` in the root of the application, and in the global object `CONF`. The guide [Configuration](../../guides/configuration/) explains the syntax, the types and environment variables; this page lists the functions and the built-in keys with their defaults. ## API ### CONF Type: `property` The global object with the whole configuration of the application. Returns: `Object` Total.js fills `CONF` with default values, then with `options.config` from the start script, and then with the values from `config` and `config-debug` or `config-release`. It is a plain object: read and assign keys as properties. Keys with a dot, like `security.txt`, need the bracket notation. Your own keys are stored the same way as the built-in ones. Values assigned in code are not saved to the files. Example: Read values ```js exports.install = function() { ROUTE('GET /api/info/', info); }; function info() { this.json({ name: CONF.name, version: CONF.version }); } ``` Example: In a view ```html <footer>@{CONF.name} v@{CONF.version}</footer> ``` ### LOADCONFIG(value) Type: `method` Merges new values into `CONF` at runtime. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `value` | `Object|String|Array` | yes | | The new values. | `value` can be: - an object, copied key by key into `CONF`; - a string in the config syntax, parsed with `String.parseConfig()`; - an array of items `{ id, type, value }` (`key` or `name` instead of `id`, `body` instead of `value`). For arrays, `type` converts the value: `number`, `boolean` (`bool`), `json` (`object`), `date`, `string`, `[string]`, `[number]`, `[boolean]` (`[bool]`). A string value that starts with `hex ` is decoded from hex. A `root` key is copied to `default_root`, and `default_root` gets a leading and a trailing slash. Changing `mail_smtp` or `mail_smtp_options` clears the cached SMTP settings, and the TMS endpoint is refreshed. Example: Settings from a database ```js // Items stored e.g. in a database: [{ id, type, value }] function applysettings(items) { LOADCONFIG(items); } ``` Example: An object or a string ```js LOADCONFIG({ allow_tms: true, secret_tms: 'token' }); LOADCONFIG('name : My Shop\nlimit (number) : 50'); ``` Example: Typed items ```js LOADCONFIG([ { id: 'limit', type: 'number', value: '50' }, { id: 'languages', type: '[string]', value: 'en, sk' }, { id: 'newsletter', type: 'boolean', value: 'on' } ]); ``` ### DEBUG Type: `property` `true` when the application runs in debug mode. Returns: `Boolean` In debug mode Total.js reads `config-debug` and `.env-debug`; otherwise `config-release` and `.env-release`. Example: Mode-specific code ```js if (DEBUG) console.log('Running with config-debug'); ``` ### RELEASE Type: `property` `true` when the application runs in release mode. Returns: `Boolean` The opposite of `DEBUG`. In release mode Total.js reads `config-release` and `.env-release`, and `default_response_maxage` is used for the `Cache-Control` header of static files. Example: Release only ```js if (RELEASE) CONF.allow_tms = true; ``` ### String.parseConfig([def], [onerr]) Type: `method` Parses text in the config syntax into an object. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `def` | `Object` | no | | Default values, copied into the result first. | | `onerr` | `Function` | no | | `function(err, line)` called when an `object` value cannot be evaluated. Without it, an error is thrown. | Returns: `Object` The parsed values. Each `key : value` line becomes a property. The value starts two characters after the `:`, so keep a space after it. Lines starting with `#` or `//` are skipped. Types in brackets work as in the config file: `string`, `number` (`float`, `double`, `currency`), `boolean` (`bool`), `array`, `json`, `object` (`eval`), `env` (`environment`), `date` (`time`, `datetime`), `random`, and `config`, which copies the value of another `CONF` key. Without a type the value stays a string. Example: Parse settings ```js var obj = 'name : Shop\nlimit (number) : 10\nhost (config) : url'.parseConfig(); // obj.limit === 10, obj.host === CONF.url ``` ### String.parseENV() Type: `method` Parses text in the `.env` syntax into an object. Returns: `Object` The parsed variables, all strings. Each `KEY=value` line becomes a property. Quotes around the value are removed, other values are trimmed, and `\n` becomes a new line. Lines starting with `#` or `//` are skipped. Total.js uses it for the `.env` files. Example: Parse variables ```js var env = 'PORT=8000\nNAME="My app"'.parseENV(); // { PORT: '8000', NAME: 'My app' } ``` ### KEY=value Type: `config` Files with environment variables, loaded before the config files. Total.js reads `.env` from the root, then `.env-debug` or `.env-release`. Every variable goes into `process.env`, but a variable that already exists there is not replaced. Use the `(env)` type in the config to read a variable into a key. Example: .env ```text DATABASE_URL=postgresql://user:pass@localhost:5432/shop PORT=8000 ``` Example: config ```text database (env) : DATABASE_URL default_port : auto ``` ### PATH.configs([filename]) Type: `method` Returns the path to a file in the `configs` directory. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `filename` | `String` | no | | A file name inside the directory. | Returns: `String` The absolute path. The directory is set by `directory_configs` (default `/configs/`). Total.js does not load files from it; it is a place for your own configuration files. Example: Read a JSON file ```js var menu = require('fs').readFileSync(PATH.configs('menu.json')).toString('utf8').parseJSON(); ``` ### name : Total.js Type: `config` The name of the application. Returns: `String` Used in the process title, the console header, the sender name of emails, page titles and the `x-app` header of Total API calls. Default: `Total.js`. Example: In the config file ```text name : My Shop ``` ### version : 1.0.0 Type: `config` The version of the application. Returns: `String` Always kept as a string. Without `etag_version`, the version without dots and spaces is used as the ETag suffix of static files; change `etag_version` to make browsers download static files again. `author` holds the author, shown in the console header and used as the default author meta tag. Default: `1.0.0`. Example: In the config file ```text version : 2.1.0 ``` ### url : <value> Type: `config` The public URL of the application. Returns: `String` Used by the Total API logger as the application name and as the base URL for JSON schema references. Not set by default. Example: In the config file ```text url : https://www.example.com ``` ### secret : <value> Type: `config` The key used by `ENCRYPT()` and `DECRYPT()`. Returns: `String` The default value is a hash of the framework path, the machine and the Node.js versions, so it changes when you move the application. Set your own value when encrypted data must survive a move. Always kept as a string. Example: In the config file ```text secret : my-long-random-secret ``` ### secret_uid : <value> Type: `config` A value that makes the generated `UID()` values unique for the application. Returns: `String` Without a value Total.js computes it from `name`. Example: In the config file ```text secret_uid : shop ``` ### secret_encryption : null Type: `config` Enables encryption of request and response bodies. Returns: `String` When set, the bodies of routes with the `encrypt` flag (and of WebSockets with encryption) are encrypted with this key. With `allow_static_encryption`, static files are encrypted too. Default: `null`. Example: In the config file ```text secret_encryption : my-encryption-key ``` ### secret_csrf : null Type: `config` Enables CSRF tokens. Returns: `String` The key used to create and check CSRF tokens. Routes with the `csrf` flag are checked only when this key is set. `default_csrf_maxage` (default `30 minutes`) sets how long a token is valid. Default: `null`. Example: In the config file ```text secret_csrf : my-csrf-key default_csrf_maxage : 30 minutes ``` ### default_root : <value> Type: `config` The URL prefix when the application runs in a subdirectory. Returns: `String` Total.js adds a leading and a trailing slash. The prefix is used for URLs of static files and in redirects, and removed from incoming URLs. `root` is an alias: when set, it is copied to `default_root`. Load it from an environment variable with `default_root (env) : APP_ROOT`. Example: In the config file ```text default_root : /shop/ ``` ### default_port : <value> Type: `config` The HTTP port. Returns: `Number|String` Used when the start script does not set a port. `auto` takes `process.env.PORT`. Without any value the port is `8000`. `default_ip` sets the IP address (without a value, or with `auto`, the server listens on `0.0.0.0`) and `default_unixsocket` a Unix socket path. Both are used only when the start script does not set them. Example: In the config file ```text default_port : auto default_ip : 127.0.0.1 ``` ### default_timezone : utc Type: `config` The time zone of the process. Returns: `String` Assigned to `process.env.TZ` when the config is loaded. Default: `utc`. Example: In the config file ```text default_timezone : Europe/Berlin ``` ### default_theme : <value> Type: `config` The default theme. Returns: `String` The name of a folder in `themes/` used by views and static files when no theme is set. Example: In the config file ```text default_theme : default ``` ### default_request_maxlength : 10 Type: `config` The maximum size of a request body, in kilobytes. Returns: `Number` Applies to routes without their own length. Parsed as an integer. Default: `10`. Example: In the config file ```text default_request_maxlength : 1024 ``` ### default_request_timeout : 3000 Type: `config` The request timeout, in milliseconds. Returns: `Number` Applies to routes without their own timeout. Parsed as an integer. Default: `3000`. Example: In the config file ```text default_request_timeout : 10000 ``` ### default_request_maxkeys : 33 Type: `config` The maximum number of keys parsed from a query string or a URL-encoded body. Returns: `Number` Extra keys are ignored. `default_request_maxkey` (default `25`) is the maximum length of one key. Default: `33`. Example: In the config file ```text default_request_maxkeys : 50 ``` ### default_restbuilder_timeout : 10000 Type: `config` The default timeout of `RESTBuilder` and `REQUEST()`, in milliseconds. Returns: `Number` Used when the request has no timeout of its own. `default_proxy` sets a proxy server (for example `http://proxy.example.com:3128`) for outgoing requests that do not set their own. Default: `10000`. Example: In the config file ```text default_restbuilder_timeout : 30000 ``` ### default_websocket_maxlength : 2 Type: `config` The maximum size of a WebSocket message, in kilobytes. Returns: `Number` Applies to WebSocket routes without their own length. Default: `2`. Example: In the config file ```text default_websocket_maxlength : 64 ``` ### default_websocket_maxlatency : 2000 Type: `config` The maximum latency of a WebSocket client, in milliseconds. Returns: `Number` Total.js pings clients every `default_interval_websocket_ping` milliseconds and closes clients with a higher latency. `0` disables the pinging. Default: `2000`. Example: In the config file ```text default_websocket_maxlatency : 5000 ``` ### default_cors : null Type: `config` Allowed origins for cross-origin requests. Returns: `Array` Hostnames separated by commas or spaces, without the protocol (a leading `//` is removed). Requests from other origins get `null` as the allowed origin. The value is stored as a lowercase array. `default_cors_maxage` (default `120`) sets how long browsers can cache a preflight response, in seconds. Default: `null`. Example: In the config file ```text default_cors : example.com, app.example.com ``` ### default_response_maxage : 11111111 Type: `config` The `max-age` of the `Cache-Control` header for static files, in seconds. Returns: `String` Used only in release mode. Default: `11111111`. Example: In the config file ```text default_response_maxage : 86400 ``` ### default_cookies_samesite : Lax Type: `config` The default `SameSite` attribute of cookies. Returns: `String` Used when a cookie does not set `samesite`. `default_cookies_secure` (default `false`) adds the `Secure` attribute to cookies that do not set `secure`. Default: `Lax`. Example: In the config file ```text default_cookies_samesite : Strict default_cookies_secure : true ``` ### default_errorbuilder_errors : false Type: `config` Sends all HTTP errors as `ErrorBuilder` JSON. Returns: `Boolean` `default_errorbuilder_forxhr` (default `true`) does the same only for XHR requests. `default_errorbuilder_status` (default `400`) is the HTTP status code of `ErrorBuilder` responses. Default: `false`. Example: In the config file ```text default_errorbuilder_errors (bool) : true ``` ### default_uid : <value> Type: `config` Changes the generator of `UID()`. Returns: `String` `r` (or `uidr`) and `f` (or `uidf`) switch to other UID versions. Without a value the default generator is used. Example: In the config file ```text default_uid : f ``` ### default_crypto : <value> Type: `config` A Node.js cipher for `ENCRYPT()` and `DECRYPT()`. Returns: `String` When set, the functions use `crypto.createCipheriv()` with this algorithm and `default_crypto_iv` (a hex string in the file; by default derived from the machine). Without a value Total.js uses its own encryption with `secret`. Example: In the config file ```text default_crypto : aes-256-cbc default_crypto_iv : 000102030405060708090a0b0c0d0e0f ``` ### default_image_converter : gm Type: `config` The command-line tool for `Image`. Returns: `String` `gm` is GraphicsMagick and `im` is ImageMagick. `default_image_consumption` (default `0`, disabled) limits the memory and map resources of the tool; the value is a percentage of 1500 MB of memory and 3000 MB of map. Default: `gm`. Example: In the config file ```text default_image_converter : im default_image_consumption : 50 ``` ### default_tms_url : /$tms/ Type: `config` The WebSocket endpoint of the Total.js Message Service. Returns: `String` Used when `allow_tms` is `true`. `default_tms_maxlength` (default `1024`, in kB) sets the maximum message size. `secret_tms` is the token that clients must send; without it the endpoint accepts every client. Default: `/$tms/`. Example: In the config file ```text allow_tms : true default_tms_url : /$tms/ secret_tms : my-token ``` ### default_interval_clear_cache : 10 Type: `config` Intervals of the internal service. - `default_interval_clear_cache` (default `10`): minutes between cleaning of expired cache items and unused sessions. - `default_interval_clear_resources` (default `20`): minutes between clearing of the loaded resources. - `default_interval_clear_dnscache` (default `30`): minutes between cleaning of the DNS cache. - `default_interval_websocket_ping` (default `20000`): milliseconds between WebSocket pings; values under `1000` mean `20000`. All are parsed as integers. Example: In the config file ```text default_interval_clear_cache : 5 default_interval_websocket_ping : 30000 ``` ### directory_public : /public/ Type: `config` Paths of the application directories. Each directory has a key, relative to the root: `directory_controllers`, `directory_definitions`, `directory_views`, `directory_public`, `directory_schemas`, `directory_models`, `directory_actions`, `directory_modules`, `directory_plugins`, `directory_resources`, `directory_databases`, `directory_logs`, `directory_temp`, `directory_themes`, `directory_components`, `directory_middleware`, `directory_packages`, `directory_flowstreams`, `directory_jsonschemas`, `directory_operations`, `directory_tasks`, `directory_extensions`, `directory_builds`, `directory_workers`, `directory_private`, `directory_configs`, `directory_tests` and others. The default value is the name with slashes, for example `/public/`. The `PATH.*()` methods use these keys. Without `directory_temp`, a folder in the system temp directory is used. The directories are read when the application starts. Example: In the config file ```text directory_public : /www/ directory_databases : /data/ ``` ### static_url_script : /js/ Type: `config` URL prefixes of static files. Used by the view helpers for static files: `static_url` (default empty, a prefix for all of them, for example a CDN), `static_url_script` (`/js/`), `static_url_style` (`/css/`), `static_url_image` (`/img/`), `static_url_video` (`/videos/`), `static_url_font` (`/fonts/`), `static_url_download` (`/download/`) and `static_url_components` (`/components.`). Example: In the config file ```text static_url : https://cdn.example.com static_url_script : /scripts/ ``` ### static_accepts : jpg, png, css, js Type: `config` File extensions served as static files. The default list contains common extensions (images, scripts, styles, fonts, documents, media). In the file, `static_accepts` replaces the whole list; `static_accepts_custom` adds extensions to it. Example: Add extensions ```text static_accepts_custom : glb, gltf ``` ### allow_websocket : true Type: `config` Enables WebSocket routes. Returns: `Boolean` `allow_websocket_compression` (default `true`) enables the `permessage-deflate` extension. Default: `true`. Example: In the config file ```text allow_websocket : false ``` ### allow_static_files : true Type: `config` Serves static files from `public/`. Returns: `Boolean` Set to `false` when another server delivers static files. Default: `true`. Example: In the config file ```text allow_static_files : false ``` ### allow_gzip : true Type: `config` Compresses responses with gzip. Returns: `Boolean` Applies to compressible content types when the client accepts gzip. Default: `true`. Example: In the config file ```text allow_gzip : false ``` ### allow_compile : true Type: `config` Minifies static files and HTML. Returns: `Boolean` `allow_compile_script`, `allow_compile_style` and `allow_compile_html` (all `true`) switch the minification of JavaScript, CSS and HTML separately. Default: `true`. Example: In the config file ```text allow_compile_html : false ``` ### allow_tms : false Type: `config` Enables the Total.js Message Service endpoint. Returns: `Boolean` The endpoint is `default_tms_url` and is protected by `secret_tms`. Default: `false`. Example: In the config file ```text allow_tms : true ``` ### allow_reqlimit : 0 Type: `config` The maximum number of concurrent requests from one IP address. Returns: `Number` Requests over the limit get `503 Service Unavailable`. `0` disables the limit. Default: `0`. Example: In the config file ```text allow_reqlimit (number) : 20 ``` ### allow_ssc_validation : true Type: `config` Validates TLS certificates of outgoing requests. Returns: `Boolean` `false` sets `NODE_TLS_REJECT_UNAUTHORIZED` to `0` and accepts self-signed certificates. Default: `true`. Example: In the config file ```text allow_ssc_validation : false ``` ### allow_cache_snapshot : false Type: `config` Saves the cache to a file and loads it after a restart. Returns: `Boolean` `allow_cache_cluster` (default `false`) synchronizes the cache between cluster instances. Default: `false`. Example: In the config file ```text allow_cache_snapshot : true ``` ### allow_totalapi : true Type: `config` Enables calls to Total API. Returns: `Boolean` The token is read from `totalapi` or `secret_totalapi`. `allow_totalapilogger` (default `false`) sends logs to Total API. `default_tapi` (default `eu`) selects the server. Default: `true`. Example: In the config file ```text totalapi : my-token allow_totalapi : true ``` ### mail_smtp : smtp.example.com Type: `config` The SMTP server used by `MAIL()` and `Mail.send()`. Related keys: - `mail_smtp_options`: the options of the SMTP connection, a JavaScript object written as text, for example `{ port: 465, secure: true, user: '...', password: '...' }`; - `mail_from`: the sender address, the sender name is `name`; - `mail_reply`: the reply-to address; - `mail_cc` and `mail_bcc`: copies of every message; - `mail_smtp_keepalive` (default `10 minutes`): how long the connection stays open; - `mail_api`: sends emails through Total API (`true` uses the `totalapi` token). `mail_address_from`, `mail_address_reply` and `mail_address_copy` are older names of `mail_from`, `mail_reply` and `mail_bcc`. Example: In the config file ```text mail_smtp : smtp.example.com mail_smtp_options : { port: 465, secure: true, user: 'info@example.com', password: 'secret' } mail_from : info@example.com mail_reply : support@example.com ``` ### logger : <value> Type: `config` Writes the console output to `logs/debug.log`. Returns: `Boolean` `console.log`, `console.warn`, `console.error` and the timers are redirected to the file. Example: In the config file ```text logger : true ``` ### nosourcemap : false Type: `config` Disables source maps. Returns: `Boolean` Source maps are generated only in debug mode; in release mode this key is always `true`. Default: `false`. Example: In the config file ```text nosourcemap : true ``` ### node_modules : node_modules Type: `config` The directory of NPM modules. Returns: `String` Used by `NPMINSTALL()` and `F.require()`. A value starting with `~` is an absolute path. Default: `node_modules`. Example: In the config file ```text node_modules : ~/opt/shared/node_modules ``` ### security.txt : Contact: mailto:support@totaljs.com Type: `config` The content of `/security.txt`. Returns: `String` In the file, lines are separated by commas. An empty value disables the response. Read it as `CONF['security.txt']`. Default: `Contact: mailto:support@totaljs.com`. Example: In the config file ```text security.txt : Contact: mailto:security@example.com, Expires: 2026-12-31T00:00:00.000Z ``` --- title: Authorization project: Total.js V4 version: 0.0.99 section: reference language: en license: MIT url: https://totaljs.es/docs/total-js-v4/0-0-99/reference/authorization/ updated: 2026-11-16T15:41:00.817Z --- # Authorization > AUTH(), route flags, roles, cookies and the SESSION() store. Total.js signs in requests with the `AUTH()` delegate, limits routes with the `+` and `-` flags, and keeps sessions with the built-in cookie session or the `SESSION()` store. The guide [Authorization](../../guides/authorization/) explains how to use them with examples; this page is the exact reference. Encryption has its own page: [Encryption](../encryption/). ## API ### AUTH(fn) Type: `method` Registers the delegate that signs in every request. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `fn` | `Function($)` | yes | | The delegate. `$` is the authorization object. | Returns: `undefined` The delegate runs for every HTTP request that reaches routing and for every WebSocket connection. It receives an authorization object `$` (see `$.success()`, `$.invalid()` and the properties of `$`). It must call exactly one of `$.success(user)`, `$.invalid()` or `$.cancel()`. Registering a new delegate replaces the previous one. Passing an object instead of a function starts the built-in cookie session, see `AUTH(options)`. Example: Sign in with a token header ```js AUTH(function($) { var token = $.headers['x-token']; if (token && token === CONF.apitoken) $.success({ id: 'api', name: 'API' }); else $.invalid(); }); ``` ### AUTH(options) Type: `method` Starts the built-in cookie session mechanism. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `options` | `Object` | yes | | Options and delegates of the session, see the table. | Returns: `undefined` Methods are added to `options`. With an object, `AUTH()` registers its own delegate. It reads the session token from the cookie `options.cookie` (or from the header `options.header`), decrypts it with `options.secret`, and keeps the user data in memory for `options.expire`. When the data is not cached, it calls `options.onread()`. Requests waiting for the same session share one `onread()` call. `AUTH()` does not return anything, but it adds methods to the object you pass: `logout()`, `update()`, `refresh()`, `sign()`, `authcookie()` and `auth()` (the delegate itself). Keep a reference to the object. | Option | Type | Description | | --- | --- | --- | | `secret` | String | Key for encrypting the token. Always set it. | | `cookie` | String | Name of the cookie with the token. | | `header` | String | Name of a request header with the token, used when the cookie is missing. Write it in lower case. | | `expire` | String | How long user data stays in memory. Default `'5 minutes'`. | | `strict` | Boolean | The cached session works only with the same user agent. Default `true`. | | `ddos` | Number | Failed attempts per IP address before every request of that IP is invalid. The counters reset with each cleaning. | | `cleaner` | Number | Cleaning interval in minutes. Default `5`. | | `options` | Object | Cookie options used when the cookie is written or removed. | | `onread` | Function(meta, next, $) | Loads the user data, see `options.onread`. | | `onsession` | Function(session, $, init) | Called when a session is found. Return `true` to stop the processing; then answer `$` yourself. `init` is `true` when the data was just loaded. | | `onauthorize` | Function($) | Called first for every request. Return `true` to skip the built-in processing; then answer `$` yourself. | | `onlogout` | Function(session) | Called by `logout()`. | | `onfree` | Function(meta) | Called after cleaning with `{ sessions: Array, users: Array }`: the removed session IDs and the user IDs without any live session. | | `onddos` | Function($) | Called when a blocked IP address makes a request. | | `locale` | Function(data, req) | Returns the language of the request. `data` is `null` for anonymous visitors. | An invalid or unknown token removes the cookie. Example: Built-in session ```js var opt = {}; opt.secret = 'a-long-random-key'; opt.cookie = 'session'; opt.expire = '10 minutes'; opt.onread = function(meta, next) { NOSQL('users').one().where('id', meta.userid).callback(next); }; AUTH(opt); MAIN.auth = opt; ``` Example: Language of the user ```js opt.locale = function(data, req) { return data ? data.language : ''; }; ``` ### options.onread = function(meta, next, $) Type: `delegate` Loads the user data for a session token in the built-in session. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `meta` | `Object` | yes | | `{ sessionid, userid, ip, ua }`. | | `next` | `Function(err, data)` | yes | | Callback with the user data. | | `$` | `Object` | yes | | The authorization object. | Called when a valid token has no cached data. `meta` contains `sessionid`, `userid`, `ip` and `ua`. Call `next(err, data)`: with data, the session is cached for `options.expire` and the request is signed in; without data, the cookie is removed and the request is anonymous. Check in your database that the session still exists, so a signed-out session cannot be used again. Example: Read the user ```js opt.onread = function(meta, next) { NOSQL('sessions').one().where('id', meta.sessionid).callback(function(err, session) { if (session) NOSQL('users').one().where('id', meta.userid).callback(next); else next(); }); }; ``` ### options.authcookie($, sessionid, userid, expiration, [cookieoptions]) Type: `method` Writes the session cookie of the built-in session. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `$` | `Controller|Object` | yes | | Object with a `cookie()` method. | | `sessionid` | `String` | yes | | Your session ID. | | `userid` | `String` | yes | | The user ID. | | `expiration` | `String|Date` | yes | | Expiration of the cookie, for example `'1 month'`. | | `cookieoptions` | `Object` | no | `options.options` | Cookie options. | Signs `sessionid` and `userid` with `options.sign()` and writes them to the cookie `options.cookie`. Call it after you check the credentials and store the session. `options.sign(sessionid, userid)` returns the same token without writing a cookie, for clients that send it in the header `options.header`. `$` is anything with a `cookie()` method: a controller, a schema `$` or the authorization `$`. Example: Sign in ```js var sessionid = UID(); NOSQL('sessions').insert({ id: sessionid, userid: user.id }); MAIN.auth.authcookie(self, sessionid, user.id, '1 month'); self.redirect('/'); ``` ### options.logout($) Type: `method` Signs out the current session of the built-in session. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `$` | `Controller|String` | yes | | The controller or the session ID. | Returns: `Boolean` `true` when a session was removed. `$` is the controller (or another object with `sessionid`), or a session ID string. Removes the session from memory, calls `options.onlogout(session)` and removes the cookie when `$` has a `cookie()` method. Returns `true` when the session was found. Delete the session from your database in `onlogout`, otherwise `onread` can load it again. Example: Sign out ```js function logout() { var self = this; MAIN.auth.logout(self); self.redirect('/'); } ``` ### options.update(userid, fn) Type: `method` · Since: `0.0.56` Changes the cached data of all sessions of a user in the built-in session. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `userid` | `String` | yes | | The user ID. | | `fn` | `Function(data, session)` | yes | | Called for each session. | Returns: `Number` Count of sessions. Calls `fn(data, session)` for every cached session of `userid`, so you can change the user object in place. Example: Rename the user ```js MAIN.auth.update(user.id, function(data) { data.name = model.name; }); ``` ### options.refresh(userid, [exceptsessionid]) Type: `method` · Since: `0.0.56` Drops the cached data of a user in the built-in session. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `userid` | `String` | yes | | The user ID. | | `exceptsessionid` | `String` | no | | A session ID to keep. | Returns: `Number` Count of removed sessions. Removes the user's sessions from memory, so the next request calls `onread` again. The cookies stay valid. Pass `exceptsessionid` to keep one session, for example the current one. Example: Reload after a change ```js MAIN.auth.refresh(user.id, self.sessionid); ``` ### $ Type: `class` The `$` object the AUTH() delegate receives. Properties (read-only): `$.req`, `$.res`, `$.ip`, `$.ua`, `$.url` (lower-case path), `$.uri`, `$.path`, `$.split`, `$.language`, `$.params`, `$.query`, `$.body`, `$.files`, `$.headers`, `$.mobile` and `$.websocket` (`true` for a WebSocket connection). Methods: `$.success(user)`, `$.invalid()`, `$.cancel()`, `$.cookie()`, `$.done()`, `$.audit(message, [type])` and `$.next(is, user)` (alias `$.callback()`). Only the first answer counts; later calls are ignored. In a WebSocket connection `$.res` is the WebSocket client, so you cannot write cookies. Example: Different rules for WebSockets ```js AUTH(function($) { var token = $.websocket ? $.query.token : $.cookie('token'); var id = DECRYPTREQ($.req, token, 'auth'); if (id) $.success({ id: id }); else $.invalid(); }); ``` ### $.success(user) Type: `method` Signs the request in with a user object. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `user` | `Object` | yes | | The signed-in user. | The user object becomes `controller.user`, `$.user` in schemas and `client.user` in WebSockets. Routes with `+` match; routes with `-` do not. `$.done([user])` returns a callback `function(is, user)` for asynchronous code: a truthy `is` (or `null` with a user) signs the request in, an `Error` marks it as anonymous. Example: Sign in ```js $.success({ id: user.id, name: user.name, roles: user.roles }); ``` ### $.invalid([user]) Type: `method` Marks the request as not signed in. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `user` | `Object` | no | | Optional data for an anonymous visitor. | Routes with `-` and routes without a flag match. A user object passed here is still set as `controller.user`, but the request counts as anonymous. Example: No token ```js if (!token) { $.invalid(); return; } ``` ### $.cancel() Type: `method` · Since: `0.0.89` Stops the authorization and the request processing. Returns: `AuthOptions` The same object. Use it when you answer the request yourself in the delegate, for example with a redirect through `$.res`. After `$.cancel()` the framework does not route the request. Example: Redirect old domains ```js AUTH(function($) { if ($.headers.host === 'old.example.com') { $.cancel(); $.res.redirect('https://www.example.com' + $.url); return; } $.invalid(); }); ``` ### $.cookie(name, [value], [expire], [options]) Type: `method` Reads or writes a cookie inside the AUTH() delegate. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `name` | `String` | yes | | Cookie name. | | `value` | `String|null` | no | | New value; `null` removes the cookie. | | `expire` | `String|Date` | no | | Expiration, for example `'1 month'`. | | `options` | `Object` | no | | Cookie options, see `controller.cookie()`. | Returns: `String|AuthOptions` The value when reading, otherwise `$`. With only `name`, returns the cookie value (an empty string when it is missing). With `value`, writes the cookie. With `value` set to `null`, removes it. The same method exists on schema and operation `$` objects. Example: Remove an invalid cookie ```js var token = $.cookie('token'); if (token && !DECRYPTREQ($.req, token, 'auth')) { $.cookie('token', null); $.invalid(); return; } ``` ### ROUTE('+GET /url/') / ROUTE('-GET /url/') Type: `config` Limits a route to signed-in or anonymous visitors. A URL that starts with `+` (or `🔒`) matches only requests signed in with `$.success()`. A URL that starts with `-` matches only requests marked with `$.invalid()`. A route without a flag matches both. In the flags array, `'authorize'`, `'authorized'` and `'logged'` mean `+`; `'unauthorize'`, `'unauthorized'` and `'unlogged'` mean `-`. The same URL can have a `+` and a `-` route. When the only route is for the other state, the response is `401`; with no route at all, `404`. WebSocket routes use the same prefixes; a WebSocket that does not match is closed with code `4001`. The flags are checked only when `AUTH()` is registered. Example: One URL, two routes ```js exports.install = function() { ROUTE('+GET /', 'dashboard'); ROUTE('-GET /', 'login'); ROUTE('+SOCKET /live/', live); }; ``` Example: Flags in an array ```js ROUTE('GET /account/', account, ['authorize']); ``` ### ROUTE('GET /url/', action, ['@role']) Type: `config` Marks a route with roles. A flag that starts with `@` is a role. It is lower-cased and kept in `controller.route.flags`, and the route needs a signed-in user (as with `+`) unless you add `-`. Total.js does not compare roles with the user: check them in the action, for example with `UNAUTHORIZED()`. Example: Check the role of the route ```js ROUTE('GET /admin/', admin, ['@admin']); function admin() { var self = this; if (UNAUTHORIZED(self, 'admin')) return; self.view('admin'); } ``` ### UNAUTHORIZED($, role, [role2], ...) Type: `method` Checks the roles of the signed-in user and answers 401 when none matches. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `$` | `Controller|Object` | yes | | A controller or a schema/operation `$`. | | `role` | `String` | yes | | One or more roles as separate arguments. | Returns: `Boolean` `true` when the request was refused. Compares the roles with `$.user.permissions` or `$.user.roles` (an array, or an object whose keys are roles). Returns `false` when the user has one of the roles or when `user.sa` or `user.su` is truthy. Otherwise calls `$.invalid(401)` and returns `true`, also when there is no user. Example: In a schema ```js schema.setRemove(function($) { if (UNAUTHORIZED($, 'admin', 'editor')) return; NOSQL('articles').remove().where('id', $.id).callback($.done()); }); ``` ### BLOCKED($, [limit], [expiration]) Type: `method` Counts attempts from an IP address and tells when to block it. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `$` | `Controller|Object` | yes | | Object with `ip`. | | `limit` | `Number` | no | `5` | Allowed attempts. | | `expiration` | `String` | no | `'15 minutes'` | How long the counter lives. | Returns: `Boolean` `true` when the IP address is blocked. Use it to slow down password guessing. Each call adds one attempt for `$.ip`. Returns `true` when the count is above `limit`. With `limit` set to `-1` or `null`, clears the counter of that IP address, for example after a successful sign-in. Example: Login form ```js function login() { var self = this; if (BLOCKED(self, 10)) { self.invalid('error-blocked'); return; } // ... on success: BLOCKED(self, -1); } ``` ### controller.user Type: `property` The user object of a signed-in request. Returns: `Object` Set by `$.success(user)`. It is `undefined` for anonymous requests. You can assign it. In schemas and operations read `$.user`; in WebSockets `client.user`. Example: Use the user ```js function account() { var self = this; self.view('account', { name: self.user.name }); } ``` ### $.user Type: `property` The signed-in user inside schemas and operations. Returns: `Object` Returns `controller.user` of the request, or `null` when the operation runs without a controller. Example: Owner of a record ```js schema.setInsert(function($, model) { model.userid = $.user.id; NOSQL('notes').insert(model).callback($.done()); }); ``` ### controller.session / controller.sessionid Type: `property` The session object and the session ID of the request. Returns: `Object / String` Both read and write `req.session` and `req.sessionid`. The built-in `AUTH(options)` sets them to the cached session (`{ sessionid, userid, data, ua, expire }`) and its ID. `SESSION().getcookie()`, `gettoken()`, `setcookie()` and `settoken()` set `sessionid`. The same properties exist on schema `$` objects and WebSocket clients. Example: Sign out of a SESSION() store ```js session.remove(self.sessionid); ``` ### controller.cookie(name, [value], [expires], [options]) Type: `method` Reads or writes a cookie. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `name` | `String` | yes | | Cookie name. | | `value` | `String` | no | | New value. | | `expires` | `String|Date|Object` | no | | Expiration, or the options. | | `options` | `Object` | no | | Cookie options. | Returns: `String|Controller` The value when reading, otherwise the controller. With only `name`, returns the decoded value of the cookie, or an empty string. With `value`, adds a `Set-Cookie` header and returns the controller. To remove a cookie, write an empty value with a past expiration such as `'-1 day'`. `expires` is a `Date` or a string like `'1 month'`. Instead of `expires` you can pass the options object, which then may contain `expires`. | Option | Description | | --- | --- | | `domain` | Cookie domain. | | `path` | Cookie path. Default `/`. | | `secure` | `true` adds `Secure`. Default `CONF.default_cookies_secure`. | | `httponly` | `true` adds `HttpOnly`. | | `samesite` or `security` | `'Lax'`, `'Strict'` or `'None'` (or `1` for Lax, `2` for Strict). Default `CONF.default_cookies_samesite`. | A cookie is not written once the response has been sent. Example: Write and read ```js self.cookie('theme', 'dark', '1 year', { httponly: true }); var theme = self.cookie('theme'); ``` Example: Remove ```js self.cookie('token', '', '-1 day'); ``` ### res.cookie(name, value, [expires], [options]) Type: `method` Writes a cookie to the HTTP response. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `name` | `String` | yes | | Cookie name. | | `value` | `String` | yes | | Value. | | `expires` | `String|Date|Object` | no | | Expiration, or the options. | | `options` | `Object` | no | | Cookie options. | Returns: `Response` The low-level method behind `controller.cookie()`, with the same options. Use it where you only have the response, for example `$.res` in the AUTH() delegate. `req.cookie(name)` reads a cookie from the request. Example: From the delegate ```js $.res.cookie('visited', '1', '1 day'); var old = $.req.cookie('visited'); ``` ### default_cookies_samesite : Lax Type: `config` Default SameSite attribute of cookies. Returns: `String` Used when a cookie has no `samesite`/`security` option. Default `'Lax'`. Example: config ```js // /config default_cookies_samesite : Strict ``` ### default_cookies_secure : false Type: `config` Adds the Secure attribute to every cookie. Returns: `Boolean` Used when a cookie has no `secure` option. Default `false`. Turn it on when the app runs only on HTTPS. Example: config ```js // /config default_cookies_secure : true ``` ### SESSION([name]) Type: `method` Returns a named session store. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `name` | `String` | no | `'default'` | Name of the store. | Returns: `Session` The store. The first call creates the store and loads its saved sessions; later calls return the same instance. The default name is `default`, saved in `databases/sessions.txt`; other names use `databases/sessions_NAME.txt`. The file is written 10 seconds after a change and holds only the metadata of each session: `sessionid`, `id`, `expire`, `used`, `created`, `note` and `settings`. The user data stays in memory; after a restart the store loads it with `session.ondata`. A session item has the properties `sessionid`, `id` (user ID), `data`, `expire`, `used`, `created`, `note`, `settings` and `released`. Store properties: `name` and `items` (a `Map` of items by session ID). Expired sessions are removed every 10 minutes. In a cluster, changes are sent to the other processes. Example: Create a store ```js var session = SESSION(); session.ondata = function(meta, next) { NOSQL('users').one().where('id', meta.id).callback(next); }; ``` ### session.ondata = function(meta, next) Type: `delegate` Loads the data of a session that is not in memory. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `meta` | `Object` | yes | | The session item: `sessionid`, `id`, `note`, `settings`... | | `next` | `Function(err, data)` | yes | | Callback with the data. | Called by `get()`, `getcookie()` and `gettoken()` when the item has no data: after a restart or after the data was released. `meta` is the session item. Call `next(err, data)`. Calls for the same user ID wait for one load. Without `ondata`, `release()`, `release2()` do nothing. Example: Load the user ```js session.ondata = function(meta, next) { NOSQL('users').one().where('id', meta.id).callback(next); }; ``` ### session.onremove = function(item) Type: `event` Called when a session is removed or expires. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `item` | `Object` | yes | | The session item. | Also called by `clear()` and `remove2()`. The sibling delegate `session.onrelease = function(item)` is called when the data of a session is released from memory. Example: Log removed sessions ```js session.onremove = function(item) { item && console.log('Session ended:', item.sessionid); }; ``` ### session.setcookie(res, opt, [callback]) Type: `method` Creates a session and writes its cookie. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `res` | `Controller|Object` | yes | | Where the cookie is written. | | `opt` | `Object` | yes | | Options, see the table. | | `callback` | `Function(err, data, meta)` | no | | Called after the session is created. | Calls `session.set()` and writes an encrypted cookie (made with `ENCRYPTREQ()`) with the session ID and the user ID. `res` can be a controller, a schema `$`, the authorization `$` or a response. | Option | Description | | --- | --- | | `name` | Cookie name. | | `sessionid` | Session ID. Default `UID()`. | | `id` | User ID. | | `data` | Session data. | | `expire` | Expiration, for example `'1 month'`. | | `key` (or `secret`) | Encryption key. | | `strict` | Bind the cookie to the IP address too. Default `false`. | | `note` | A note, for example the user agent. | | `settings` | A string with settings. | | `options` | Cookie options. Default `{ httponly: true, security: 'lax' }`. | Example: Sign in ```js session.setcookie(self, { name: 'sid', id: user.id, data: user, expire: '1 month', key: 'session-key' }, function() { self.redirect('/'); }); ``` ### session.getcookie(req, opt, callback, [param]) Type: `method` Reads the session from the cookie of a request. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `req` | `Object` | yes | | The authorization `$`, a controller or a request. | | `opt` | `Object` | yes | | Options, see the table. | | `callback` | `Function(err, data, meta, init, param)` | yes | | `data` is the session data, `meta` the item, `init` is `true` when `ondata` loaded the data. | | `param` | `Any` | no | | A value passed to the callback. | Decrypts the cookie with `DECRYPTREQ()` and calls `session.get()`. `req` can be the authorization `$`, a controller or a request. Tokens shorter than 20 characters are ignored. An invalid cookie is removed, and with `ddos` each failed attempt is counted for the IP address. | Option | Description | | --- | --- | | `name` | Cookie name. | | `expire` | Extends the session and the cookie by this time. | | `key` (or `secret`) | Encryption key. | | `extendcookie` | Extend the cookie with `expire`. Default `true`. | | `removecookie` | Remove an invalid cookie. Default `true`. | | `options` | Cookie options. | | `ddos` | Failed attempts per IP address before the cookie is not checked anymore. | Example: In AUTH() ```js AUTH(function($) { session.getcookie($, { name: 'sid', expire: '1 month', key: 'session-key', ddos: 5 }, function(err, data) { if (data) $.success(data); else $.invalid(); }); }); ``` ### session.settoken(res, opt, [callback]) Type: `method` Creates a session and returns a token instead of a cookie. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `res` | `Object` | yes | | A controller, a schema `$` or a response. | | `opt` | `Object` | yes | | Options of `setcookie()`. | | `callback` | `Function(err, token, data, meta)` | no | | Receives the token. | Takes the options of `setcookie()` except `name` and `options`, and passes the encrypted token to the callback. Send the token to the client, for example in JSON. Example: API sign-in ```js session.settoken(self, { id: user.id, data: user, expire: '7 days', key: 'session-key' }, function(err, token) { self.json({ token: token }); }); ``` ### session.gettoken(req, opt, callback, [param]) Type: `method` Reads the session from a token. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `req` | `Object` | yes | | The authorization `$` or a request. | | `opt` | `Object` | yes | | Options. | | `callback` | `Function(err, data, meta, init, param)` | yes | | Called with the session. | | `param` | `Any` | no | | A value passed to the callback. | Like `getcookie()`, with the token in `opt.token`. Options: `token`, `expire`, `key` (or `secret`) and `ddos`. Example: Token header ```js AUTH(function($) { session.gettoken($, { token: $.headers['x-token'], key: 'session-key' }, function(err, data) { if (data) $.success(data); else $.invalid(); }); }); ``` ### session.set(sessionid, [id], data, expire, [note], [settings], [callback]) Type: `method` Creates or replaces a session. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `sessionid` | `String` | yes | | Session ID. | | `id` | `String` | no | | User ID. | | `data` | `Object` | yes | | Session data. | | `expire` | `String` | yes | | Expiration. | | `note` | `String` | no | | A note. | | `settings` | `String` | no | | Settings. | | `callback` | `Function(err, data, meta)` | no | | Called after the change. | `id` is the user ID; it can be left out when `data` is an object. `expire` is required, for example `'1 month'`. `session.set2(id, data, [expire], [note], [settings], [callback])` replaces the data of all loaded sessions of user `id` and passes the count of updated sessions. Example: Create a session ```js session.set(UID(), user.id, user, '1 month', $.ua); ``` ### session.get(sessionid, [expire], callback) Type: `method` Reads a session. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `sessionid` | `String` | yes | | Session ID. | | `expire` | `String` | no | | Extends the session by this time. | | `callback` | `Function(err, data, meta, init)` | yes | | Called with the session. | Returns the data through the callback and updates `used`. With `expire`, the session is extended. An expired session is removed. When the data is not in memory, `ondata` loads it and `init` is `true`. `session.get2(id, callback(err, items))` returns all live items of user `id`. Example: Read ```js session.get(self.sessionid, function(err, data, meta) { self.json(data); }); ``` ### session.update(sessionid, data, [expire], [note], [settings], [callback]) Type: `method` Changes a session. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `sessionid` | `String` | yes | | Session ID. | | `data` | `Object` | yes | | New data. | | `expire` | `String` | no | | New expiration from now. | | `note` | `String` | no | | New note. | | `settings` | `String` | no | | New settings. | | `callback` | `Function` | no | | Called after the change. | Replaces the data only when it is loaded; `note`, `settings` and `expire` change always. The callback receives `(null, data, meta)`, or no arguments when the session is missing or not loaded. `session.update2(id, data, [expire], [note], [settings], [callback])` does the same for all sessions of user `id` and passes the count of updated sessions. Example: Update all sessions of a user ```js session.update2(user.id, user, function(err, count) { console.log('Updated', count); }); ``` ### session.remove(sessionid, [callback]) Type: `method` Removes a session. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `sessionid` | `String|Object` | yes | | Session ID or item. | | `callback` | `Function(err, item)` | no | | Called after the removal. | `sessionid` can also be a session item. The callback receives `(null, item)`. `session.remove2(id, [callback])` removes all sessions of user `id` and passes the count, for example to sign a user out everywhere. Example: Sign out ```js session.remove(self.sessionid); self.cookie('sid', '', '-1 day'); ``` Example: Sign out everywhere ```js session.remove2(user.id); ``` ### session.release([sessionid], [expire], [callback]) Type: `method` Frees the data of a session from memory. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `sessionid` | `String|Object` | no | | Session ID or item. | | `expire` | `String` | no | | Used by `release2()`. | | `callback` | `Function(err, count)` | no | | Called with the count. | The session stays valid; the next read loads the data again with `ondata`. Without `sessionid` (or with `null`), releases every session and passes the count. `session.release2(id, [expire], [callback])` releases all sessions of user `id` and, with `expire`, sets their new expiration. `session.releaseunused(lastusage, [callback])` releases sessions not used for `lastusage`, for example `'30 minutes'`; the framework calls it every 10 minutes with `CONF.allow_sessions_unused` (default `'-20 minutes'`). Without `ondata`, `release()` and `release2()` do nothing. Example: Reload a user after a change ```js session.release2(user.id); ``` ### session.contains(sessionid, callback) Type: `method` Returns a session only when its data is in memory. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `sessionid` | `String` | yes | | Session ID. | | `callback` | `Function(err, data, meta)` | yes | | Called with the result. | Unlike `get()`, it never calls `ondata`. The callback receives `(null, data, meta)` or no arguments. `session.contains2(id, callback)` finds the first such session of user `id`. `session.has(sessionid, callback(err, bool))` and `session.has2(id, callback(err, bool))` only tell whether a session exists. Example: Is the user online? ```js session.has2(user.id, function(err, is) { console.log(is ? 'online' : 'offline'); }); ``` ### session.list(id, callback) Type: `method` Lists the live sessions of a user. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `id` | `String` | yes | | User ID. | | `callback` | `Function(err, items)` | yes | | Called with the items. | Passes an array of session items of user `id` and removes expired items. `session.listlive(callback)` lists all sessions with loaded data, for any user. Example: Devices of a user ```js session.list(self.user.id, function(err, items) { self.json(items.map(function(item) { return { id: item.sessionid, note: item.note, used: item.used }; })); }); ``` ### session.count([id], callback) Type: `method` Counts sessions. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `id` | `String` | no | | User ID. | | `callback` | `Function(err, stats)` | yes | | Called with the counts. | Passes `{ used, free, count }`: `used` sessions have loaded data, `free` do not. With `id`, counts only the sessions of that user. `session.usage()` returns the same object for all sessions directly. Example: Stats ```js session.count(function(err, stats) { console.log(stats.count, 'sessions'); }); console.log(session.usage()); ``` ### session.clear([lastusage], [callback]) Type: `method` Removes sessions. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `lastusage` | `String` | no | | Unused time. | | `callback` | `Function(err, count)` | no | | Called after the removal. | With `lastusage` (for example `'7 days'`), removes the sessions not used for that time and passes their count. Without it, removes every session. `session.clean()` removes only expired sessions; the framework calls it every 10 minutes. `session.load([callback])` reads the saved sessions from the file again; `SESSION()` calls it on creation. Example: Remove old sessions ```js session.clear('30 days'); ``` ### allow_sessions_unused : -20 minutes Type: `config` Releases the data of SESSION() items unused for this time. Returns: `String` Every 10 minutes the framework calls `releaseunused()` with this value on every session store. Default `'-20 minutes'`. The sessions stay valid; their data is loaded again with `ondata`. Example: config ```js // /config allow_sessions_unused : -1 hour ``` --- title: Encryption project: Total.js V4 version: 0.0.99 section: reference language: en license: MIT url: https://totaljs.es/docs/total-js-v4/0-0-99/reference/encryption/ updated: 2026-11-18T16:57:34.578Z --- # Encryption > ENCRYPT(), DECRYPT(), ENCRYPTREQ(), DECRYPTREQ() and CONF.secret. The functions that encrypt and decrypt values, and the secret they use. The guide [Encryption](../../guides/encryption/) explains how to use them with examples; this page is the exact reference. ## API ### ENCRYPT(value, [key], [isUnique]) Type: `method` Encrypts a value with CONF.secret and a key. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `value` | `Object|String|Number` | yes | | The value. | | `key` | `String` | no | | Your key, combined with `CONF.secret`. | | `isUnique` | `Boolean` | no | | Different output for the same input. | Returns: `String` The encrypted value; an empty string for `null`. Objects are serialized to JSON, numbers to strings, and a function is called for its value. The result is a string you can store in a cookie or a URL. When `CONF.default_crypto` is set to a Node.js cipher name, the value is encrypted with that cipher, `key` as the cipher key and `CONF.default_crypto_iv`. Example: Encrypt an object ```js var token = ENCRYPT({ id: user.id, expire: NOW.add('1 day') }, 'reset'); ``` ### DECRYPT(value, [key], [jsonConvert]) Type: `method` Decrypts a value from ENCRYPT(). | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `value` | `String` | yes | | The encrypted value. | | `key` | `String` | no | | The same key as in `ENCRYPT()`. | | `jsonConvert` | `Boolean` | no | `true` | Parse the result as JSON. | Returns: `Object|String|null` By default the result is parsed as JSON and `null` is returned when it is not JSON, so pass `false` as `jsonConvert` for a plain string. Returns `null` when the value cannot be decrypted. Example: Decrypt ```js var data = DECRYPT(self.query.token, 'reset'); if (!data || data.expire < NOW) return self.invalid('error-token'); ``` Example: Plain string ```js var id = DECRYPT(value, 'key', false); ``` ### ENCRYPTREQ(req, value, [key], [strict]) Type: `method` Encrypts a value bound to the browser of the request. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `req` | `Request|Controller` | yes | | The request. | | `value` | `Object|String` | yes | | The value. | | `key` | `String` | no | | Encryption key. | | `strict` | `Boolean` | no | `false` | Bind to the IP address too. | Returns: `String` The token. Stores the user agent (and with `strict` the IP address) next to `value` and encrypts it with `ENCRYPT()`. `DECRYPTREQ()` returns the value only for a request with the same user agent (and IP address). `req` can be a request or a controller. Example: Sign-in cookie ```js self.cookie('token', ENCRYPTREQ(self, user.id, 'auth'), '1 month'); ``` ### DECRYPTREQ(req, value, [key]) Type: `method` Decrypts a value from ENCRYPTREQ() for the same browser. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `req` | `Request|Controller` | yes | | The request. | | `value` | `String` | yes | | The token. | | `key` | `String` | no | | The same key as in `ENCRYPTREQ()`. | Returns: `Object|String|undefined` Returns the value, or `undefined` when it cannot be decrypted, or the user agent (or the IP address in strict mode) differs from the request. Example: In AUTH() ```js var id = DECRYPTREQ($.req, $.cookie('token'), 'auth'); ``` ### secret : your-secret Type: `config` The secret of the app used by ENCRYPT() and DECRYPT(). Returns: `String` Defaults to a hash generated for the app. Set your own value in `/config` so tokens stay valid when the app moves to another server. Changing it makes all encrypted tokens invalid. Example: config ```js // /config secret : a-long-random-secret ``` --- title: Middleware project: Total.js V4 version: 0.0.99 section: reference language: en license: MIT url: https://totaljs.es/docs/total-js-v4/0-0-99/reference/middleware/ updated: 2026-11-18T16:57:34.578Z --- # Middleware > MIDDLEWARE(), USE(), MiddlewareOptions and the $ object of a middleware. ## API ### MIDDLEWARE(name, fn, [types], [first]) Type: `method` Registers, replaces or removes a named middleware. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `name` | `String` | yes | | The name used in route flags (`#name`) and in `USE()`. | | `fn` | `Function($)` | yes | | The middleware, or `null` to remove it. | | `types` | `String|String[]` | yes | | Assigns the middleware globally to these request types. | | `first` | `Boolean` | yes | | With `types`, puts the middleware before the others. | `fn` receives one argument, `$` (`MiddlewareOptions`). It must call `$.next()`, call `$.cancel()`, or respond with `$.res`; otherwise the request waits until its timeout. A middleware that is not registered but assigned to a route is skipped and logged as `Middleware not found`. With `types`, the middleware is also assigned globally by calling `USE(name, '', types, first)`. Use a type name or an array: `web`, `file`, `websocket`, `all`. `fn = null` removes the middleware and removes its name from all routes and global lists. `NEWMIDDLEWARE()` is the same function. Middleware registered by a plugin or another owner is removed when that owner is unloaded. Example: Check an API key ```js MIDDLEWARE('apikey', function($) { if ($.headers['x-api-key'] === CONF.apikey) $.next(); else $.res.throw401(); }); exports.install = function() { ROUTE('GET /api/products/', products, ['#apikey']); }; ``` Example: Register and assign to all static files ```js MIDDLEWARE('cors', function($) { $.res.setHeader('Access-Control-Allow-Origin', '*'); $.next(); }, ['file']); ``` Example: Remove ```js MIDDLEWARE('apikey', null); ``` ### USE(name, [url], [types], [first]) Type: `method` Assigns middleware to all requests, to one type of request, or to routes under a URL. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `name` | `String|String[]|Function` | yes | | Middleware name(s), or a function. | | `url` | `String|String[]` | yes | | A URL prefix. An array here is taken as `types`. | | `types` | `String|String[]` | yes | | Request types: `web`, `file`, `websocket`, `all`. | | `first` | `Boolean` | yes | | Puts the middleware before the middleware already assigned. | `USE()` runs after the application is loaded, so it sees the routes from all controllers. - Without `url` and `types`, or with the type `all` or `*`, the middleware runs for every request, static files included, before the routing. `$.controller` is not set there. - With `types` only, it runs for every request of those types. `web` (also `route`, `routes`, `dynamic`, `http`, `https`, `api`, `schema`, `schemas`) means dynamic routes; `file` (also `files`, `static`) means static files and file routes; `websocket` (also `socket`, `sockets`, `websockets`, `ws`, `wss`) means WebSocket routes. - With `url` and `types`, it is added to each existing route of those types whose URL starts with `url`. A `url` of `*` means no URL. `name` can be a string with several names separated by commas or spaces (a leading `#` or `&` is ignored), an array of names, or a function, which is registered as a middleware with a generated name. A name that is already in a list is not added twice. Example: Every request ```js USE('poweredby'); ``` Example: Only dynamic routes under /api/ ```js USE('apikey', '/api/', ['web']); ``` Example: An anonymous middleware for WebSocket routes ```js USE(function($) { console.log('WebSocket', $.url); $.next(); }, ['websocket']); ``` ### $ Type: `class` The argument of every middleware function. A new instance is created for each chain of middleware of a request. Besides the methods below, it has these read-only shortcuts: | Property | Value | | --- | --- | | `$.req`, `$.res` | The request and the response (for WebSocket routes, `$.res` is the WebSocket client) | | `$.user`, `$.session`, `$.sessionid` | The user and session set by authorization | | `$.headers`, `$.ip`, `$.ua`, `$.language` | Request data | | `$.url`, `$.path`, `$.split` | The URL and its parts | | `$.query`, `$.body`, `$.files` | Query string, parsed body and uploaded files | | `$.params`, `$.id` | Route parameters and the controller ID (only when `$.controller` exists) | | `$.controller` | The controller, in middleware of dynamic routes | | `$.options` | The options object of the route | | `$.middleware` | The list of names in the current chain | Example: Read request data ```js MIDDLEWARE('logger', function($) { console.log($.ip, $.url, $.ua); $.next(); }); ``` ### $.next([err]) Type: `method` Continues with the next middleware, or with the action when this was the last one. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `err` | `Boolean|Error|ErrorBuilder` | yes | | `false` to stop, or an error to respond with 500. | - No argument: continue. - `false`: stop the chain; the action is not run. - An `Error` or an `ErrorBuilder`: respond with an error 500 and stop. If the response was already sent, the chain stops by itself. Example: Stop with an error ```js MIDDLEWARE('maintenance', function($) { if (CONF.maintenance) $.next(new Error('Maintenance')); else $.next(); }); ``` ### $.cancel() Type: `method` Stops the chain of middleware without running the action. Returns: `MiddlewareOptions` The same as `$.next(false)`. Use it after you have sent a response yourself. Returns `$`. Example: Answer and stop ```js MIDDLEWARE('ping', function($) { if ($.url === '/ping/') { $.res.send(200, 'pong', 'text/plain'); $.cancel(); } else $.next(); }); ``` ### $.callback() Type: `method` Continues the chain; the same as `$.next()` without an argument. Returns: `MiddlewareOptions` Returns `$`. Example: Continue ```js MIDDLEWARE('log', function($) { console.log($.url); $.callback(); }); ``` ### $.options Type: `property` The options object from the flags of the route. Returns: `Object` An object in the flags array of `ROUTE()` or a file route becomes `$.options` in all middleware of that route. For global middleware it is an empty object. Example: One middleware, different settings ```js MIDDLEWARE('role', function($) { if ($.user && $.user.roles.includes($.options.role)) $.next(); else $.res.throw403(); }); exports.install = function() { ROUTE('GET /admin/', admin, ['#role', { role: 'admin' }]); ROUTE('GET /editor/', editor, ['#role', { role: 'editor' }]); }; ``` ### $.controller Type: `property` The controller of the request, in middleware of dynamic routes. Returns: `Controller` It is set for middleware of a route and for middleware assigned with `USE(name, ...['web'])`. In global middleware of all requests, static files and file routes it is `undefined`. `$.params` and `$.id` read from it. Example: Use the controller ```js MIDDLEWARE('product', function($) { if ($.params.id) $.next(); else $.controller.throw404(); }); ``` ### PATH.middleware([filename]) Type: `method` Returns the absolute path to a file in the middleware directory. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `filename` | `String` | yes | | A file name. | Returns: `String` An absolute path. The directory is set by `directory_middleware`. Example: Path ```js PATH.middleware('auth.js'); ``` ### directory_middleware Type: `config` The directory with middleware files. Default `/middleware/`. Returns: `String` '/middleware/' Each `.js` file is loaded at startup and its `exports.install()` is called. Register the middleware there with `MIDDLEWARE()`. Example: A middleware file ```js // /middleware/auth.js exports.install = function() { MIDDLEWARE('auth', function($) { if ($.user) $.next(); else $.res.throw401(); }); }; ``` --- title: Static files project: Total.js V4 version: 0.0.99 section: reference language: en license: MIT url: https://totaljs.es/docs/total-js-v4/0-0-99/reference/static-files/ updated: 2026-11-18T16:57:34.578Z --- # Static files > File routes, the response methods for files, and the helpers and config of static files. ## API ### FILE(url, action, [flags]) Type: `method` Creates a file route; `ROUTE('FILE /url/*.ext', action, [flags])` calls it. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `url` | `String|Function` | yes | | The URL pattern, or a function `(req, res)` returning `true`. | | `action` | `Function(req, res)|String` | yes | | The handler, a file name or a URL. | | `flags` | `Array` | yes | | `#middleware`, `.ext`, `id:name`, an options object. | A file route handles requests for static files (paths that end with an extension) before the framework looks into `public/`. The first matching route wins; longer URLs are tested first. The `url` forms: | URL | Matches | | --- | --- | | `/photos/*.jpg` | `.jpg` files under `/photos/` | | `/photos/*` or `/photos/*.*` | any file under `/photos/` | | `/favicon.ico` | exactly this file | `action` is `function(req, res)`. It can also be a string: an absolute file name to send with `res.file()`, or an `http://`/`https://` URL whose response is streamed. Instead of a URL you can pass a function `function(req, res)` that returns `true` for the requests to handle. Flags: `#name` adds middleware, `.ext` limits the extensions, `id:name` sets the route ID, and an object becomes `$.options` in middleware. For file routes, put middleware in the flags array, not inline in the URL. When the action does not answer itself, call `res.continue()` to serve the file from `public/`. Example: Protected downloads ```js exports.install = function() { ROUTE('FILE /docs/*.pdf', function(req, res) { res.file(PATH.root('documents/' + U.getName(req.uri.pathname))); }, ['#auth']); }; ``` Example: A fixed file ```js ROUTE('FILE /robots.txt', PATH.root('robots.txt')); ``` Example: Validation function ```js FILE(function(req, res) { return req.uri.pathname.startsWith('/uploads/'); }, function(req, res) { res.continue(); }, ['#auth']); ``` ### FILE404(fn) Type: `method` Sets a handler for static files that do not exist. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `fn` | `Function(req, res)` | yes | | The handler. | `fn(req, res)` is called instead of the 404 response for static files that are missing, not allowed by `static_accepts`, or not found by `res.file()`. Return `true` when you answered the request; otherwise the framework responds with 404. Example: Placeholder image ```js FILE404(function(req, res) { if (req.extension === 'jpg' || req.extension === 'png') { res.file(PATH.public('img/placeholder.png')); return true; } }); ``` ### res.file(filename, [download], [headers], [callback]) Type: `method` Sends a file. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `filename` | `String` | yes | | An absolute path. | | `download` | `String|Boolean` | yes | | A download name, or `true` for the file name. | | `headers` | `Object` | yes | | Additional headers. | | `callback` | `Function` | yes | | Called when the file is sent. | Returns: `Response` `filename` is an absolute path; a leading `@` means a file of a package. The content type comes from the extension of the request (or of the file). The file gets the same caching, GZIP compression, `Range` support and `304 Not Modified` handling as files in `public/`. `.html` files are localized when `allow_localize` is on. `download` adds `Content-Disposition: attachment` with this file name; `true` uses the name of the file. In release mode the framework remembers the file of each URL; call `TOUCH(url)` when it changes. Example: Download ```js ROUTE('FILE /invoices/*.pdf', function(req, res) { var name = U.getName(req.uri.pathname); res.file(PATH.databases('invoices/' + name), 'invoice.pdf'); }); ``` ### res.image(filename, make, [headers], [callback], [persistent]) Type: `method` Processes an image with GraphicsMagick or ImageMagick and sends the result. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `filename` | `String|Stream` | yes | | The source image. | | `make` | `Function(image, res)` | yes | | Sets the image operations. | | `headers` | `Object` | yes | | Additional headers. | | `callback` | `Function` | yes | | Called when the image is sent. | | `persistent` | `Boolean` | yes | | Stores the result as a persistent file. | Returns: `Response` `filename` is an absolute path or a readable stream. `make(image, res)` gets an image object and sets the operations (`resize()`, `crop()`, `quality()`, `grayscale()`, `output()`...). The result is stored in `/tmp/` under the URL of the request and later requests get the stored file. `persistent` stores the result as a persistent file (`timg_` prefix in `/tmp/`) and reuses it while it exists; when omitted, it follows `allow_persistent_images` (default `true`). `res.image_nocache(filename, make, [headers], [callback])` does the same without the cache. Example: Thumbnails ```js ROUTE('FILE /thumbnails/*.jpg', function(req, res) { res.image(PATH.public('photos/' + U.getName(req.uri.pathname)), function(image) { image.resize(150, 150); image.quality(80); }); }); ``` ### res.filefs(name, id, [download], [headers], [callback], [checkmeta]) Type: `method` Sends a file from a FileStorage. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `name` | `String` | yes | | The FileStorage name. | | `id` | `String|Number` | yes | | The file ID. | | `download` | `String` | yes | | A download name. | | `headers` | `Object` | yes | | Additional headers. | | `callback` | `Function` | yes | | Called when done. | | `checkmeta` | `Function(meta)` | yes | | Checks the metadata of the file. | Returns: `Response` Reads the file `id` from `FILESTORAGE(name)` and sends it with its stored content type. `checkmeta(meta)` can inspect the metadata of the file before it is sent. Example: Files from storage ```js ROUTE('FILE /files/*.*', function(req, res) { var id = U.getName(req.uri.pathname).replace(/\..*$/, ''); res.filefs('files', id); }); ``` ### res.imagefs(name, id, make, [headers], [callback], [checkmeta]) Type: `method` Processes an image from a FileStorage and sends the result. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `name` | `String` | yes | | The FileStorage name. | | `id` | `String|Number` | yes | | The file ID. | | `make` | `Function(image, res)` | yes | | Sets the image operations. | | `headers` | `Object` | yes | | Additional headers. | | `callback` | `Function` | yes | | Called when done. | | `checkmeta` | `Function(meta)` | yes | | Checks the metadata of the file. | Returns: `Response` Like `res.filefs()`, but `make(image, res)` sets image operations as in `res.image()`. Example: Avatars from storage ```js ROUTE('FILE /avatars/*.jpg', function(req, res) { var id = U.getName(req.uri.pathname).replace('.jpg', ''); res.imagefs('avatars', id, function(image) { image.resize(100, 100); }); }); ``` ### res.stream(type, stream, [download], [headers], [callback], [nocompress]) Type: `method` Sends a readable stream. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `type` | `String` | yes | | The content type. | | `stream` | `Stream` | yes | | A readable stream. | | `download` | `String` | yes | | A download name. | | `headers` | `Object` | yes | | Additional headers. | | `callback` | `Function` | yes | | Called when done. | | `nocompress` | `Boolean` | yes | | Disables compression. | Returns: `Response` The stream is compressed with GZIP when the content type can be compressed and the client accepts it, unless `nocompress` is `true`. Example: Stream a file ```js ROUTE('FILE /logs/*.txt', function(req, res) { var stream = require('fs').createReadStream(PATH.logs(U.getName(req.uri.pathname))); res.stream('text/plain', stream); }, ['#admin']); ``` ### res.continue([callback]) Type: `method` Serves the requested static file from the public directory, as without a file route. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `callback` | `Function` | yes | | Called when the file is sent. | Returns: `Response` Use it in a file route or a middleware that decides not to answer the request itself. The extension must be in `static_accepts`; otherwise, and when the file does not exist, the response is 404 (or the `FILE404()` handler). It also applies `MAP()`, `MERGE()` and `RESIZE()`. Example: Serve only to signed-in users ```js ROUTE('FILE /private/*.*', function(req, res) { if (req.user) res.continue(); else res.throw401(); }); ``` ### req.filecache(callback) Type: `method` Serves a generated file from `/tmp/`, or asks you to create it. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `callback` | `Function(next, filename, req, res)` | yes | | Creates the missing file. | The file name in `/tmp/` is built from the URL of the request. When the file exists, it is sent and `callback` is not called. Otherwise `callback(next, filename, req, res)` is called: write the file to `filename`, send the response (for example `res.file(filename)`), and call `next()`. At most 20 files are generated at the same time. Example: Generated file ```js ROUTE('FILE /reports/*.csv', function(req, res) { req.filecache(function(next, filename) { require('fs').writeFile(filename, 'id;name\n1;Peter\n', function() { res.file(filename); next(); }); }); }); ``` ### req.extension Type: `property` The extension of a static-file request, without the dot. Returns: `String` Set for requests whose path ends with an extension (`req.isStaticFile` is `true`). Example: Branch by extension ```js FILE404(function(req, res) { if (req.extension === 'svg') { res.send(200, '<svg xmlns="http://www.w3.org/2000/svg"/>', 'image/svg+xml'); return true; } }); ``` ### LOCALIZE(url, [flags], [minify]) Type: `method` Serves static files through the translator, or sets the language of requests. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `url` | `String|Function` | yes | | The URL pattern, or the language function. | | `flags` | `String[]` | yes | | `nocompress`, `.ext` and route flags such as `#middleware`. | | `minify` | `Boolean` | yes | | Minifies HTML. Default `true`. | `LOCALIZE(url)` creates a file route that reads the files under `url` from `public/`, replaces `@(Text)` markers with translations in the request language, and caches the result per language in release mode. HTML is minified when `allow_compile_html` is on; the flag `nocompress` or `minify = false` turns it off. The URL can end with a file pattern such as `/templates/*.html`. Without an extension, `.html`, `.htm`, `.md` and `.txt` files are handled; `.ext` flags choose others. A URL starting with `#` is a sitemap ID. `LOCALIZE(fn)` sets the function `fn(req, res, isStaticFile)` that returns the language of a request. Static `.html` and `.htm` files from `public/` are localized automatically when `allow_localize` is on. Example: Language and files ```js LOCALIZE(function(req, res) { return (req.headers['accept-language'] || 'en').substring(0, 2); }); LOCALIZE('/templates/*.html'); LOCALIZE('/texts/*.md', ['nocompress']); ``` ### RESIZE(url, fn, [flags]) Type: `method` Creates resized images on the fly for a URL. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `url` | `String` | yes | | A URL path, optionally with `*.ext`. | | `fn` | `Function(image)` | yes | | Sets the image operations. | | `flags` | `String[]` | yes | | Source path or URL, `.ext`, `nocache`. | Requests for images under `url` are made from the source images by `fn(image)` and cached in `/tmp/`. By default the source is the same path in `public/`. In `flags`, a path (`/img/`, or `~/absolute/path/`) or an `http(s)://` URL sets where the source images are, `.ext` adds an extension, and `nocache` disables the cache. JPG, JPEG, PNG, GIF, APNG, HEIF and HEIC are always handled. Example: Small images from /public/img/ ```js RESIZE('/img/small/*.jpg', function(image) { image.resize(200, 200); image.quality(80); }, ['/img/']); ``` ### MAP(url, filename, [filter]) Type: `method` Serves a URL from another file or directory. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `url` | `String` | yes | | The URL. | | `filename` | `String` | yes | | A file or a directory. | | `filter` | `String[]|Function` | yes | | Filters the files of a directory. | When `filename` has an extension, the URL is mapped to that file. Otherwise it is a directory and every file inside is mapped under `url`; `filter` is an array of extensions or a function `(filename)` that returns `true` for the files to map. A relative `filename` is looked up in `public/` first. Prefixes: `~` for a path from the application root, `@` for a package, `=` for a theme. A `url` starting with `#` is a sitemap ID. The mapped file is still served only when its extension is allowed. Example: File and directory ```js MAP('/favicon.ico', '/img/favicon.ico'); MAP('/manuals/', '/files/manuals/', ['.pdf']); ``` ### MERGE(url, file1, [file2], [fileN]) Type: `method` Serves several files as one file. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `url` | `String` | yes | | The URL of the merged file. | | `file1` | `String|String[]` | yes | | Files to merge, in order. | The files are joined into one file stored in `/tmp/`. Each argument can be a file name, a URL or an array. A file name with `@` is from a package, with `=` from a theme. The `url` follows the `/versions` file. Example: Bundle ```js MERGE('/js/bundle.js', '/js/jquery.js', '/js/app.js'); MERGE('/css/bundle.css', ['/css/base.css', '/css/theme.css']); ``` ### ACCEPT(extension, [type]) Type: `method` Allows an extension for static files. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `extension` | `String` | yes | | An extension, with or without the dot. | | `type` | `String` | yes | | The content type. | Adds the extension to `static_accepts`. With `type`, it also sets the content type of the extension. Example: 3D models ```js ACCEPT('.glb', 'model/gltf-binary'); ``` ### TOUCH([url]) Type: `method` Clears the cache of processed static files. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `url` | `String` | yes | | A URL such as `/css/default.css`. | The framework remembers each processed file (minified, compressed or not found) by its URL. `TOUCH(url)` forgets one URL, so the next request reads the file again; `TOUCH()` forgets all. Example: After a change ```js require('fs').writeFile(PATH.public('css/theme.css'), css, function() { TOUCH('/css/theme.css'); }); ``` ### PATH.public([filename]) Type: `method` Returns the absolute path to a file in the public directory. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `filename` | `String` | yes | | A relative file name. | Returns: `String` An absolute path. The directory is set by `directory_public`. Example: Path ```js var filename = PATH.public('img/logo.png'); ``` ### F.public(name, [theme]) Type: `method` Returns the URL of a static file, with `static_url` and the `/versions` file applied. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `name` | `String` | yes | | A file name. | | `theme` | `String` | yes | | A theme name. | Returns: `String` A URL. Relative names get the prefix of the helper: `F.public()` uses `static_url`, `F.public_js()` `static_url_script`, `F.public_css()` `static_url_style`, `F.public_image()` `static_url_image`, `F.public_video()` `static_url_video`, `F.public_font()` `static_url_font` and `F.public_download()` `static_url_download`. Names starting with `/` get no prefix. A name starting with `~` ignores the theme, `=theme/` selects a theme (`=?/` the default theme). With `default_root`, the root is added. Views use the same helpers. Example: URLs ```js F.public('/robots.txt'); // /robots.txt F.public_font('icons.woff2'); // /fonts/icons.woff2 F.public_download('manual.pdf'); // /download/manual.pdf ``` ### F.public_js(name, [theme]) Type: `method` Returns the URL of a script, with `static_url_script` as the prefix. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `name` | `String` | yes | | A file name. | | `theme` | `String` | yes | | A theme name. | Returns: `String` A URL. See `F.public()` for the rules. Example: Script ```js F.public_js('app.js'); // /js/app.js ``` ### F.public_css(name, [theme]) Type: `method` Returns the URL of a stylesheet, with `static_url_style` as the prefix. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `name` | `String` | yes | | A file name. | | `theme` | `String` | yes | | A theme name. | Returns: `String` A URL. See `F.public()` for the rules. Example: Stylesheet ```js F.public_css('default.css'); // /css/default.css ``` ### F.public_image(name, [theme]) Type: `method` Returns the URL of an image, with `static_url_image` as the prefix. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `name` | `String` | yes | | A file name. | | `theme` | `String` | yes | | A theme name. | Returns: `String` A URL. See `F.public()` for the rules. Example: Image ```js F.public_image('logo.png'); // /img/logo.png ``` ### directory_public Type: `config` The directory with static files. Default `/public/`. Returns: `String` '/public/' Static-file requests are looked up here. `PATH.public()` builds paths into it. Example: Config file ```text directory_public : /www/ ``` ### static_url Type: `config` The prefix of URLs made by `F.public()`. Default empty. Returns: `String` '' The other prefixes are `static_url_script` (`/js/`), `static_url_style` (`/css/`), `static_url_image` (`/img/`), `static_url_video` (`/videos/`), `static_url_font` (`/fonts/`) and `static_url_download` (`/download/`). They change only the generated URLs; files are still served from their path in `public/`. A prefix can be a full URL, for example of a CDN. Example: Config file ```text static_url_image : https://cdn.example.com/img/ ``` ### static_url_script Type: `config` The prefix of URLs made by `F.public_js()`. Default `/js/`. Returns: `String` '/js/' See `static_url`. Example: Config file ```text static_url_script : /scripts/ ``` ### static_accepts Type: `config` The extensions that static files may have. Returns: `Object` flac, jpg, jpeg, png, gif, ico, wasm, js, mjs, css, txt, xml, ... Static files with other extensions answer 404. The default list: `flac`, `jpg`, `jpeg`, `png`, `gif`, `ico`, `wasm`, `js`, `mjs`, `css`, `txt`, `xml`, `woff`, `woff2`, `otf`, `ttf`, `eot`, `svg`, `zip`, `rar`, `pdf`, `docx`, `xlsx`, `doc`, `xls`, `html`, `htm`, `appcache`, `manifest`, `map`, `ogv`, `ogg`, `mp4`, `mp3`, `webp`, `webm`, `swf`, `package`, `json`, `ui`, `md`, `m4v`, `jsx`, `heif`, `heic`, `ics`, `ts`, `m3u8`, `wav`, `xslt`, `xsd`. In the config file, `static_accepts` **replaces** the list, while `static_accepts_custom` adds extensions to it. Both take a comma-separated list. In code, use `ACCEPT()`. Example: Config file ```text static_accepts_custom : glb, usdz ``` ### allow_static_files Type: `config` Turns handling of static files on or off. Default `true`. Returns: `Boolean` true When `false`, paths with an extension are routed as normal requests and the public directory is not served. Example: Config file ```text allow_static_files : false ``` ### allow_gzip Type: `config` Compresses static files with GZIP. Default `true`. Returns: `Boolean` true Applies to text types: plain text, HTML, CSS, JavaScript, JSX, JSON, XML, SVG and Markdown, when the client sends `Accept-Encoding: gzip`. The compressed copy is stored in `/tmp/`. Example: Config file ```text allow_gzip : false ``` ### allow_compile Type: `config` Minifies static JavaScript, CSS and HTML. Default `true`. Returns: `Boolean` true `allow_compile_script` (JavaScript and `.mjs`), `allow_compile_style` (CSS) and `allow_compile_html` (localized HTML) switch single types; all default to `true`. Files named like `*.min.js`, `*-min.css` or `*.min@version.js` are not minified. In CSS, `url()` values follow the `/versions` file. Example: Config file ```text allow_compile_script : false ``` ### allow_localize Type: `config` Localizes static `.html` and `.htm` files. Default `true`. Returns: `Boolean` true The `@(Text)` markers in HTML files from `public/` are translated to the request language set with `LOCALIZE(fn)`. Example: Config file ```text allow_localize : false ``` ### allow_persistent_images Type: `config` Stores images made by `res.image()` as persistent files. Default `true`. Returns: `Boolean` true The default for the `persistent` argument of `res.image()`. Example: Config file ```text allow_persistent_images : false ``` ### etag_version Type: `config` A value added to the `ETag` of static files. Returns: `String` '' When empty, it is set from `version` (without dots and spaces) at startup. Change `version` or `etag_version` to make browsers download changed files again. Example: Config file ```text etag_version : 2 ``` ### default_root Type: `config` A URL prefix when the application runs under a sub-path. Returns: `String` '' With `default_root : /app/`, static URLs made by `F.public()` and the views start with `/app/`, and the `/versions` file is applied with this prefix. Example: Config file ```text default_root : /app/ ``` ### versions Type: `config` The `/versions` file in the root of the application maps file URLs to versioned URLs. Returns: `File` Each line is `url : newurl`. The value `auto` adds a hash of the file content to the name at startup (`/js/app.js` becomes `/js/app-<hash>.js`). With `-->` instead of `:`, the new URL is also mapped to the original file. Lines starting with `#` or `// ` are comments. The helpers `F.public_*()`, `MERGE()` and views use the new URLs. Example: Config file ```text /js/app.js : /js/app-2.js /css/style.css : auto /img/logo.png --> /img/logo-2023.png ``` ### MODIFY([filename], fn) Type: `method` Changes the content of views, styles and scripts before they are compiled. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `filename` | `String` | no | | A path relative to the app, for example `'/views/index.html'`. | | `fn` | `Function` | yes | | `function(type, filename, value, controller)` that returns the new content. | The function is called with `(type, filename, value, controller)`, where `type` is `'view'`, `'style'`, `'script'` or `'static'` (a static file localized by Total.js) and `filename` is the path relative to the app with a leading `/`. Return the new content; a falsy result keeps it as it was. With `filename` (for example `'/views/index.html'`) the function runs only for that file. The change is made in memory, the file on the disk stays as it is. In release mode compiled content is cached, so the function runs once per file. A function registered by a plugin or a module is removed when it is uninstalled. Example: Add a banner to every view ```js MODIFY(function(type, filename, value) { if (type === 'view') return value.replace('</body>', '<div class="banner">Beta</div></body>'); }); ``` Example: One file only ```js MODIFY('/views/index.html', function(type, filename, value) { return value.replace('@@VERSION@@', CONF.version); }); ``` --- title: WebSockets project: Total.js V4 version: 0.0.99 section: reference language: en license: MIT url: https://totaljs.es/docs/total-js-v4/0-0-99/reference/websockets/ updated: 2026-11-16T15:41:00.817Z --- # WebSockets > The SOCKET route, the WebSocket controller, the connected client and WEBSOCKETCLIENT(). A `SOCKET` route creates a WebSocket controller shared by all clients of a URL; each connection is a client object, and `WEBSOCKETCLIENT()` connects from the server to other WebSocket servers. The guide [WebSockets](../../guides/websockets/) explains how to use them with examples; this page is the exact reference. ## API ### ROUTE('SOCKET /url/', action, [flags], [length]) Type: `method` Declares a WebSocket route. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `url` | `String` | yes | | `SOCKET /path/`, optionally with `+`/`-`, `{params}` and `@apiname` | | `action` | `Function` | yes | | Initializes the WebSocket controller | | `flags` | `Array` | yes | | Flags, origins, protocols, middleware, a length or an options object | | `length` | `Number` | yes | | Maximum message size in kB | Returns: `FrameworkRoute` The route instance The URL starts with `SOCKET` (or `WS`, `WSS`). A `+` or `-` before it limits the route to signed-in or anonymous users. `action` runs once, when the first client connects to the URL, with the WebSocket controller as `this` and the dynamic URL parameters as arguments. `length` is the maximum size of one message in kB (default `CONF.default_websocket_maxlength`, `2`). With `@name` in the URL and no action, the route processes the WebSocket API `@name` and destroys itself when the last client leaves. The flags are described in the entry **WebSocket route flags**. Example: Chat route ```js exports.install = function() { ROUTE('SOCKET /chat/{room}/', chat, ['json'], 32); }; function chat(room) { var self = this; self.autodestroy(); self.on('message', function(client, message) { self.send({ room: room, body: message.body }); }); } ``` Example: WebSocket API without an action ```js exports.install = function() { ROUTE('API @chat -messages_list *Messages --> list'); ROUTE('SOCKET /chat/ @chat'); }; ``` ### ROUTE('SOCKET /url/', action, ['json', 'binary', 'text', ...]) Type: `config` Flags that set the data type, access, origins and protocols of a WebSocket route. - `json` (default): incoming messages are parsed as JSON (invalid JSON is ignored) and outgoing objects are serialized. - `text`, `plain`: messages are strings; objects you send are serialized as JSON. - `binary`: messages are `Buffer` objects. - `raw`: turns off `json` and `binary` (text mode). - `buffer`: the `message` event always receives the raw `Buffer`. - `authorize`, `authorized`, `logged` / `unauthorize`, `unauthorized`, `unlogged`: signed-in or anonymous users only. - `@role`: a role flag; it makes the route `authorize`. - `http://...`, `https://...`: allowed origins; the request `Origin` must contain one of them. - `#middleware`, `&middleware`: middleware names. - `id:name`: the route identifier. - `get`, `csrf`, `http`, `https`, `debug`, `release`: standard route flags. - Any other word is a required sub-protocol. Every listed protocol must be in the client's `Sec-WebSocket-Protocol` header, otherwise the connection is closed with `4001`. - A number is the maximum message size in kB; an object is the middleware options. Example: Binary route for one origin ```js ROUTE('SOCKET /upload/', upload, ['binary', 'https://app.example.com'], 1024); function upload() { this.on('message', function(client, buffer) { // buffer is a Buffer }); } ``` Example: Required sub-protocol ```js // The browser: new WebSocket('wss://example.com/rpc/', 'rpc'); ROUTE('SOCKET /rpc/', rpc, ['rpc']); ``` ### websocket.online Type: `property` The number of connected clients. Returns: `Number` Updated whenever a client connects or disconnects. Example: Broadcast the count ```js function counter() { var self = this; self.on('open', function() { self.send({ online: self.online }); }); } ``` ### websocket.connections Type: `property` All connected clients by their id. Returns: `Object` An object whose keys are client ids and values are client objects. `websocket.keys` holds the same ids as an array. `websocket.id` is the key of the controller in `F.connections`: the URL followed by `#` and the route flags. Example: Read a client ```js var client = this.connections['15']; ``` ### websocket.url Type: `property` The URL of the connection. Returns: `String` The path the first client connected to, with a trailing slash. ### websocket.params Type: `property` The dynamic parameters of the URL. Returns: `Object` Each `{name}` of the route becomes a key. The same values arrive as arguments of the action. Example: Room name ```js ROUTE('SOCKET /rooms/{name}/', room); function room(name) { // name === this.params.name } ``` ### websocket.repository Type: `property` An object for your own data. Returns: `Object` Created on first access and kept for the life of the controller. Example: Keep history ```js function chat() { var self = this; self.repository.history = []; self.on('message', function(client, message) { self.repository.history.push(message); }); } ``` ### websocket.on(name, callback) Type: `method` Registers an event handler. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `name` | `String` | yes | | Event name | | `callback` | `Function` | yes | | Handler | Returns: `WebSocket` The controller Events: `open`, `close`, `message`, `error` and `destroy`. `this` in the handler is the controller. `once(name, fn)` registers a handler for one call, `removeListener(name, fn)` and `removeAllListeners([name])` remove handlers, and `emit(name, [args...])` calls the handlers of your own events. Example: Events ```js function chat() { this.on('open', function(client) {}); this.on('message', function(client, message) {}); this.on('close', function(client, code, message) {}); } ``` ### websocket.send(message, [comparer], [replacer], [params]) Type: `method` Sends a message to all clients or to the clients you select. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `message` | `Object/String/Buffer` | yes | | The message | | `comparer` | `Function` | yes | | `function(client, message, params)` returns `true` to send | | `replacer` | `Function/Boolean` | yes | | JSON replacer | | `params` | `Object` | yes | | Value passed to `comparer` | Returns: `WebSocket` In a `json` route the message is serialized once and sent to every client. `comparer(client, message, params)` returns `true` for the clients that receive the message. `replacer` is passed to `JSON.stringify()`; `true` uses the framework's JSON replacer. When the third argument is not a function, it is used as `params`. Example: Everybody except the sender ```js self.on('message', function(client, message) { self.send(message, function(c) { return c !== client; }); }); ``` Example: With params ```js self.send({ type: 'refresh' }, function(client, message, params) { return client.user && client.user.role === params.role; }, { role: 'admin' }); ``` ### websocket.find(fn) Type: `method` Finds the first client that matches a function. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `fn` | `Function` | yes | | `function(client)` returns `true` for the wanted client | Returns: `Object` The client or `undefined` Returns `undefined` when no client matches. Example: Find a user ```js var client = this.find(function(client) { return client.user && client.user.id === userid; }); client && client.send({ type: 'notify' }); ``` ### websocket.clients() Type: `method` Returns all connected clients as an array. Returns: `Array` Example: List users ```js var users = this.clients().map(function(client) { return client.user ? client.user.name : 'anonymous'; }); ``` ### websocket.close([message], [code]) Type: `method` Closes all connected clients. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `message` | `String` | yes | | Close reason | | `code` | `Number` | yes | | Close code, default `1000` | Returns: `WebSocket` Every client receives a close frame with `code` (default `1000`) and `message`. The controller itself stays; use `destroy()` to remove it. Example: Close everybody ```js this.close('Server restart', 4000); ``` ### websocket.destroy() Type: `method` Closes all clients and removes the controller. Returns: `WebSocket` Emits `destroy`, removes the controller from `F.connections` and frees it. The next client of the URL creates a new controller. ### websocket.autodestroy([callback]) Type: `method` Destroys the controller when no client is online. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `callback` | `Function` | yes | | Called before the controller is destroyed | Returns: `WebSocket` When the last client disconnects and nobody connects within 5 seconds, `callback` is called (with the controller as `this`) and the controller is destroyed. Calling it again adds another callback. Example: Auto destroy ```js function room() { this.autodestroy(function() { console.log('Destroyed', this.url); }); } ``` ### websocket.ping() Type: `method` Sends a ping to all clients. Returns: `WebSocket` The framework calls it on its own every `CONF.default_interval_websocket_ping` ms. The pong answer sets `client.latency`. ### websocket.api(name) Type: `method` · Since: `0.0.44` Processes WebSocket API messages. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `name` | `String` | yes | | API name, with or without `@` | Returns: `WebSocket` Registers a `message` handler that runs `API` routes with the given `@name` for messages whose `TYPE` is `api`. The message `data` is `{ schema: 'operation/param', data: {} }`; the answer is sent back to the client when the message has `callbackid`, with `success: true` and `data`, or `error: true` and the error items. Example: Process an API ```js exports.install = function() { ROUTE('API @chat -messages_list *Messages --> list'); ROUTE('SOCKET /chat/', chat); }; function chat() { this.api('@chat'); this.autodestroy(); } ``` ### websocket.encrypt([enable]) Type: `method` Encrypts messages with `CONF.secret_encryption`. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `enable` | `Boolean` | yes | | Default `true` | Returns: `WebSocket` When enabled and `CONF.secret_encryption` is set, outgoing text messages are encrypted and incoming ones decrypted. Without an argument it enables encryption. ### websocket.on('open', function(client) {}) Type: `event` A client connected. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `client` | `Object` | yes | | The new client | Emitted after the client joined the controller, so `this.online` already counts it. Example: Welcome ```js this.on('open', function(client) { client.send({ type: 'welcome' }); }); ``` ### websocket.on('message', function(client, message) {}) Type: `event` A client sent a message. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `client` | `Object` | yes | | The sender | | `message` | `Object/String/Buffer` | yes | | The message | `message` is an object in `json` routes, a string in `text` routes and a `Buffer` in `binary` or `buffer` routes. Example: Echo ```js this.on('message', function(client, message) { client.send(message); }); ``` ### websocket.on('close', function(client, code, message) {}) Type: `event` A client disconnected. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `client` | `Object` | yes | | The client | | `code` | `Number` | yes | | Close code | | `message` | `String` | yes | | Close reason | `code` and `message` come from the close frame of the client, when it sent one. ### websocket.on('error', function(err, client) {}) Type: `event` A socket error occurred. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `err` | `Error` | yes | | The error | | `client` | `Object` | yes | | The client | ### websocket.on('destroy', function() {}) Type: `event` The controller is being destroyed. ### client.id Type: `property` The unique id of the connection. Returns: `String` A numeric string. It is also available as `client.ID` and is the key in `websocket.connections`. `client.online` is `true` while the connection is open, and `client.controller` (or `client.container`) is the WebSocket controller. ### client.user Type: `property` The user accepted by `AUTH()`. Returns: `Object` You can also assign a value. `client.session` and `client.sessionid` hold the session values from the request. Example: Private message ```js var client = self.find(function(c) { return c.user && c.user.id === message.to; }); ``` ### client.query Type: `property` The query string of the connection URL. Returns: `Object` The values are strings. `client.get` is an alias. Example: Token in the URL ```js // new WebSocket('wss://example.com/live/?channel=sport') this.on('open', function(client) { client.channel = client.query.channel; }); ``` ### client.headers Type: `property` The headers of the upgrade request. Returns: `Object` Also available: `client.ip`, `client.ua`, `client.url`, `client.uri`, `client.mobile`, `client.language` and `client.req`. `client.protocol` is the array of sub-protocols from `Sec-WebSocket-Protocol`. ### client.latency Type: `property` The latency of the last ping in ms. Returns: `Number` Set when the client answers a ping. Clients without an answer or with a higher latency than `CONF.default_websocket_maxlatency` are closed. ### client.send(message, [raw], [replacer]) Type: `method` Sends a message to this client. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `message` | `Object/String/Buffer` | yes | | The message | | `raw` | `Boolean` | yes | | Do not serialize (json routes) | | `replacer` | `Function/Boolean` | yes | | JSON replacer; `true` uses the framework's replacer | Returns: `Object` The client In a `json` route objects are serialized; with `raw` set to `true` the message is sent as it is (a JSON string you already have). In a `text` route objects are serialized and other values converted to strings. In a `binary` route the message must be a `Buffer`. Nothing happens if the client is closed. Example: Reply ```js this.on('message', function(client, message) { client.send({ ok: true, id: message.id }); }); ``` ### client.close([message], [code]) Type: `method` Closes this connection. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `message` | `String` | yes | | Close reason | | `code` | `Number` | yes | | Close code, default `1000` | Returns: `Object` The client Sends a close frame with `code` (default `1000`) and `message`. The arguments can also be passed in the order `(code, message)`. Example: Kick a client ```js client.close('Kicked', 4100); ``` ### client.cookie(name) Type: `method` Reads a cookie of the upgrade request. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `name` | `String` | yes | | Cookie name | Returns: `String` Example: Read a cookie ```js var token = client.cookie('token'); ``` ### client.hostname([path]) Type: `method` Returns the hostname with an optional path. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `path` | `String` | yes | | Path to append | Returns: `String` `client.host()` is an alias. ### F.findConnection(path) Type: `method` Finds a WebSocket controller by its id. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `path` | `String/RegExp` | yes | | Part of the id or a regular expression | Returns: `WebSocket` The controller or `undefined` Returns the first controller whose id contains `path` (or matches a `RegExp`). Controllers are kept in `F.connections`. Example: Send from an HTTP route ```js function notify() { var ws = F.findConnection('/notifications/'); ws && ws.send({ type: 'refresh' }); this.success(); } ``` ### F.findConnections([path]) Type: `method` Finds WebSocket controllers. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `path` | `String/RegExp` | yes | | Part of the id or a regular expression | Returns: `Array` Without `path` it returns all controllers. Example: All rooms ```js F.findConnections('/rooms/').forEach(function(ws) { ws.send({ type: 'shutdown' }); }); ``` ### ON('websocket_begin', function(controller, client) {}) Type: `event` A client joined a WebSocket controller. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `controller` | `WebSocket` | yes | | The controller | | `client` | `Object` | yes | | The client | ### ON('websocket_end', function(controller, client) {}) Type: `event` A client left a WebSocket controller. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `controller` | `WebSocket` | yes | | The controller | | `client` | `Object` | yes | | The client | ### CONF.default_websocket_maxlength Type: `config` The default maximum message size in kB. Returns: `Number` Default `2`. A route overrides it with its `length`. ### CONF.default_websocket_maxlatency Type: `config` · Since: `0.0.59` The maximum ping latency in ms. Returns: `Number` Default `2000`. Clients with a higher latency, or without a pong, are closed. `0` turns the pinger off. The ping runs every `CONF.default_interval_websocket_ping` ms (default `20000`; values below `1000` use `20000`). ### CONF.allow_websocket Type: `config` Enables WebSocket routes. Returns: `Boolean` Default `true`. `CONF.allow_websocket_compression` (default `true`) allows `permessage-deflate`, and `CONF.default_websocket_encodedecode` (default `false`) turns on URI encoding of messages. ### WEBSOCKETCLIENT([callback]) Type: `method` Creates a WebSocket client. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `callback` | `Function` | yes | | `function(client)` | Returns: `WebSocketClient` `callback(client)` is called at once with the new client (also as `this`). Set options, headers and events there, 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('wss://example.com/chat/'); }); ``` ### websocketclient.options Type: `property` Options of the client. Returns: `Object` - `type` (`'json'`): `json`, `text`, `binary` or `buffer`. - `compress` (`true`): asks for `permessage-deflate`. - `reconnect` (`3000`): ms before reconnecting after a closed connection; `0` disables it. - `reconnectserver` (`false`): also reconnect after a connection error or an unexpected HTTP response. - `masking` (`false`): masks outgoing frames. - `encodedecode` (`false`): URI encoding of messages. - `encrypt`: a secret to encrypt and decrypt text messages. - `length`: maximum size of a decompressed message in bytes. - `rejectunauthorized` (`false`): rejects invalid TLS certificates. - `key`, `cert`, `dhparam`: TLS options. Example: Text client ```js WEBSOCKETCLIENT(function(client) { client.options.type = 'text'; client.options.reconnect = 10000; client.connect('ws://127.0.0.1:8000/log/'); }); ``` ### websocketclient.headers Type: `property` Extra headers of the upgrade request. Returns: `Object` `websocketclient.cookies` is an object of cookies sent in the `Cookie` header. Example: Token ```js client.headers['x-token'] = 'secret'; client.cookies.session = 'abc'; ``` ### websocketclient.closed Type: `property` `true` when the client is not connected. Returns: `Boolean` `websocketclient.reconnect` counts the reconnections. ### websocketclient.latency Type: `property` · Since: `0.0.44` The latency of the last ping in ms. Returns: `Number` Set when the server answers `ping()`. ### websocketclient.connect(url, [protocol], [origin]) Type: `method` Opens the connection. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `url` | `String/Object` | yes | | Server URL | | `protocol` | `String` | yes | | Sub-protocol | | `origin` | `String` | yes | | Origin | `url` starts with `ws://` or `wss://`. It can also be an object `{ socket: '/path/to/unix.socket', path: '/chat/' }`. `protocol` is sent in `Sec-WebSocket-Protocol` and `origin` in `Sec-WebSocket-Origin`. The connection starts on the next tick. Example: With a protocol ```js client.connect('wss://example.com/rpc/', 'rpc'); ``` ### websocketclient.send(message, [raw], [replacer]) Type: `method` Sends a message. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `message` | `Object/String/Buffer` | yes | | The message | | `raw` | `Boolean` | yes | | Do not serialize (json) | | `replacer` | `Function/Boolean` | yes | | JSON replacer | Returns: `Boolean` `true` when sent With `type: 'json'` objects are serialized (unless `raw` is `true`). With `text` objects are serialized and other values converted to strings. With `binary` or `buffer` a non-`Buffer` message is converted to a `Buffer`. Returns `false` when the client is closed. Example: Send ```js if (!client.send({ type: 'ping' })) console.log('Not connected'); ``` ### websocketclient.close([message], [code]) Type: `method` Closes the connection. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `message` | `String/Boolean` | yes | | Close reason, or `true` to reconnect | | `code` | `Number` | yes | | Close code, default `1000` | Returns: `WebSocketClient` Sends a close frame with `code` (default `1000`). It also stops reconnecting, unless `message` is `true`: then the connection closes and the client reconnects. The arguments can be passed as `(code, message)`. Example: Reconnect ```js // Close and connect again after options.reconnect ms client.close(true); ``` ### websocketclient.destroy() Type: `method` · Since: `0.0.42` Frees the client and stops reconnecting. Emits `destroy` and removes all event handlers. ### websocketclient.ping([timeout]) Type: `method` · Since: `0.0.44` Sends a ping to the server. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `timeout` | `Number` | yes | | Default `3000` ms | Returns: `WebSocketClient` If no pong arrives within `timeout` ms (default `3000`), the client emits `error` with `'Timeout'` and closes. The pong sets `latency`. Example: Measure latency ```js setInterval(function() { client.ping(5000); }, 30000); ``` ### websocketclient.api([schema], [data], [callback], [timeout]) Type: `method` · Since: `0.0.44` Calls the WebSocket API of a Total.js server. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `schema` | `String` | yes | | Operation, e.g. `'messages_read/123'` | | `data` | `Object` | yes | | Payload | | `callback` | `Function` | yes | | `function(err, response)` | | `timeout` | `Number` | yes | | Default `5000` ms | Returns: `WebSocketClient` Sends `{ TYPE: 'api', data: { schema, data } }`. `callback(err, response)` gets the answer; `err` is `408` after `timeout` ms (default `5000`). Without `schema` it only registers the handler for answers. Example: Call an operation ```js client.api('messages_list', { page: 1 }, function(err, response) { if (err) console.log(err); else console.log(response); }); ``` ### websocketclient.on(name, callback) Type: `method` Registers an event handler. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `name` | `String` | yes | | Event name | | `callback` | `Function` | yes | | Handler | Returns: `WebSocketClient` Events: `open()`, `message(data)`, `close(code, message)`, `error(err)` and `destroy()`. `once()`, `removeListener()`, `removeAllListeners()` and `emit()` work as in the controller. Example: Events ```js client.on('open', function() {}); client.on('message', function(data) {}); client.on('close', function(code, message) {}); client.on('error', function(err) {}); ``` ### client.session Type: `property` The session of the connection. Returns: `Object` The session set by your `AUTH()` delegate for the upgrade request. `client.sessionid` is its id. It can be set. Example: Example ```js function socket() { this.on('open', function(client) { console.log(client.sessionid, client.session); }); } ``` ### client.ping() Type: `method` Sends a ping frame to this client. Returns: `Object` The client. The answer of the client updates `client.latency`. `websocket.ping()` pings all clients. Example: Ping one client ```js function socket() { this.on('open', function(client) { client.ping(); }); } ``` ### websocketclient.url Type: `property` The URL of the last `connect()`. Returns: `String` `websocketclient.protocol` and `websocketclient.origin` keep the other arguments of `connect()`. Example: Example ```js WEBSOCKETCLIENT(function(client) { client.connect('wss://example.com/live/'); client.on('open', function() { console.log('Connected to', client.url); }); }); ``` --- title: NoSQL database project: Total.js V4 version: 0.0.99 section: reference language: en license: MIT url: https://totaljs.es/docs/total-js-v4/0-0-99/reference/nosql/ updated: 2026-11-16T15:41:05.817Z --- # NoSQL database > NOSQL(), TABLE(), database methods, the query builder and the config keys of the embedded database. `NOSQL(name)` and `TABLE(name)` return a database stored in the `databases/` folder. Database methods start a query and return a query builder; builder methods add conditions, sorting, paging and the callback. In this reference `db` is a database returned by `NOSQL()` or `TABLE()` and `builder` the query builder. The guide [NoSQL database](../../guides/nosql/) explains how the parts work together. ## API ### NOSQL(name) Type: `method` Returns a NoSQL database: JSON documents stored in a text file. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `name` | `String` | yes | | Name of the database, or `~` followed by an absolute path to the file. | Returns: `Database` The database instance. The database is stored in `databases/{name}.nosql`, one JSON document per line. The instance is created on the first call and then reused. A name that starts with `~` is an absolute path to the file; such an instance is not cached. All operations return a query builder and run asynchronously in a queue, one after another. Example: Insert and read ```js NOSQL('users').insert({ id: UID(), name: 'Peter', created: NOW }); NOSQL('users').find().where('name', 'Peter').callback(function(err, items) { console.log(items); }); ``` Example: A file outside the databases folder ```js NOSQL('~/www/backup/orders.nosql').find().callback(console.log); ``` ### TABLE(name) Type: `method` Returns a table database: rows with a fixed schema stored in a text file. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `name` | `String` | yes | | Name of the table, or `~` followed by an absolute path to the file. | Returns: `Database` The table instance. The table is stored in `databases/{name}.table`. The first line holds the schema, each next line one row with values separated by `|`. The schema comes from the config key `table_{name}` or from `alter()`; until a table has a schema, its operations wait. Column types: `string`, `string(length)`, `number`, `number(length)`, `boolean` (or `bool`), `date` and `object`. Columns can be separated with `|`, `,` or `;`. Fields that are not in the schema are not stored. When every column has a size, rows have a fixed width. A string longer than its size is cut. A table uses the same methods and query builder as `NOSQL()`. A name that starts with `~` is an absolute path to the file. Example: Schema in the config file ```js // config table_products : id:string(20)|name:string(50)|price:number|stock:number|created:date ``` Example: Use the table ```js TABLE('products').insert({ id: UID(), name: 'Book', price: 12, stock: 5, created: NOW }); TABLE('products').find().where('price', '<', 20).sort('name').callback(console.log); ``` ### directory_databases : /databases/ Type: `config` Folder for the NoSQL and table files. Default `/databases/`, relative to the app directory. `NOSQL()` and `TABLE()` create the folder when they need it. ### table_{name} : column:type|column:type Type: `config` Schema of the table `TABLE(name)`. Columns are `name:type`, separated by `|`, `,` or `;`. Types: `string`, `string(length)`, `number`, `number(length)`, `boolean`, `bool`, `date`, `object`. When the schema in the config differs from the schema in the file, the table is rewritten to the new schema the first time it is used. Example: Config ```js table_users : id:string(20)|name:string(50)|email:string(120)|age:number|active:boolean|created:date ``` ### textdb_inmemory : 0 Type: `config` Keeps small databases in memory for reading. Size in megabytes. Default `0` (off). A database whose file is smaller than this number of megabytes is cached in memory after it is read, and later reads use the cache. Writes keep the cache in sync or reset it. Example: Cache databases up to 10 MB ```js // config textdb_inmemory : 10 ``` ### textdb_worker : false Type: `config` Runs the NoSQL engine in a worker thread. Default `false`. With `true`, and only while the web server is running, all `NOSQL()` and `TABLE()` operations run in a worker thread, so reading large files does not block the main thread. The `oninsert`, `onupdate` and `onremove` handlers are not called in this mode. Example: Config ```js textdb_worker : true ``` ### db.find() Type: `method` Finds documents. The response is an array. Returns: `QueryBuilder` Builder for conditions and the callback. Alias: `db.all()`. Add conditions, sorting and limits to the returned builder. The callback receives `(err, items, meta)`, where `meta` has `count` (matched documents), `counter`, `scanned` and `duration`. Without sorting and pagination, reading stops as soon as `take()` documents are found. Example: Find documents ```js NOSQL('users').find().where('active', true).sort('name').take(50).callback(function(err, items, meta) { console.log(items.length, meta.duration); }); ``` ### db.find2() Type: `method` Finds documents, reading the file from the end. Returns: `QueryBuilder` Builder for conditions and the callback. Like `find()`, but the newest documents come first, because new documents are appended to the end of the file. Example: The last ten log entries ```js NOSQL('logs').find2().take(10).callback(console.log); ``` ### db.read() Type: `method` Reads one document. The response is the document or nothing. Returns: `QueryBuilder` Builder for conditions and the callback. Alias: `db.one()`. Reads the file from the end and stops at the first match, so with several matches it returns the newest one. Example: Read by id ```js NOSQL('users').read().id(id).fields('-password').callback(function(err, user) { if (user) console.log(user.name); }); ``` ### db.list() Type: `method` Finds documents and returns a page with paging data. Returns: `QueryBuilder` Builder for conditions and the callback. The response is `{ page, pages, limit, count, items }`. `count` is the number of all matching documents, so use it with `page()` or `paginate()`. Example: A page for a grid ```js NOSQL('users').list().search('name', $.query.q).sort('name').paginate($.query.page, $.query.limit, 100).callback(function(err, response) { // response.items, response.count, response.pages }); ``` ### db.count() Type: `method` Counts matching documents. The response is `{ count: Number }`. Returns: `QueryBuilder` Builder for conditions and the callback. Example: Count ```js NOSQL('users').count().where('active', true).callback(function(err, response) { console.log(response.count); }); ``` ### db.scalar(type, key, [key2]) Type: `method` Computes values over matching documents: min, max, sum, count or groups. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `type` | `String` | yes | | `group`, `min`, `max` or `sum`. With one argument it is the field name. | | `key` | `String` | no | | Field to compute, or the field to group by when `key2` is given. | | `key2` | `String` | no | | Field with the values, grouped by `key`. | Returns: `QueryBuilder` Builder for conditions and the callback. - `scalar(type, key)` or `scalar(key)`: the response is `{ count, sum, min, max }` for the field `key`. - `scalar('group', key)`: counts documents by the values of `key`, e.g. `{ admin: 2, user: 10 }`. - `scalar('group', key, key2)`: sums `key2` by the values of `key`. - `scalar('max', key, key2)`, `scalar('min', key, key2)`: the highest / lowest value of `key2` for each value of `key`; any other type sums `key2`. Example: Statistics of a field ```js NOSQL('orders').scalar('price').where('paid', true).callback(function(err, response) { // response: { count, sum, min, max } }); ``` Example: Sum by group ```js NOSQL('orders').scalar('group', 'country', 'price').callback(function(err, response) { // { SK: 1200, CZ: 800 } }); ``` ### db.stats(groupfield, datefield, key, [type]) Type: `method` Groups documents by a field and a period and returns min, max and count of a value. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `groupfield` | `String` | yes | | Field to group by. | | `datefield` | `String` | yes | | Field with a `Date`. | | `key` | `String` | yes | | Field with the measured value. | | `type` | `String` | no | `daily` | `hourly`, `monthly` or `yearly`; anything else is daily. | Returns: `QueryBuilder` Builder for conditions and the callback. The response is `{ [group]: { [period]: { min, max, count } } }`. The period key is the date formatted as `yyyyMMddHH` (`hourly`), `yyyyMMdd` (default, daily), `yyyyMM` (`monthly`) or `yyyy` (`yearly`). Only documents with a `Date` in `datefield` are used. Example: Monthly temperatures by sensor ```js NOSQL('measurements').stats('sensor', 'created', 'temperature', 'monthly').callback(function(err, response) { // { sensor1: { '202201': { min: -4, max: 8, count: 744 } } } }); ``` ### db.insert(doc, [check]) Type: `method` Inserts a document. The response is `1`. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `doc` | `Object` | yes | | The document. | | `check` | `Boolean` | no | `false` | Insert only when no document matches the conditions of the returned builder. | Returns: `QueryBuilder` Builder for the callback (and for conditions with `check`). The document is appended to the end of the file. Key prefixes used by `update()` (`+`, `-`, `*`, `/`, `!`, `=`, `<`, `>`) are removed from the keys. With `check` set to `true` the method returns a builder for conditions: the document is inserted only when no document matches them, otherwise the response is `0`. Example: Insert ```js NOSQL('users').insert({ id: UID(), name: 'Peter', created: NOW }).callback(function(err) { console.log('Inserted'); }); ``` Example: Insert only a unique email ```js NOSQL('users').insert(model, true).where('email', model.email).callback(function(err, count) { if (!count) console.log('Exists'); }); ``` ### db.update(data, [upsert]) Type: `method` Changes fields of matching documents. The response is the number of changed documents. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `data` | `Object` | yes | | Fields to change, with optional prefixes. | | `upsert` | `Boolean` | no | `false` | Insert the data when no document matches. | Returns: `QueryBuilder` Builder for conditions and the callback. Aliases: `db.modify()`, `db.mod()`. Only the fields in `data` change; other fields stay. Keys with the value `undefined` are skipped. A prefix in the key performs an operation with the stored value: | Key | Operation | | --- | --- | | `field` | Set the value | | `+field` | Add (a missing value counts as `0`) | | `-field` | Subtract | | `*field` | Multiply | | `/field` | Divide | | `!field` | Toggle a boolean; the value is ignored | | `>field` | Keep the higher value | | `<field` | Keep the lower value | With `upsert` the data (without the prefixes) is inserted as a new document when nothing matched; `builder.insert(fn)` can change it first. Example: Update by id ```js NOSQL('products').update({ price: 15, '+version': 1, updated: NOW }).id(id).callback(function(err, count) { console.log('Updated:', count); }); ``` Example: Upsert a counter ```js NOSQL('visits').update({ id: url, '+count': 1 }, true).id(url); ``` ### db.remove() Type: `method` Removes matching documents. The response is the number of removed documents. Returns: `QueryBuilder` Builder for conditions and the callback. Alias: `db.rem()`. Removed documents are marked in the file; `clean()` frees the space. Without conditions all documents are removed. Example: Remove old documents ```js NOSQL('sessions').remove().where('expire', '<', NOW).callback(function(err, count) { console.log('Removed:', count); }); ``` ### db.clear([callback]) Type: `method` Removes all documents. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `callback` | `Function` | no | | Called when the database is empty. | Returns: `QueryBuilder` A builder. A NoSQL database deletes its data file. A table keeps only its schema line. Example: Clear ```js NOSQL('cache').clear(function() { console.log('Empty'); }); ``` ### db.clean([callback]) Type: `method` Compacts the file: rewrites it without removed and outdated lines. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `callback` | `Function` | no | | Called when the file is rewritten. | Returns: `QueryBuilder` The database. Removing a document, and updating one that grows, leaves unused lines in the file. Run `clean()` from time to time, e.g. once a day, to make the file smaller and reading faster. Example: Clean once a day ```js ON('service', function(counter) { if (counter % 1440 === 0) NOSQL('logs').clean(); }); ``` ### db.drop() Type: `method` Deletes the database: the data file, its backups (`.bk`) and log (`.log`). Returns: `QueryBuilder` A builder. A callback set with `.callback()` is called when the drop is queued, with `{ success: true }` as its first argument. Example: Drop ```js NOSQL('temporary').drop(); ``` ### db.backups([callback]) Type: `method` Reads the backups made by `builder.backup()`. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `callback` | `Function` | no | | `function(err, items)`. | Returns: `QueryBuilder` Builder for conditions and the callback. Backups are stored in `{file}.bk`, newest first. Each record has `date`, `body` (the original document as a JSON string) and the fields you passed to `builder.backup(data)`. You can filter the records with the returned builder. Example: Backups made by a user ```js NOSQL('products').backups().where('user', 'Peter').take(20).callback(function(err, items) { items.forEach(item => console.log(item.date, JSON.parse(item.body))); }); ``` ### db.usage([callback]) Type: `method` Returns the number of documents and the file size. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `callback` | `Function` | no | | `function(err, response)`. | Returns: `QueryBuilder` A builder. The response is `{ documents, filesize }` (size in bytes). The values come from the last counting of the database; `db.recount()` counts the documents and measures the file again. Example: Usage ```js NOSQL('users').usage(function(err, response) { console.log(response.documents, response.filesize); }); ``` ### db.memory([count], [size]) Type: `method` Sets the read buffer of the database. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `count` | `Number` | no | `15` | Number of documents processed at once. | | `size` | `Number` | no | `32` | Size of the read buffer in kB. | Larger buffers read big files faster and use more memory. Example: Bigger buffers ```js NOSQL('logs').memory(50, 128); ``` ### db.lock(callback) Type: `method` Runs a function while no other operation of the database runs. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `callback` | `Function` | yes | | `function(next)`; call `next()` to release the lock. | The callback receives `next`. Queued operations wait until you call it. Example: Lock ```js NOSQL('counters').lock(function(next) { // exclusive work with the file next(); }); ``` ### db.alter(schema, [callback]) Type: `method` Sets or changes the schema of a table. Only for `TABLE()`. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `schema` | `String` | yes | | Columns as `name:type`, separated by `\|`, `,` or `;`. | | `callback` | `Function` | no | | Called when the schema is applied. | Returns: `Database` The table. A new table writes the schema line. When the schema differs from the current one, the file is rewritten and existing rows get the new columns. A column written as `newname=oldname:type` takes the values of the old column. Example: Declare a table ```js TABLE('users').alter('id:string(20)|name:string(50)|age:number|active:boolean|created:date'); ``` Example: Rename a column ```js TABLE('users').alter('id:string(20)|fullname=name:string(50)|age:number|active:boolean|created:date'); ``` ### db.oninsert = function(doc) {} Type: `delegate` Called for every inserted document. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `doc` | `Object` | yes | | The inserted document. | Assign it before the first operation of the database. Called only by `NOSQL()` databases and not when `textdb_worker` is on. Example: Log inserts ```js var db = NOSQL('orders'); db.oninsert = function(doc) { console.log('New order', doc.id); }; ``` ### db.onupdate = function(doc) {} Type: `delegate` Called for every changed document. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `doc` | `Object` | yes | | The document after the change. | Assign it before the first operation of the database. Called by `NOSQL()` and `TABLE()`, not when `textdb_worker` is on. Example: Log updates ```js NOSQL('orders').onupdate = function(doc) { console.log('Changed order', doc.id); }; ``` ### db.onremove = function(record) {} Type: `delegate` Called for every removed document. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `record` | `String` | yes | | The removed record as stored in the file. | Assign it before the first operation of the database. It receives the stored line of the document as a string (JSON for `NOSQL()`). Not called when `textdb_worker` is on. Example: Log removals ```js NOSQL('orders').onremove = function(record) { var doc = JSON.parse(record); console.log('Removed order', doc.id); }; ``` ### builder.where(name, [operator], value) Type: `method` Adds a condition that compares a field with a value. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `name` | `String` | yes | | Field name. | | `operator` | `String` | no | `==` | Comparison operator. | | `value` | `Object` | yes | | Value to compare with. | Returns: `QueryBuilder` The same builder, for chaining. Operators: `=` and `==` (equal), `!=` and `<>` (not equal), `>`, `<`, `>=`, `<=`. With two arguments the operator is `==`. A dotted name reads a nested field (`address.city`); a missing parent does not throw. Example: Conditions ```js NOSQL('users').find().where('role', 'admin').where('age', '>=', 18).where('address.city', 'Bratislava').callback(console.log); ``` ### builder.id(id) Type: `method` Adds a condition for the field `id`. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `id` | `String|Array` | yes | | The id or an array of ids. | Returns: `QueryBuilder` The same builder, for chaining. An array of ids works like `in('id', ids)`. Example: By id ```js NOSQL('users').read().id('3ab5k001pt51d').callback(console.log); ``` Example: Several ids ```js NOSQL('users').find().id(['a1', 'a2', 'a3']).callback(console.log); ``` ### builder.in(name, value, [key]) Type: `method` The field value must be in the array. | 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. When the field holds an array, it is enough that one of its items is in `value`. With `key`, `value` is an array of objects and their `key` property is used. Example: In ```js NOSQL('products').find().in('category', ['books', 'music']).callback(console.log); ``` Example: Ids from other documents ```js NOSQL('users').find().in('id', orders, 'userid').callback(console.log); ``` ### builder.notin(name, value, [key]) Type: `method` The field value must not be in the array. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `name` | `String` | yes | | Field name. | | `value` | `Array` | yes | | Excluded values. | | `key` | `String` | no | | Property to read from objects in `value`. | Returns: `QueryBuilder` The same builder, for chaining. The opposite of `in()`. With `key`, `value` is an array of objects and their `key` property is used. Example: Not in ```js NOSQL('orders').find().notin('status', ['canceled', 'deleted']).callback(console.log); ``` ### builder.between(name, a, b) Type: `method` The field value must be between two values, both included. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `name` | `String` | yes | | Field name. | | `a` | `Number|Date|String` | yes | | Lowest value. | | `b` | `Number|Date|String` | yes | | Highest value. | Returns: `QueryBuilder` The same builder, for chaining. Example: Between ```js NOSQL('orders').find().between('created', NOW.add('-7 days'), NOW).callback(console.log); ``` ### builder.search(name, value, [where]) Type: `method` Case-insensitive text search in a field. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `name` | `String` | yes | | Field name. | | `value` | `String` | yes | | Searched text. | | `where` | `String` | no | | `beg` or `end`. | Returns: `QueryBuilder` The same builder, for chaining. Without `where` the field must contain the value. `beg` means it starts with the value, `end` that it ends with it. A field with an array matches when one of its items matches. An empty field or value never matches. Example: Search ```js NOSQL('products').find().search('name', 'phone').callback(console.log); ``` Example: Starts with ```js NOSQL('users').find().search('email', 'admin', 'beg').callback(console.log); ``` ### builder.contains(name) Type: `method` The field must not be empty. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `name` | `String` | yes | | Field name. | Returns: `QueryBuilder` The same builder, for chaining. An array must have items; any other value must be truthy. Example: With photos ```js NOSQL('products').find().contains('photos').callback(console.log); ``` ### builder.empty(name) Type: `method` The field must be empty. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `name` | `String` | yes | | Field name. | Returns: `QueryBuilder` The same builder, for chaining. An empty array, `null`, `undefined`, an empty string, `0` or `false`. Example: Without a note ```js NOSQL('orders').find().empty('note').callback(console.log); ``` ### builder.year(name, [operator], value) Type: `method` Compares the year of a date field. `month()` and `day()` compare the month (1-12) and the day of the month. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `name` | `String` | yes | | Field with a `Date`. | | `operator` | `String` | no | `=` | Comparison operator. | | `value` | `Number` | yes | | Year, month (1-12) or day. | Returns: `QueryBuilder` The same builder, for chaining. `builder.month(name, [operator], value)` and `builder.day(name, [operator], value)` work the same way. Operators are the same as in `where()`; the default is `=`. Fields without a date never match. Example: Orders from June 2022 on ```js NOSQL('orders').find().year('created', 2022).month('created', '>=', 6).callback(console.log); ``` ### builder.or(fn) Type: `method` Joins the conditions added inside the function with OR. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `fn` | `Function` | yes | | `function(builder)` that adds conditions. | Returns: `QueryBuilder` The same builder, for chaining. The function receives the builder (also as `this`). Conditions outside the function are still joined with AND. Example: Or ```js NOSQL('products').find().where('active', true).or(function(builder) { builder.where('stock', '>', 0); builder.where('preorder', true); }).callback(console.log); ``` ### builder.rule(code, [arg]) Type: `method` Adds a raw JavaScript condition. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `code` | `String` | yes | | JavaScript expression, e.g. `doc.age > arg.age`. | | `arg` | `Object` | no | | Values for the expression. | Returns: `QueryBuilder` The same builder, for chaining. `code` is an expression that returns a boolean. It sees `doc` (the document) and `arg` (your values; the keys of `arg` are copied to it). Code with the words `require` or `global` is rejected and matches nothing. Example: Rule ```js NOSQL('users').find().rule('doc.age >= arg.min && doc.age <= arg.max', { min: 18, max: 30 }).callback(console.log); ``` ### builder.fields(fields) Type: `method` Chooses the returned fields. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `fields` | `String` | yes | | Fields, e.g. `id,name,email` or `-password`. | Returns: `QueryBuilder` The same builder, for chaining. A comma-separated list. `-name` removes a field and keeps the others. `name as title` returns the field under another name. Example: Only some fields ```js NOSQL('users').find().fields('id,name,email').callback(console.log); ``` Example: Without a field ```js NOSQL('users').read().id(id).fields('-password').callback(console.log); ``` ### builder.sort(sort) Type: `method` Sorts the result. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `sort` | `String` | yes | | E.g. `name`, `created_desc` or `country,name_desc`. | Returns: `QueryBuilder` The same builder, for chaining. Alias: `builder.gridsort()`. `name` or `name_asc` sorts ascending, `name_desc` descending. Several fields are separated with commas; dotted names sort by nested fields. Example: Sort ```js NOSQL('users').find().sort('created_desc').take(10).callback(console.log); ``` ### builder.take(count) Type: `method` Returns at most `count` documents. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `count` | `Number` | yes | | Maximum number of documents. | Returns: `QueryBuilder` The same builder, for chaining. Alias: `builder.limit()`. Example: Take ```js NOSQL('users').find().take(5).callback(console.log); ``` ### builder.skip(count) Type: `method` Skips the first `count` matching documents. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `count` | `Number` | yes | | Number of documents to skip. | Returns: `QueryBuilder` The same builder, for chaining. Example: Skip ```js NOSQL('users').find().sort('name').skip(20).take(10).callback(console.log); ``` ### builder.first() Type: `method` Returns only the first matching document instead of an array. Returns: `QueryBuilder` The same builder, for chaining. In a `join()` it makes the joined field one document (or `null`) instead of an array. Example: First ```js NOSQL('users').find().where('role', 'admin').sort('created').first().callback(console.log); ``` ### builder.page(page, [limit]) Type: `method` Selects a page. The page number starts at `0`. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `page` | `Number` | yes | | Page index, starting at `0`. | | `limit` | `Number` | no | | Documents per page. | Returns: `QueryBuilder` The same builder, for chaining. Sets `skip` to `page * limit`. Without `limit` the value of an earlier `take()` is used. For page numbers from the query string, which start at `1`, use `paginate()`. Example: Second page ```js NOSQL('users').list().sort('name').page(1, 20).callback(console.log); ``` ### builder.paginate(page, limit, [maxlimit]) Type: `method` Selects a page. The page number starts at `1`. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `page` | `Number|String` | yes | | Page number, starting at `1`. | | `limit` | `Number|String` | yes | | Documents per page. | | `maxlimit` | `Number` | no | | Highest allowed limit. | Returns: `QueryBuilder` The same builder, for chaining. Accepts strings, so values from the query can be passed as they are. A page lower than `1` becomes `1`. `limit` is capped by `maxlimit`; without `limit`, `maxlimit` is used. Example: From the query ```js NOSQL('users').list().paginate($.query.page, $.query.limit, 100).callback(function(err, response) { $.callback(response); }); ``` ### builder.callback(fn, [error]) or builder.callback($, [error]) Type: `method` Sets the function that receives the result, or connects the builder to an operation `$`. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `fn` | `Function|Object` | yes | | `function(err, response, meta)` or the `$` object of an operation. | | `error` | `String` | no | | Error when nothing was found, e.g. `error-users-404`. | Returns: `QueryBuilder|Promise` The builder for a function; a promise for `$`. With a function, it receives `(err, response, meta)`. With the `$` of a schema operation, an error is passed to `$.invalid()` and the method returns a promise with the response, so you can `await` it. `error` is used when the response is empty (nothing, `0` or an empty array): the function receives it as `err`, or `$.invalid(error)` is called. Example: Callback ```js NOSQL('users').find().callback(function(err, items, meta) { console.log(items, meta.scanned); }); ``` Example: Await in an operation ```js schema.setRead(async function($) { var item = await NOSQL('users').read().id($.id).callback($, 'error-users-404'); $.callback(item); }); ``` ### builder.promise([fn]) Type: `method` Returns a promise with the response. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `fn` | `Function` | no | | `function(response)` that returns the value for the promise. | Returns: `Promise` Promise with the response. The promise rejects with the error. `fn` can transform the response before the promise resolves. Example: Await ```js var items = await NOSQL('users').find().where('active', true).promise(); ``` Example: Transform ```js var count = await NOSQL('users').count().promise(response => response.count); ``` ### builder.done($, fn, [param]) Type: `method` Calls `fn` with the response, or `$.invalid()` on an error. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `$` | `Object` | yes | | The `$` object of an operation. | | `fn` | `Function` | yes | | `function(response, param)`. | | `param` | `Object` | no | | Value passed to `fn` as the second argument. | Returns: `QueryBuilder` The same builder, for chaining. Example: Done ```js NOSQL('users').count().done($, function(response) { $.callback(response.count); }); ``` ### builder.error(message) Type: `method` Sets an error for an empty response. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `message` | `String` | yes | | Error message or key. | Returns: `QueryBuilder` The same builder, for chaining. Alias: `builder.err()`. When the response is empty (nothing, `0` or an empty array), the callback receives this error, or `$.invalid()` is called when the builder is connected to `$`. Example: Not found ```js NOSQL('users').read().id(id).error('error-users-404').callback($); ``` ### builder.insert(fn) Type: `method` Changes the document that an upsert inserts. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `fn` | `Function` | yes | | `function(doc, builder)`. | Returns: `QueryBuilder` The same builder, for chaining. Only for `update(data, true)`. When nothing matched, `fn` receives the data that will be inserted and the builder. Example: Upsert with extra fields ```js NOSQL('stats').update({ id: key, '+count': 1, updated: NOW }, true).id(key).insert(function(doc) { doc.created = NOW; }); ``` ### builder.backup([data]) Type: `method` Saves the original documents before an update or removal. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `data` | `Object` | no | | Extra fields for the backup record, e.g. who made the change. | Returns: `QueryBuilder` The same builder, for chaining. Each changed or removed document is appended to `{file}.bk` as `{ ...data, date, body }`, where `body` is the original document as a JSON string. Read the backups with `db.backups()`. Example: Backup with the user ```js NOSQL('products').update(model).id(model.id).backup({ user: $.user.name }).callback($.done()); ``` ### builder.join(field, database, [type]) Type: `method` Adds documents from another database to each result. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `field` | `String` | yes | | Field that receives the joined documents. | | `database` | `String` | yes | | `name`, `nosql/name` or `table/name`. | | `type` | `String` | no | `left` | `inner`; anything else is a left join. | Returns: `QueryBuilder` Builder for the joined database. Returns a new builder for the joined database: set the link with `on()`, and use `where()`, `fields()`, `take()` or `first()` on it. A `callback()` on it sets the callback of the main query. `database` is a NoSQL name, `nosql/name` or `table/name`. By default (`left`) every document is kept and `field` is an array (or `null` with `first()`). With `inner`, documents without a match are left out. Example: Orders with their user ```js NOSQL('orders').find().where('paid', true).join('user', 'users').on('id', 'userid').fields('id,name').first().callback(function(err, items) { // items[0].user = { id, name } }); ``` ### builder.on(field, parentfield) Type: `method` Links a joined database to the main query. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `field` | `String` | yes | | Field in the joined database. | | `parentfield` | `String` | yes | | Field in the documents of the main query. | Returns: `QueryBuilder` The same builder, for chaining. Use it on the builder returned by `join()`. A joined document matches when its `field` equals `parentfield` of the main document. Example: On ```js NOSQL('users').find().join('orders', 'orders').on('userid', 'id').callback(console.log); ``` ### builder.gridfilter(name, obj, [type], [field]) Type: `method` Adds a condition from a filter value typed by a user. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `name` | `String` | yes | | Key in `obj`. | | `obj` | `Object` | yes | | The filter values, e.g. `$.query`. | | `type` | `Function` | no | `String` | `String`, `Number`, `Date` or `Boolean`. | | `field` | `String` | no | | Field to filter when it differs from `name`. | Returns: `QueryBuilder` The same builder, for chaining. Reads `obj[name]` and does nothing when it is empty. The value is converted with `type` (`String`, `Number`, `Date` or `Boolean`): - `a - b` adds `between()`. - `a, b` adds `in()`; for strings, `search()` for each value joined with OR. - A string adds `search()`; other types add `where()`. - For `Date`: `today`, `yesterday`, a year (`2022`), a month number, or a date for the whole day. Example: Filters from the query ```js var builder = NOSQL('orders').list(); builder.gridfilter('name', $.query); builder.gridfilter('price', $.query, Number); builder.gridfilter('created', $.query, Date); builder.paginate($.query.page, $.query.limit, 50); builder.callback(function(err, response) { $.callback(response); }); ``` ### builder.autofill($, [allowedfields], [skipfields], [defsort], [maxlimit]) Type: `method` Sets fields, filters, sorting and paging from the query of an operation. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `$` | `Object` | yes | | The `$` object of a schema operation. | | `allowedfields` | `String` | no | | Extra fields, e.g. `id,created:date`. | | `skipfields` | `String` | no | | Schema fields to leave out, e.g. `password`. | | `defsort` | `String|Number` | no | | Default sorting, e.g. `created_desc`. A number here is `maxlimit`. | | `maxlimit` | `Number` | no | `50` | Highest page size. | Returns: `QueryBuilder` The same builder, for chaining. Reads `$.query` and the schema of the operation: - `fields`: returned fields; only schema fields and `allowedfields`. Without it, all of them. - Any key with the name of a schema field adds a filter with `gridfilter()`. - `sort`: e.g. `name_desc`; unknown fields are ignored. Without it, `defsort`. - `page` and `limit`: `paginate()` with `maxlimit`. `allowedfields` adds fields that are not in the schema (`name:type`, where the type also adds a filter); `skipfields` hides schema fields. Example: Query operation ```js schema.setQuery(async function($) { var response = await NOSQL('users').list().autofill($, 'id,created:date', 'password', 'created_desc', 100).callback($); $.callback(response); }); ``` --- title: Localization project: Total.js V4 version: 0.0.99 section: reference language: en license: MIT url: https://totaljs.es/docs/total-js-v4/0-0-99/reference/localization/ updated: 2026-11-16T15:41:05.817Z --- # Localization > Resource files, translation functions, the localization delegate and the translate tool. Global functions, delegates, properties, configuration keys, view commands and command-line tools for resource files and translations. The guide [Localization](../../guides/localization/) explains how they work together, with examples; this page is the exact reference. ## API ### resources/{name}.resource Type: `type` A text file with `key : value` lines that holds the texts of one language. The file name without `.resource` is the name of the resource, usually a language (`en`, `sk`). `default.resource` is the fallback for all languages. Each line holds a key, ` : ` and a value. Keep a space after the colon, because the parser skips the first character after `:`. Lines that start with `//` or `#` are comments. Keys `T` + hash are translations of `@(Text)` and are created by `total4 translate`. A resource is joined from files registered with `F.register()`, then `tmp/{name}.resource`, then `resources/{name}.resource`; a later line with the same key wins. Example: resources/sk.resource ```text // Slovak texts title : Moja stránka error-email : Zadajte platnú e-mailovú adresu ``` ### RESOURCE([name], key) Type: `method` Reads a value from a resource file. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `name` | `String` | no | `default` | The resource name (file name without `.resource`), usually a language. | | `key` | `String` | yes | | The key. | Returns: `String` The value, or an empty string. With one argument it reads from `default.resource`. When the key is missing in the named resource, the value from `default.resource` is used and cached. The result is an empty string when the key exists nowhere. Parsed files are cached in `F.resources`. Example: Read values ```js var title = RESOURCE('sk', 'title'); var fallback = RESOURCE('title'); // default.resource ``` ### TRANSLATE([language], text) Type: `method` Translates one text the same way as `@(Text)` in views. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `language` | `String` | no | `default` | The resource name. | | `text` | `String` | yes | | The text in the default language, or `#key`. | Returns: `String` The translation or the original text. The key is `T` plus the hash of the text. When no translation exists, the original text is returned. A text that starts with `#` (not followed by a space) is read as a resource key, so `TRANSLATE('sk', '#title')` is `RESOURCE('sk', 'title')`. Without a language, `default.resource` is used. Example: Translate a message ```js var msg = TRANSLATE($.language, 'Thank you for your order'); ``` ### TRANSLATOR(language, text) Type: `method` Replaces every `@(...)` in a string with its translation. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `language` | `String` | yes | | The resource name. | | `text` | `String` | yes | | A string with `@(...)` commands. | Returns: `String` The translated string. Uses the same rules as views: `@(Text)` is translated by hash, `@(#key)` is read from the resource, quotes are escaped when the command is inside quotes. A text with `@{notranslate}` is returned without that command and without translation. When the resource of the language does not exist, the texts stay. Example: Translate a template ```js var html = TRANSLATOR('sk', '<h1>@(Products)</h1><p>@(#welcome)</p>'); ``` ### LOADRESOURCE(name, value) Type: `method` Writes a resource into the temporary directory and clears its cache. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `name` | `String` | yes | | The resource name, or a URL that returns several resources. | | `value` | `String|Object|Array` | no | | The content, an object, an array, or an `http(s)` URL. | `value` can be the content of a resource file (a string), an object `{ key: value }`, or an array of items with `id`/`key`/`code`/`language` and `value`/`name`/`text`/`body`. The result is saved as `tmp/{name}.resource` and joined with `resources/{name}.resource`, which wins for duplicate keys. `LOADRESOURCE(name, url)` downloads one resource; `LOADRESOURCE(url)` downloads an object or an array of several resources. Download errors are thrown. Example: Load from an object ```js LOADRESOURCE('sk', { title: 'Moja stránka', welcome: 'Vitajte' }); ``` Example: Download from a URL ```js LOADRESOURCE('sk', 'https://example.com/translations/sk.json'); LOADRESOURCE('https://example.com/translations/'); ``` ### LOCALIZE(fn) Type: `method` Sets the delegate that returns the language of each request. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `fn` | `Function` | yes | | `function(req, res, isStaticFile)` that returns a language string. | The function is stored as `DEF.onLocale`. It receives `req`, `res` and, for static files, `true`. It must return the language, which is saved to `req.$language`. For WebSocket connections it gets only `req`. Example: Language from the query or the header ```js LOCALIZE(function(req, res) { var lang = req.query.language || (req.headers['accept-language'] || '').substring(0, 2); return lang === 'sk' ? 'sk' : 'en'; }); ``` ### LOCALIZE(url, [flags], [minify]) Type: `method` Serves static files of a URL translated into the language of the request. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `url` | `String` | yes | | The URL, for example `/docs/*.md`. | | `flags` | `Array` | no | `[]` | File extensions (`.md`) and `nocompress`. | | `minify` | `Boolean` | no | `true` | Minifies HTML. | Creates a file route that reads the file, replaces `@(...)` and returns it. Without an extension in the URL it handles `.html`, `.htm`, `.md` and `.txt`. HTML is minified unless `minify` is `false` or `flags` contains `nocompress`. In release mode the result is cached for each language. A URL that starts with `#` is taken from the sitemap. Example: Localized Markdown ```js LOCALIZE('/docs/*.md'); LOCALIZE('/templates/*.html', ['nocompress']); ``` ### DEF.onLocale = function(req, res, isStaticFile) Type: `delegate` The delegate that returns the language of a request; `null` by default. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `req` | `Request` | yes | | The request. | | `res` | `Response` | no | | The response. | | `isStaticFile` | `Boolean` | no | | `true` for static files. | Returns: `String` The language, saved to `req.$language`. Set it with `LOCALIZE(fn)` or directly. It is called at the start of a static file request, after authorization for routes (so `req.user` is known), and when a WebSocket connects (with `req` only). `req.localize()` calls it again. Example: Language of the user ```js DEF.onLocale = function(req) { return req.user ? req.user.language : 'en'; }; ``` ### AUTH({ locale: function(user, req) }) Type: `config` · Since: `0.0.57` Option of the built-in session `AUTH()` that sets the language from the user. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `user` | `Object` | yes | | The user data from `onread`, or `null`. | | `req` | `Request` | yes | | The request. | Returns: `String` The language. It is called after the session is read, with the user data (or `null` when the session is missing or invalid) and the request. The returned value is saved to `req.$language`. Example: Language from the user ```js AUTH({ secret: 'my-secret', cookie: 'session', onread: function(meta, next) { NOSQL('users').one().id(meta.userid).callback(next); }, locale: function(user, req) { return user ? user.language : 'en'; } }); ``` ### controller.language Type: `property` The language of the controller; views and e-mails use it. Returns: `String` It is set from `req.$language` when the controller is created, so it is `undefined` without a localization delegate. You can assign another value before you render a view. Views are compiled and cached for each language. `client.language` in WebSocket controllers works the same way. Example: Language from the URL ```js exports.install = function() { ROUTE('GET /{lang}/', home); }; function home(lang) { this.language = lang; this.view('index'); } ``` ### req.language Type: `property` The language of the request. Returns: `String` Returns `req.$language`. When it is not set, it returns the first language of the `Accept-Language` header in lower case (for example `en-us`) and keeps it. It can be assigned. Example: Read the language ```js function detail() { var lang = this.req.language; this.plain(lang); } ``` ### req.localize() Type: `method` Runs `DEF.onLocale` again and returns the new language. Returns: `String` The language. Useful when something that the delegate reads (a cookie, the user) has changed during the request. Example: Refresh the language ```js function setlanguage() { this.req.user.language = this.query.lang; this.language = this.req.localize(); this.redirect('/'); } ``` ### $.language Type: `property` The language of the request in schemas, operations, middleware and `AUTH()`. Returns: `String` In schemas and operations it is `controller.language` (an empty string without a controller). In middleware it is `req.$language`. In an `AUTH()` delegate it is `req.language`, which falls back to `Accept-Language`, because the localization delegate runs after authorization. Example: Use it in a schema ```js schema.addWorkflow('send', function($) { var subject = TRANSLATE($.language, 'Your message was received'); $.success(subject); }); ``` ### @(Text) Type: `method` Marks text for translation in views and static HTML files. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `Text` | `String` | yes | | The text in the default language, or `#key`. | The text is replaced with the translation from the resource of the current language when the view is compiled. The key is `T` plus a hash of the text; when there is no translation, or the resource file of the language does not exist, the original text stays. `@(#key)` reads a key from the resource directly. Inside quotes, quotes in the translation are escaped. Example: Translated text ```html <h1>@(Products)</h1> <button title="@(Add to cart)">@(Add)</button> <p>@(#welcome)</p> ``` ### @{resource([name], key)} Type: `method` Prints a value from a resource file in a view, HTML-encoded. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `name` | `String` | no | `default` | The resource name. | | `key` | `String` | yes | | The key. | Returns: `String` The value, or an empty string. It calls `RESOURCE()`, so without `name` it reads `default.resource`. Use the view variable `language` to read the resource of the current language. `@{!resource(...)}` prints the value raw. Example: Resource values ```html <p>@{resource('welcome')}</p> <p>@{resource(language, 'welcome')}</p> ``` ### @{language} Type: `property` The language of the request inside a view. The view variable `language` holds `req.$language`, or an empty string. Use it in expressions, for example in `@{resource(language, 'key')}` or in the `lang` attribute. Example: The lang attribute ```html <html lang="@{language}"> ``` ### @{notranslate} Type: `method` Turns off translation of `@(...)` in a view. Put it anywhere in the view or in a string passed to `TRANSLATOR()`. It is removed from the output and the `@(...)` commands stay untouched. `@{nolocalize}` does the same. Example: A view without translation ```html @{notranslate} <p>@(This text stays as it is)</p> ``` ### MAIL(address, subject, view, [model], [language], [callback]) Type: `method` Sends an e-mail rendered from a view, in a given language. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `address` | `String|Array` | yes | | The recipient or recipients. | | `subject` | `String` | yes | | The subject. | | `view` | `String` | yes | | The view name. | | `model` | `Object` | no | | The model of the view. | | `language` | `String` | no | | The language. | | `callback` | `Function` | no | | `function(err)`. | Returns: `MailMessage` The message. With a language, the subject is translated (with `TRANSLATOR()` when it contains `@(`, otherwise with `TRANSLATE()`) and the view is rendered with that language. `language` and `callback` can be swapped. Example: A translated e-mail ```js MAIL(user.email, '@(Order confirmation)', 'mails/order', order, user.language, function(err) { err && console.log(err); }); ``` ### HTMLMAIL(address, subject, body, [language], [callback]) Type: `method` · Since: `0.0.37` Sends a raw HTML e-mail, translated into a given language. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `address` | `String|Array` | yes | | The recipient or recipients. | | `subject` | `String` | yes | | The subject. | | `body` | `String` | yes | | The HTML body. | | `language` | `String` | no | | The language. | | `callback` | `Function` | no | | `function(err)`. | Returns: `MailMessage` The message. With a language, the subject is translated and every `@(...)` in the body is replaced. `language` and `callback` can be swapped. Example: A translated HTML e-mail ```js HTMLMAIL(user.email, '@(Welcome)', '<p>@(Thank you for signing up.)</p>', 'sk'); ``` ### VIEW(name, [model], [layout], [repository], [language]) Type: `method` Renders a view to a string, optionally in a given language. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `name` | `String` | yes | | The view name. | | `model` | `Object` | no | | The model. | | `layout` | `String` | no | | The layout. | | `repository` | `Object` | no | | The repository. | | `language` | `String` | no | | The language. | Returns: `String` The HTML. The language is used for `@(...)` in the view. Without it the view is translated with `default.resource`. Example: Render in Slovak ```js var html = VIEW('mails/invoice', invoice, '', null, 'sk'); ``` ### date.format([format], [resource]) Type: `method` Formats a date; month and day names are read from a resource. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `format` | `String` | no | | The format, for example `dddd d. MMMM yyyy`. | | `resource` | `String` | no | `default` | The resource with names of months and days. | Returns: `String` The formatted date. `MMMM` and `MMM` read the English month name (`January`…`December`) as a key from the resource, `dddd` and `ddd` the day name (`Sunday`…`Saturday`). When a key is missing, the English name is used. Example: Localized names ```js // sk.resource: January : január, Monday : pondelok var text = NOW.format('dddd d. MMMM yyyy', 'sk'); ``` ### builder.resource(name, [prefix]) Type: `method` Sets the resource and the key prefix for error messages. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `name` | `String` | yes | | The resource name. | | `prefix` | `String` | no | `''` | A prefix for keys. | Returns: `ErrorBuilder` The builder. Errors pushed with a key (`builder.push('email')`) are read as `prefix + name` from the resource. The builder then keeps this resource and is not switched to the language of the request. Example: Errors from a resource ```js var builder = new ErrorBuilder(); builder.resource('sk', 'error-'); builder.push('email'); // reads error-email from sk.resource ``` ### builder.setResource(name) Type: `method` Sets only the resource for error messages. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `name` | `String` | yes | | The resource name. | Returns: `ErrorBuilder` The builder. The framework calls it with the language of the request before it sends errors, unless you have set a resource yourself. Example: Fixed language ```js var builder = new ErrorBuilder(); builder.setResource('de'); ``` ### builder.setPrefix(prefix) Type: `method` Sets the prefix of keys for error messages. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `prefix` | `String` | yes | | The prefix. | Returns: `ErrorBuilder` The builder. An error pushed with a name is read as `prefix + name` from the resource. Example: A prefix ```js var builder = new ErrorBuilder(); builder.setPrefix('error-'); builder.push('name'); ``` ### schema.setResource(name) Type: `method` Reads the errors of a schema from a fixed resource. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `name` | `String` | yes | | The resource name. | Returns: `SchemaBuilderEntity` The schema. Without it, errors of the schema are translated with the language of the request. Example: Errors from errors.resource ```js NEWSCHEMA('Contact', function(schema) { schema.setResource('errors'); schema.define('email', 'Email', true); }); ``` ### schema.setPrefix(prefix) Type: `method` Sets a prefix for resource keys of the schema errors. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `prefix` | `String` | yes | | The prefix. | Returns: `SchemaBuilderEntity` The schema. A required or invalid field `email` is read as `prefix + 'email'` from the resource. Example: Prefixed keys ```js NEWSCHEMA('Contact', function(schema) { schema.setPrefix('contact-'); schema.define('email', 'Email', true); // key: contact-email }); ``` ### F.register(path) Type: `method` Adds a `.resource` file from another location to a resource. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `path` | `String` | yes | | The path to a `.resource` file. | The file name gives the resource name, so `/modules/shop/sk.resource` is added to the `sk` resource. A path that starts with `@` is in a package, `=` in a theme. Registered files are read before `tmp/` and `resources/`, so the application can override their keys. Other extensions throw an error. Example: Resources of a module ```js F.register(PATH.root('modules/shop/sk.resource')); ``` ### F.resources Type: `property` The cache of parsed resources, by name. Returns: `Object` Each value is an object of keys and values. It is cleared every `default_interval_clear_resources` minutes, and for one name when `LOADRESOURCE()` or `F.register()` changes it. Example: Clear the cache ```js F.resources = {}; ``` ### PATH.resources([filename]) Type: `method` Returns the path of the resources directory or of a file in it. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `filename` | `String` | no | | A file name. | Returns: `String` The absolute path. Example: Path to a resource ```js var filename = PATH.resources('sk.resource'); ``` ### directory_resources : /resources/ Type: `config` The directory with resource files. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `directory_resources` | `String` | no | `/resources/` | A path relative to the root of the application. | Example: Another directory ```text directory_resources : /translations/ ``` ### allow_localize : true Type: `config` Translates `.html` and `.htm` files from `public/` with `@(...)`. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `allow_localize` | `Boolean` | no | `true` | Enables translation of static HTML files. | The translated files are cached for each language in release mode. Example: Turn it off ```text allow_localize : false ``` ### default_interval_clear_resources : 20 Type: `config` How often, in minutes, the cache of resources is cleared. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `default_interval_clear_resources` | `Number` | no | `20` | Minutes. | After clearing, resource files are read again on the next use, so changes appear without a restart. The `clear` event is emitted with `resources`. Example: Every five minutes ```text default_interval_clear_resources : 5 ``` ### default_errorbuilder_resource_name : name Type: `config` The default resource of every new `ErrorBuilder`. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `default_errorbuilder_resource_name` | `String` | no | | The resource name. | Not set by default. The framework still switches error builders to the language of the request before it sends them. Example: Errors from errors.resource ```text default_errorbuilder_resource_name : errors ``` ### default_errorbuilder_resource_prefix : prefix Type: `config` The default key prefix of every new `ErrorBuilder`. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `default_errorbuilder_resource_prefix` | `String` | no | `''` | The prefix. | Not set by default (an empty prefix). Example: Prefixed keys ```text default_errorbuilder_resource_prefix : error- ``` ### total4 translate [path | "text" | filename] Type: `method` Creates `translate.resource` with every text to translate. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `argument` | `String` | no | | A directory, a text file, or a text. | Without an argument it scans the current directory (without `node_modules`, `tmp` and `.git`): `@(Text)` in `.html`, `.js` and sitemap files, and in `.js` also keys of `$.invalid('key')` and `.error('key')`. Texts are grouped under comments with the file names. `@(#key)` is skipped. With a text file, each line becomes one entry. With a text that is not a file, it prints its key. Example: Create the file ```bash total4 translate total4 translate "Add to cart" ``` ### total4 translatecsv Type: `method` Writes the texts to translate into `translate.csv`. The CSV has the columns `Hash;Text;Translation`. Fill the last column, then convert it back with `total4 csv`. Example: Export to CSV ```bash total4 translatecsv ``` ### total4 csv <filename> Type: `method` Creates a resource file from a CSV file. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `filename` | `String` | yes | | The CSV file. | Reads a `;`-separated CSV, skips the first row, and uses the first column as the key and the second as the value. The output has the same name with `.resource`. Example: Import from CSV ```bash total4 csv sk.csv ``` ### total4 diff <source> <target> Type: `method` Lists keys to add to and to remove from a resource. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `source` | `String` | yes | | The new file, for example `translate.resource`. | | `target` | `String` | yes | | The translated file. | Compares the keys of both files and writes `<target>-diff.txt` with the keys of `source` that the target does not have and the keys of the target that `source` does not have. Example: Find new texts ```bash total4 diff translate.resource resources/sk.resource ``` ### total4 merge <source> <target> Type: `method` Copies values from one resource into another. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `source` | `String` | yes | | The file with new values. | | `target` | `String` | yes | | The file to update. | Writes `<target>-merged.txt`: the lines of the target, with the value of each key replaced by the value from `source` when it has one. Example: Merge translations ```bash total4 merge translated.resource resources/sk.resource ``` ### total4 clean <source> Type: `method` Aligns the keys and values of a resource file. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `source` | `String` | yes | | The resource file. | Writes `<source>-cleaned.txt` with all keys padded to the same width and ` : ` between key and value. Example: Clean a file ```bash total4 clean resources/sk.resource ``` --- title: HTTP requests project: Total.js V4 version: 0.0.99 section: reference language: en license: MIT url: https://totaljs.es/docs/total-js-v4/0-0-99/reference/http-requests/ updated: 2026-11-16T15:57:56.811Z --- # HTTP requests > RESTBuilder, REQUEST() and DOWNLOAD(): the clients for other HTTP services. The global functions and the `RESTBuilder` methods that send requests to other services. The guide [HTTP requests](../../guides/http-requests/) explains how to use them with examples; this page is the exact reference. ## API ### REQUEST(options, [callback]) Type: `method` Sends an HTTP request and returns the raw response. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `options` | `Object` | yes | | The options of the request (see the table). | | `callback` | `Function` | no | | `function(err, response)`. Without it the method returns a promise. | Returns: `Promise|undefined` A promise of the response when you do not pass a callback. The low-level HTTP client of the framework; `RESTBuilder` and `DOWNLOAD()` use it. Without a callback it returns a promise of the response. **Options** | Option | Type | Description | | --- | --- | --- | | `url` | String | The address (`http://` or `https://`) | | `method` | String | The HTTP method, default `GET` | | `headers` | Object | Request headers | | `query` | Object/String | Appended to the URL as a query string | | `body` | String/Buffer | The body; with `files`, an object of form fields | | `type` | String | Sets `Content-Type`: `json`, `urlencoded`, `xml`, `plain`, `html` or `raw` (`application/octet-stream`) | | `files` | Array | Files to upload as `multipart/form-data`: `{ name, filename, buffer }`, `{ name, filename, path }` or `{ name, filename, url }` | | `cookies` | Object | Cookies to send, as `{ name: value }` | | `cook` | Boolean | Collects cookies of the responses (also from redirects) into `options.cookies` | | `timeout` | Number | Milliseconds; default `CONF.default_restbuilder_timeout` (`10000`); `0` turns it off | | `encoding` | String | Encoding of a text response, default `utf8`; `binary` returns a `Buffer` | | `custom` | Boolean | Returns `response.stream` instead of reading the body | | `noredirect` | Boolean | Does not follow `301` and `302` redirects | | `keepalive` | Boolean | Reuses connections (not with a proxy) | | `proxy` | String | A proxy server, for example `http://user:pass@host:8080` | | `resolve` / `dnscache` | Boolean | Resolves the host name once and caches the address | | `xhr` | Boolean | Adds `X-Requested-With: XMLHttpRequest` | | `unixsocket` | Object | `{ socket, path }` sends the request to a Unix socket instead of `url` | | `key`, `cert`, `dhparam` | Buffer | TLS client certificate | | `insecure` | Boolean | Accepts invalid TLS certificates | | `compress` | String | Compresses the body with `gzip` or `deflate` and sets `Content-Encoding` | | `encrypt` | String | Encrypts the body with this key (header `X-Encryption`) and decrypts a text response | | `onprogress` | Function | `fn(percentage)` while the body downloads | | `ondata` | Function | `fn(chunk, percentage)` for every chunk | | `callback` | Function | The same as the `callback` argument | **Response**: `status`, `headers`, `body`, `host`, `origin` (the resolved addresses, with `resolve`) and `cookies`; with `custom: true`, `stream` instead of `body`. Errors: `Invalid hostname`, the text of status `408` after a timeout, `Too many redirects` after four redirects, or a network error (then `status` is `0`). Example: GET with a callback ```js REQUEST({ url: 'https://api.example.com/status/', timeout: 5000 }, function(err, response) { if (err) { console.log(err); return; } console.log(response.status, response.body); }); ``` Example: POST JSON with a promise ```js var response = await REQUEST({ url: 'https://api.example.com/items/', method: 'POST', type: 'json', body: JSON.stringify({ name: 'Item' }) }); var data = response.body.parseJSON(); ``` Example: Read a stream ```js REQUEST({ url: 'https://www.example.com/big.csv', custom: true }, function(err, response) { if (!err) response.stream.pipe(Fs.createWriteStream(PATH.temp('big.csv'))); }); ``` ### DOWNLOAD(url, filename, [callback], [timeout]) Type: `method` Downloads a URL into a file. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `url` | `String|Object` | yes | | An absolute or relative URL, or `{ socket, path }`. | | `filename` | `String` | yes | | The target file. | | `callback` | `Function` | no | | `function(err, response)`. | | `timeout` | `Number` | no | `CONF.default_restbuilder_timeout` | Milliseconds. | Returns: `Promise|undefined` A promise of the response when you do not pass a callback. Sends a `GET` request and writes the response body into `filename`. The callback runs when the file is written. Without a callback the method returns a promise. A relative URL (for example `/sitemap.xml`) is requested from your own application; before the application is loaded the call waits. An object `{ socket, path }` instead of the URL sends the request to a Unix socket. The response has `status`, `headers` and `filename`. The status code is not checked: the file is written for `404` too. Example: Save an image ```js DOWNLOAD('https://www.example.com/logo.png', PATH.public('img/logo.png'), function(err, response) { if (err || response.status !== 200) console.log('Download failed'); }); ``` Example: With await ```js var response = await DOWNLOAD('https://www.example.com/data.json', PATH.databases('data.json'), null, 30000); ``` ### RESTBuilder.GET(url, [data]) Type: `method` Creates a builder for a `GET` request. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `url` | `String` | yes | | The address. | | `data` | `Object` | no | | Query string arguments. | Returns: `RESTBuilder` A new builder. `data` becomes the query string of the URL. Send the request with `callback()`, `exec()`, `promise()` or `stream()`. Example: Load a list ```js RESTBuilder.GET('https://api.example.com/products/', { page: 2, limit: 50 }).callback(function(err, response) { // GET https://api.example.com/products/?page=2&limit=50 console.log(response); }); ``` ### RESTBuilder.POST(url, [data]) Type: `method` Creates a builder for a `POST` request. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `url` | `String` | yes | | The address. | | `data` | `Object` | no | | The body, sent as JSON. | Returns: `RESTBuilder` A new builder. The data is sent as JSON. Call `urlencoded()` or `xml()` to send another format. Example: POST request ```js RESTBuilder.POST('https://api.example.com/products/', { name: 'Bike', price: 150 }).callback(function(err, response, output) { console.log(output.status, response); }); ``` ### RESTBuilder.PUT(url, [data]) Type: `method` Creates a builder for a `PUT` request. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `url` | `String` | yes | | The address. | | `data` | `Object` | no | | The body, sent as JSON. | Returns: `RESTBuilder` A new builder. The data is sent as JSON. Example: PUT request ```js RESTBuilder.PUT('https://api.example.com/products/P01/', { name: 'Bike', price: 150 }).callback(function(err, response, output) { console.log(output.status, response); }); ``` ### RESTBuilder.PATCH(url, [data]) Type: `method` Creates a builder for a `PATCH` request. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `url` | `String` | yes | | The address. | | `data` | `Object` | no | | The body, sent as JSON. | Returns: `RESTBuilder` A new builder. The data is sent as JSON. Example: PATCH request ```js RESTBuilder.PATCH('https://api.example.com/products/P01/', { name: 'Bike', price: 150 }).callback(function(err, response, output) { console.log(output.status, response); }); ``` ### RESTBuilder.DELETE(url, [data]) Type: `method` Creates a builder for a `DELETE` request. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `url` | `String` | yes | | The address. | | `data` | `Object` | no | | The body, sent as JSON. | Returns: `RESTBuilder` A new builder. The data, if any, is sent as JSON. Example: DELETE request ```js RESTBuilder.DELETE('https://api.example.com/products/P01/', { name: 'Bike', price: 150 }).callback(function(err, response, output) { console.log(output.status, response); }); ``` ### RESTBuilder.HEAD(url) Type: `method` Creates a builder for a `HEAD` request. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `url` | `String` | yes | | The address. | Returns: `RESTBuilder` A new builder. Read the answer from `output.status` and `output.headers` in the callback. Example: Does the file exist? ```js RESTBuilder.HEAD('https://cdn.example.com/files/report.pdf').callback(function(err, response, output) { console.log(output.status === 200, output.headers['content-length']); }); ``` ### RESTBuilder.API(url, name, [data]) Type: `method` Calls an operation of a Total.js API endpoint. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `url` | `String` | yes | | The address of the API endpoint. | | `name` | `String` | yes | | The name of the operation, with its parameters (for example `products_read/P01`). | | `data` | `Object` | no | | The data of the operation. | Returns: `RESTBuilder` A new builder. Sends a `POST` with the JSON body `{ schema: name, data: data }`, the format that Total.js API routes read. Example: Call an operation ```js RESTBuilder.API('https://app.example.com/admin/', 'products_save', { name: 'Bike' }).callback(function(err, response) { console.log(err, response); }); ``` ### RESTBuilder.make(fn) Type: `method` Creates an empty builder and passes it to a function. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `fn` | `Function` | yes | | `function(builder)`. | Returns: `RESTBuilder` The new builder. `fn(builder)` sets the URL, method and everything else. `RESTBuilder.url(url)` creates a builder with a URL only, and the instance method `builder.make(fn)` calls `fn` with the builder as `this` and as the argument. Example: Build the request ```js RESTBuilder.make(function(builder) { builder.url('https://api.example.com/orders/'); builder.post({ product: 'P01' }); builder.header('X-Token', CONF.token); builder.callback(console.log); }); ``` ### RESTBuilder.upgrade(fn) Type: `method` Changes every builder before it sends its request. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `fn` | `Function` | yes | | `function(builder)`. | Returns: `undefined` `fn(builder)` runs in `exec()` for every builder of the application, after the body is prepared and before the request is sent. Register it once, in a definition file. Example: Add a header to all requests ```js // definitions/restbuilder.js RESTBuilder.upgrade(function(builder) { builder.header('X-App', 'eshop'); }); ``` ### RESTBuilder.addTransform(name, fn, [isDefault]) Type: `method` Registers a function that changes parsed responses. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `name` | `String` | yes | | The name of the transformation. | | `fn` | `Function` | yes | | `function(value, output)` returning the new value. | | `isDefault` | `Boolean` | no | `false` | Use it for all builders. | Returns: `undefined` `fn(value, output)` runs with `this` as the builder and returns the new value. A builder uses it after `setTransform(name)`; with `isDefault`, every new builder uses it. `RESTBuilder.setDefaultTransform(name)` changes the default and `RESTBuilder.setDefaultTransform()` removes it. The transformation does not run when the response is a Total.js error array that becomes `err`. Example: Unwrap a data envelope ```js RESTBuilder.addTransform('envelope', function(value, output) { return value && value.data ? value.data : value; }); RESTBuilder.GET('https://api.example.com/users/').setTransform('envelope').callback(function(err, users) { console.log(users); }); ``` ### builder.url([url]) Type: `method` Reads or sets the URL. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `url` | `String` | no | | The address. | Returns: `RESTBuilder|String` The builder, or the URL when called without an argument. Without an argument it returns the current URL. Example: Set the URL ```js var builder = RESTBuilder.GET('https://api.example.com/'); builder.url('https://api.example.com/v2/products/'); ``` ### builder.method(method, [data]) Type: `method` Sets the HTTP method. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `method` | `String` | yes | | For example `POST` or `put`. | | `data` | `Object` | no | | The body, sent as JSON. | Returns: `RESTBuilder` The builder, for chaining. Lower-case names are converted to upper case. `data` is sent as JSON. Example: Choose the method ```js RESTBuilder.make(function(builder) { builder.url('https://api.example.com/items/P01/'); builder.method('PUT', { price: 20 }); builder.callback(console.log); }); ``` ### builder.get([data]) Type: `method` Switches to `GET` and sets the query string. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `data` | `Object` | no | | Query string arguments. | Returns: `RESTBuilder` The builder, for chaining. `data` replaces the query. Alias `builder.GET()`. Example: Query ```js RESTBuilder.make(function(builder) { builder.url('https://api.example.com/search/'); builder.get({ q: 'bike' }); builder.callback(console.log); }); ``` ### builder.post([data]) Type: `method` Switches to `POST` and sets the body. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `data` | `Object|String` | no | | The body. | Returns: `RESTBuilder` The builder, for chaining. The body keeps the type set earlier (`urlencoded()`, `xml()`), otherwise it is JSON. Alias `builder.POST()`. Example: POST ```js RESTBuilder.make(function(builder) { builder.url('https://api.example.com/orders/'); builder.post({ product: 'P01', count: 1 }); builder.callback(console.log); }); ``` ### builder.put([data]) Type: `method` Switches to `PUT` and sets the body. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `data` | `Object|String` | no | | The body. | Returns: `RESTBuilder` The builder, for chaining. `builder.patch([data])` and `builder.delete([data])` work the same with `PATCH` and `DELETE`; `builder.head()` switches to `HEAD`. Each has an upper-case alias (`PUT()`, `PATCH()`, `DELETE()`, `HEAD()`). Example: PUT and DELETE ```js RESTBuilder.make(function(builder) { builder.url('https://api.example.com/items/P01/'); builder.put({ price: 20 }); builder.callback(console.log); }); RESTBuilder.make(function(builder) { builder.url('https://api.example.com/items/P02/'); builder.delete(); builder.callback(console.log); }); ``` ### builder.header(name, value) Type: `method` Sets a request header. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `name` | `String` | yes | | The name of the header. | | `value` | `String` | yes | | The value. | Returns: `RESTBuilder` The builder, for chaining. For a CSRF token you can also use `builder.csrf(value)` (`X-Csrf-Token`), and `builder.origin(value)` for `Origin`. Example: Token header ```js RESTBuilder.GET('https://api.example.com/me/').header('X-Token', CONF.token).callback(console.log); ``` ### builder.type(value) Type: `method` Sets the `Content-Type` header. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `value` | `String` | yes | | The content type. | Returns: `RESTBuilder` The builder, for chaining. It overrides the type that `json()`, `xml()` and the other body methods set. Example: Custom type ```js RESTBuilder.POST('https://api.example.com/events/').raw(JSON.stringify(data), 'json').type('application/vnd.api+json').callback(console.log); ``` ### builder.accept(type) Type: `method` Sets the `Accept` header. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `type` | `String` | yes | | An extension or a content type. | Returns: `RESTBuilder` The builder, for chaining. A short value is an extension (`json`, `xml`) and is converted to its content type; a longer value is used as it is. Example: Ask for XML ```js RESTBuilder.GET('https://api.example.com/feed/').accept('xml').callback(console.log); ``` ### 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 builder, for chaining. With a password it creates Basic authentication. Without it, `user` is the whole value, for example `Bearer TOKEN`. Example: Basic and Bearer ```js RESTBuilder.GET('https://api.example.com/').auth('admin', 'secret').callback(console.log); RESTBuilder.GET('https://api.example.com/').auth('Bearer ' + CONF.token).callback(console.log); ``` ### builder.cookie(name, value) Type: `method` Adds a cookie to the request. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `name` | `String` | yes | | The name. | | `value` | `String` | yes | | The value. | Returns: `RESTBuilder` The builder, for chaining. `builder.cookies(obj)` replaces all cookies with an object `{ name: value }`. Example: Send a session cookie ```js RESTBuilder.GET('https://www.example.com/account/').cookie('session', token).callback(console.log); ``` ### builder.cook([enable]) Type: `method` Collects the cookies of the responses. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `enable` | `Boolean` | no | `true` | `false` turns it off. | Returns: `RESTBuilder` The builder, for chaining. Cookies set by the server, also during redirects, are stored in the object of `cookies()` and returned by `output.cookie(name)`. Pass the same object to the next builder to keep a session. Example: Keep a session ```js var jar = {}; RESTBuilder.POST('https://www.example.com/login/', { name: 'user', password: 'pass' }).cookies(jar).cook().callback(function(err, response, output) { RESTBuilder.GET('https://www.example.com/account/').cookies(jar).callback(console.log); }); ``` ### builder.json([data]) Type: `method` Sends the body as JSON. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `data` | `Object|String` | no | | The body. | Returns: `RESTBuilder` The builder, for chaining. A `GET` becomes a `POST`. Example: JSON body ```js RESTBuilder.make(function(builder) { builder.url('https://api.example.com/items/'); builder.json({ name: 'Item' }); builder.callback(console.log); }); ``` ### builder.urlencoded([data]) Type: `method` Sends the body as `application/x-www-form-urlencoded`. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `data` | `Object|String` | no | | The body. | Returns: `RESTBuilder` The builder, for chaining. A `GET` becomes a `POST`. An object is encoded as a form. Example: Form body ```js RESTBuilder.POST('https://www.example.com/contact/').urlencoded({ email: 'info@example.com', message: 'Hello' }).callback(console.log); ``` ### builder.xml([data], [replace]) Type: `method` Sends the body as XML. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `data` | `String` | no | | The XML. | | `replace` | `Boolean` | no | `false` | Passed to `parseXML()` for the response. | Returns: `RESTBuilder` The builder, for chaining. Sets `Content-Type: text/xml`; a `GET` becomes a `POST`. Send the XML as a string. An XML response is parsed with `String.parseXML()`; `replace` is its argument. Example: SOAP-like call ```js RESTBuilder.make(function(builder) { builder.url('https://service.example.com/rates/'); builder.xml('<request><currency>EUR</currency></request>'); builder.callback(console.log); }); ``` ### builder.plain([value]) Type: `method` Sends a text body and returns the response as text. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `value` | `String` | no | | The body. | Returns: `RESTBuilder` The builder, for chaining. Sets `Content-Type: text/plain`. The response is not parsed: `response` is the raw body. Example: Read text ```js RESTBuilder.GET('https://www.example.com/robots.txt').plain().callback(function(err, text) { console.log(text); }); ``` ### builder.raw(value, type) Type: `method` Sets the body and its type. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `value` | `Object|String|Buffer` | yes | | The body. | | `type` | `String` | yes | | The type of the body. | Returns: `RESTBuilder` The builder, for chaining. `type` is `json`, `urlencoded`, `xml`, `plain`, `html` or `raw` (`application/octet-stream`). An object is serialized when the request is sent, except for type `raw`: send a string or a `Buffer` there. Example: Binary body ```js RESTBuilder.POST('https://api.example.com/blob/').raw(buffer, 'raw').callback(console.log); ``` ### builder.set(name, [value]) Type: `method` Sets one field of the body. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `name` | `String|Object` | yes | | The field, or an object of fields. | | `value` | `Object` | no | | The value. | Returns: `RESTBuilder` The builder, for chaining. `name` can be an object with several fields. `builder.rem(name)` removes a field. With `file()`, the fields are sent as form fields. Example: Fields ```js RESTBuilder.POST('https://api.example.com/items/').set('name', 'Bike').set({ price: 150, stock: 3 }).callback(console.log); ``` ### builder.file(name, filename, [source]) Type: `method` Adds a file to upload. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `name` | `String` | yes | | The name of the form field. | | `filename` | `String` | yes | | The file name. | | `source` | `Buffer|String` | no | | The content, a path or a URL. | Returns: `RESTBuilder` The builder, for chaining. The request becomes `multipart/form-data`, and a `GET` becomes a `POST`. `source` is a `Buffer`, a path or a URL; a URL is downloaded and forwarded. Without `source`, `filename` is read as a path and only its name is sent. The content type comes from the extension of `filename`. Example: Upload two files ```js RESTBuilder.POST('https://api.example.com/upload/') .file('photo', 'photo.jpg', PATH.public('img/photo.jpg')) .file('data', 'data.json', Buffer.from(JSON.stringify(data))) .callback(console.log); ``` ### builder.timeout(ms) Type: `method` Sets the timeout. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `ms` | `Number` | yes | `10000` | Milliseconds. | Returns: `RESTBuilder` The builder, for chaining. The default of a builder is `10000`. After the timeout `err` is the text of status `408`. Example: Short timeout ```js RESTBuilder.GET('https://api.example.com/health/').timeout(2000).callback(console.log); ``` ### builder.keepalive() Type: `method` Reuses connections. Returns: `RESTBuilder` The builder, for chaining. The request uses a shared keep-alive agent. It has no effect with a proxy. Example: Many calls to one host ```js RESTBuilder.GET('https://api.example.com/items/').keepalive().callback(console.log); ``` ### builder.proxy(url) Type: `method` Sends the request through a proxy server. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `url` | `String` | yes | | For example `http://user:password@proxy.example.com:8080`. | Returns: `RESTBuilder` The builder, for chaining. The URL can contain credentials. For all requests set `CONF.default_proxy`. Example: Proxy ```js RESTBuilder.GET('https://api.example.com/').proxy('http://proxy.example.com:3128').callback(console.log); ``` ### builder.cert(key, cert, [dhparam]) Type: `method` Sets a TLS client 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 builder, for chaining. Use it for services that require client certificates. `builder.insecure()` accepts invalid server certificates (for testing only). Example: Client certificate ```js RESTBuilder.GET('https://bank.example.com/api/') .cert(Fs.readFileSync(PATH.root('client.key')), Fs.readFileSync(PATH.root('client.crt'))) .callback(console.log); ``` ### builder.nodnscache() Type: `method` Turns off the DNS cache for this request. Returns: `RESTBuilder` The builder, for chaining. A builder resolves the host name once and keeps the address; this resolves it as usual. Local addresses are never cached. Example: Fresh DNS ```js RESTBuilder.GET('https://api.example.com/').nodnscache().callback(console.log); ``` ### builder.redirect(enable) Type: `method` Turns following of redirects on or off. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `enable` | `Boolean` | yes | | Follow redirects. | Returns: `RESTBuilder` The builder, for chaining. `redirect(false)` returns the `301` or `302` response itself. Redirects are followed by default. Example: Read the location ```js RESTBuilder.GET('https://short.example.com/abc').redirect(false).callback(function(err, response, output) { console.log(output.headers.location); }); ``` ### builder.unixsocket(socket, path) Type: `method` Sends the request to a Unix socket. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `socket` | `String` | yes | | The path of the socket file. | | `path` | `String` | yes | | The path of the request. | Returns: `RESTBuilder` The builder, for chaining. A URL set earlier becomes the path. Example: Local service ```js RESTBuilder.make(function(builder) { builder.unixsocket('/var/run/app.sock', '/api/status/'); builder.callback(console.log); }); ``` ### builder.xhr() Type: `method` Adds `X-Requested-With: XMLHttpRequest`. Returns: `RESTBuilder` The builder, for chaining. Example: XHR ```js RESTBuilder.GET('https://www.example.com/api/').xhr().callback(console.log); ``` ### builder.referrer(value) Type: `method` Sets the `Referer` header. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `value` | `String` | yes | | The URL. | Returns: `RESTBuilder` The builder, for chaining. Alias `builder.referer()`. Example: Referer ```js RESTBuilder.GET('https://www.example.com/page/').referrer('https://www.example.com/').callback(console.log); ``` ### builder.encrypt([key]) Type: `method` Encrypts the body and decrypts the response. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `key` | `String` | no | `DEF.secret_encryption` | The key. | Returns: `RESTBuilder` The builder, for chaining. Uses the framework encryption with `key`, or `DEF.secret_encryption`, and adds `X-Encryption`. Both sides must use the same key. Example: Encrypted call ```js RESTBuilder.POST('https://node2.example.com/sync/', data).encrypt(CONF.sync_key).callback(console.log); ``` ### builder.cache(expire) Type: `method` Caches a successful response. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `expire` | `String` | yes | | For example `5 minutes`. | Returns: `RESTBuilder` The builder, for chaining. A response with status `200` is stored in `F.cache` for `expire`; the key is made from the URL and the body. `builder.nocache()` skips the cache for one call. Example: Cache rates ```js RESTBuilder.GET('https://api.example.com/rates/').cache('1 hour').callback(console.log); ``` ### builder.schema(name) Type: `method` Validates the response with a schema. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `name` | `String` | yes | | The name of the schema. | Returns: `RESTBuilder` The builder, for chaining. The callback gets the model created by the schema. Errors of the schema and a status code `400` or higher come back as `err`. The method throws when the schema does not exist. Example: Validate the response ```js NEWSCHEMA('Rate', function(schema) { schema.define('currency', 'String(3)', true); schema.define('value', Number, true); }); RESTBuilder.GET('https://api.example.com/rate/EUR/').schema('Rate').callback(function(err, rate) { console.log(err, rate); }); ``` ### builder.map(map) Type: `method` Keeps and converts selected fields of the response. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `map` | `String` | yes | | For example `id:number,name:string,dtcreated:date:created`. | Returns: `RESTBuilder` The builder, for chaining. `map` lists `field:type` pairs separated by commas. A third part renames the field: `source:type:target`. It works for an object and for an array of objects. Example: Map a list ```js RESTBuilder.GET('https://api.example.com/users/').map('id:number,name:string').callback(function(err, users) { console.log(users); }); ``` ### builder.convert(schema) Type: `method` Converts fields of the response. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `schema` | `String` | yes | | For example `price:number,date:date`. | Returns: `RESTBuilder` The builder, for chaining. The response goes through `CONVERT(value, schema)`. It does not run together with `schema()`. Example: Convert types ```js RESTBuilder.GET('https://api.example.com/order/1/').convert('total:number,created:date').callback(console.log); ``` ### builder.strict() Type: `method` Treats status codes `400` and higher as errors. Returns: `RESTBuilder` The builder, for chaining. Then `err` is the status code. Without it you must check `output.status` yourself. Example: Fail on 404 ```js RESTBuilder.GET('https://api.example.com/items/X/').strict().callback(function(err, response) { if (err === 404) console.log('Not found'); }); ``` ### builder.noparse() Type: `method` Returns the raw body without parsing. Returns: `RESTBuilder` The builder, for chaining. `response` is the body as text (or a `Buffer` for binary types). Example: Raw JSON ```js RESTBuilder.GET('https://api.example.com/export/').noparse().callback(function(err, body) { Fs.writeFile(PATH.temp('export.json'), body, NOOP); }); ``` ### builder.setTransform(name) Type: `method` Uses a registered transformation. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `name` | `String` | yes | | The name of the transformation. | Returns: `RESTBuilder` The builder, for chaining. See `RESTBuilder.addTransform()`. Example: Use a transformation ```js RESTBuilder.GET('https://api.example.com/users/').setTransform('envelope').callback(console.log); ``` ### builder.progress(fn) Type: `method` Reports the progress of the download. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `fn` | `Function` | yes | | `function(percentage)`. | Returns: `RESTBuilder` The builder, for chaining. `fn(percentage)` runs for every chunk. It needs the `Content-Length` header of the response; without it the percentage is `0`. Example: Progress ```js RESTBuilder.GET('https://www.example.com/large.json').progress(function(percentage) { console.log(percentage.floor(1) + '%'); }).callback(console.log); ``` ### builder.debug() Type: `method` Logs the request and the response. Returns: `RESTBuilder` The builder, for chaining. Prints the status, method, URL, error and raw body to the console. Example: Debug ```js RESTBuilder.GET('https://api.example.com/').debug().callback(console.log); ``` ### builder.callback([fn]) Type: `method` Sends the request. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `fn` | `Function|Object` | no | | `function(err, response, output)`, or `$`. | Returns: `RESTBuilder|Promise` The builder, or a promise without a function. With a function, `fn(err, response, output)` runs with the result. Without a function, or with `$` of a schema operation, the method returns a promise: with `$`, an error goes to `$.invalid()`. Example: Callback ```js RESTBuilder.GET('https://api.example.com/items/').callback(function(err, response, output) { console.log(err, response, output.status); }); ``` Example: Promise ```js var items = await RESTBuilder.GET('https://api.example.com/items/').callback(); ``` ### 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 builder, for chaining. `callback(err, response, output)` is the same as in `callback()`; `exec()` sends immediately, `callback()` on the next tick. Example: Exec ```js RESTBuilder.GET('https://api.example.com/ping/').exec(function(err, response) { console.log(response); }); ``` ### builder.promise([$]) Type: `method` Sends the request and returns a promise. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `$` | `Object` | no | | The options of an operation. | Returns: `Promise` A promise of the parsed response. The promise resolves with the parsed response. With `$` (the options of a schema operation), an error is passed to `$.invalid()` and the promise does not settle; without it the promise rejects. Example: In an operation ```js schema.action('sync', { name: 'Sync', action: async function($) { var items = await RESTBuilder.GET('https://api.example.com/items/').promise($); $.callback(items); } }); ``` ### builder.stream(callback) Type: `method` Sends the request and returns the response as a stream. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `callback` | `Function` | yes | | `function(err, response)`. | Returns: `RESTBuilder` The builder, for chaining. `callback(err, response)` receives `status`, `headers`, `origin` and `stream` (the incoming message). The body is not read or parsed. Example: Pipe to a file ```js RESTBuilder.GET('https://www.example.com/export.csv').stream(function(err, response) { if (!err) response.stream.pipe(Fs.createWriteStream(PATH.temp('export.csv'))); }); ``` ### output.cookie(name) Type: `method` Reads a cookie from the response. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `name` | `String` | yes | | The name of the cookie. | Returns: `String` The value. `output` is the third argument of the callback. The method reads the `Set-Cookie` headers, or the cookies collected by `cook()`, and returns the decoded value or an empty string. Example: Read a cookie ```js RESTBuilder.POST('https://www.example.com/login/', { name: 'user', password: 'pass' }).callback(function(err, response, output) { var session = output.cookie('session'); }); ``` --- title: OpenClient project: Total.js V4 version: 0.0.99 section: reference language: en license: MIT url: https://totaljs.es/docs/total-js-v4/0-0-99/reference/openclient/ updated: 2026-11-18T16:57:39.578Z --- # OpenClient > OPENCLIENT(): a WebSocket client for messages to other services. ## API ### OPENCLIENT(url, [id]) Type: `method` Opens a shared WebSocket client for request and response messages. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `url` | `String` | yes | | The address of the server (`ws://`, `wss://`, `http://` or `https://`). | | `id` | `String` | no | `GUID(10)` | The client identifier. | Returns: `Object` The client. Connects to `url` over WebSocket (`http` becomes `ws`, `https` becomes `wss`) and reconnects automatically. Clients with the same URL share one connection; the connection closes when its last client is removed. Passing an existing `id` removes the old client with that id first. The client has these methods: - `send(msg, [callback], [timeout])` sends a JSON message. With a callback, the message gets a `callbackid`, and the callback `function(err, response)` runs when the server answers with the same `callbackid` (fields `error` and `response`). While the connection is down it retries every 500 ms, up to ten times, then calls back with `offline`. A timeout gives `timeout`. - `rpc(msg, [timeout])` the same as `send()`, but returns a promise. - `cmd(msg, [timeout])` sends without waiting for an answer. - `message(fn)`, `error(fn)` and `online(fn)` set handlers. `online(meta)` runs with the `init` message of the server, and with `null` when the connection closes. - `close()` or `remove()` removes the client. Properties: `id`, `url`, `connected`, `meta` (the last `init` message). Example: Ask the server ```js var client = OPENCLIENT('https://service.example.com/'); client.message(function(msg) { console.log('Message:', msg); }); client.send({ type: 'ping' }, function(err, response) { console.log(err, response); }, 5000); var stats = await client.rpc({ type: 'stats' }, 5000); ``` --- title: Mail project: Total.js V4 version: 0.0.99 section: reference language: en license: MIT url: https://totaljs.es/docs/total-js-v4/0-0-99/reference/mail/ updated: 2026-11-16T15:41:05.817Z --- # Mail > Global mail functions, the mail configuration, the Mail module and the message object. `MAIL()`, `HTMLMAIL()`, `LOGMAIL()` and `controller.mail()` send email with the SMTP server from the configuration; the `Mail` module creates and sends messages to any server. In this reference `message` is a message returned by these functions or by `Mail.create()`. The guide [Sending email](../../guides/mail/) explains how to use them with examples; this page is the exact reference. ## API ### MAIL(address, subject, view, [model], [language], [callback]) Type: `method` Renders a view and sends it as an HTML email. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `address` | `String|Array` | yes | | One email address or an array of addresses; each one becomes a `To` recipient. | | `subject` | `String` | yes | | The subject. | | `view` | `String` | yes | | The name of a view in `views/`, for example `mails/welcome`. | | `model` | `Object` | no | | The model of the view. | | `language` | `String` | no | | A language for the subject and the view. | | `callback` | `Function` | no | | Called with `function(err, message)` when the message has been written to the server, or with the reply line when the server rejects it. | Returns: `MailMessage` The message, before it is sent. The view is rendered without a layout; the model is available as `model`. With `language`, the subject is translated (a subject with `@(...)` is translated by its parts) and the view is rendered in this language. A view name that starts with `=theme/` is taken from this theme. The sender, reply-to and copies come from the configuration. The message is sent on the next tick, so you can still change it. `callback` can also be the fifth argument and `language` the sixth. Example: A welcome email ```js MAIL('peter@example.com', 'Welcome', 'mails/welcome', { name: 'Peter' }, function(err) { err && console.log('Not sent', err); }); ``` Example: Translated, with an attachment ```js MAIL(user.email, '@(Your invoice)', 'mails/invoice', invoice, user.language).attachment(filename, 'invoice.pdf'); ``` ### HTMLMAIL(address, subject, body, [language], [callback]) Type: `method` Sends an HTML string as an email. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `address` | `String|Array` | yes | | One email address or an array of addresses; each one becomes a `To` recipient. | | `subject` | `String` | yes | | The subject. | | `body` | `String` | yes | | The HTML of the message. | | `language` | `String` | no | | A language for the subject and the body. | | `callback` | `Function` | no | | Called with `function(err, message)` when the message has been written to the server, or with the reply line when the server rejects it. | Returns: `MailMessage` The message, before it is sent. A body without a `<body>` element is wrapped in a full HTML document with the subject as the title and a `<body>` with normalized CSS (no margin, Arial 14px). With `language`, the subject is translated and the `@(...)` texts of the body are translated too. `callback` can also be the fourth argument. Example: A short message ```js HTMLMAIL('peter@example.com', 'Reset password', '<p>Your code is <b>' + code + '</b>.</p>'); ``` ### LOGMAIL(address, [subject], body, [callback]) Type: `method` Sends a log or notification email. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `address` | `String|Array` | yes | | One email address or an array of addresses; each one becomes a `To` recipient. | | `subject` | `String` | no | `name and version` | The subject. | | `body` | `String|Object` | yes | | The text or an object to serialize. | | `callback` | `Function` | no | | Called with `function(err, message)` when the message has been written to the server, or with the reply line when the server rejects it. | Returns: `MailMessage` The message, before it is sent. The body is placed in a `<pre>` element; an object is serialized as JSON. Without a subject, the subject is the `name` and the `version` of the configuration, for example `My app v1.0.0`. Example: Notify the administrator ```js LOGMAIL('admin@example.com', 'New order', { id: order.id, price: order.price }); ``` Example: Only a body ```js LOGMAIL('admin@example.com', 'The import has finished.'); ``` ### controller.mail(address, subject, view, [model], [callback]) Type: `method` Renders a view and sends it as an email from an action. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `address` | `String|Array` | yes | | One email address or an array of addresses; each one becomes a `To` recipient. | | `subject` | `String` | yes | | The subject; `@(...)` parts are translated. | | `view` | `String` | yes | | The name of a view in `views/`. | | `model` | `Object` | no | | The model of the view. | | `callback` | `Function` | no | | Called with `function(err, message)` when the message has been written to the server, or with the reply line when the server rejects it. | Returns: `MailMessage` The message, before it is sent. It works like `MAIL()`; the subject is translated with the language of the controller (`this.language`), and the view is rendered with it. The layout of the controller is not used for the email. Example: After an order ```js exports.install = function() { ROUTE('POST /api/orders/', order); }; function order() { var self = this; self.mail(self.body.email, '@(Your order)', 'mails/order', self.body); self.success(); } ``` ### DEF.onMail = function(address, subject, body, [callback], [replyTo]) {} Type: `delegate` Creates and schedules every message of `MAIL()`, `HTMLMAIL()`, `LOGMAIL()` and `controller.mail()`. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `address` | `String|Array` | yes | | One email address or an array of addresses; each one becomes a `To` recipient. | | `subject` | `String` | yes | | The subject. | | `body` | `String` | yes | | The HTML body. | | `callback` | `Function` | no | | The message callback. | | `replyTo` | `String` | no | | A reply-to address instead of `mail_reply`. | Returns: `MailMessage` The message. The default delegate creates a message with `Mail.create()`, adds the recipients, sets the sender from `mail_from` and `name`, adds `replyTo` or `mail_reply`, `mail_bcc` and `mail_cc`, and sends it on the next tick with `message.send2()`. Replace it to send email in another way; it must return a message object, because the callers change it (for example with `manually()`). Example: Add a header to the subject ```js var onmail = DEF.onMail; DEF.onMail = function(address, subject, body, callback, replyTo) { return onmail(address, '[My app] ' + subject, body, callback, replyTo); }; ``` ### ON('mail', function(message) {}) Type: `event` Emitted for every message just before it is written to the SMTP server. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `message` | `MailMessage` | yes | | The message being sent. | It is emitted for messages sent with the configuration and with `Mail.send()`. Example: Audit outgoing email ```js ON('mail', function(message) { console.log('Mail to', message.address_to, message.subject); }); ``` ### CMD('clear_smtpcache') Type: `command` Makes the next message read `mail_smtp_options` again. The options of the SMTP connection are cached after the first message. Run this command after you change `CONF.mail_smtp_options` in code. `LOADCONFIG()` and `Mail.use()` clear the cache themselves. Example: Change the SMTP account ```js CONF.mail_smtp = 'smtp.example.com'; CONF.mail_smtp_options = { port: 465, secure: true, user: 'info@example.com', password: 'secret' }; CMD('clear_smtpcache'); ``` ### mail_smtp : smtp.example.com Type: `config` The host name of the SMTP server. Used by `MAIL()`, `HTMLMAIL()`, `LOGMAIL()`, `controller.mail()`, `message.send2()` and `Mail.send2()`. When it is empty, the framework uses `smtp.` plus the domain of the sender address and stores it here. Example: In the config file ```text mail_smtp : smtp.example.com ``` ### mail_smtp_options : { port: 465, secure: true, user: '...', password: '...' } Type: `config` The options of the SMTP connection. In the config file it is a JavaScript object written as text; in code it is an object. Options: - `port` (default `25`, or `465` with `secure`); - `secure` (default `false`): TLS from the start; the options are also passed to the TLS connection; - `user` and `password`: the login (`AUTH LOGIN` or `AUTH PLAIN`, as the server offers); - `token`: an OAuth 2.0 access token for `AUTH XOAUTH2`, used with `user`; - `tls`: options of the TLS connection; the client upgrades the connection with `STARTTLS`; - `timeout` (default `10000`): the socket timeout in milliseconds. With `user` and `password`, a server that announces ESMTP gets `STARTTLS` before the login. Example: SMTPS ```text mail_smtp_options : { port: 465, secure: true, user: 'info@example.com', password: 'secret' } ``` Example: Submission port with STARTTLS ```text mail_smtp_options : { port: 587, user: 'info@example.com', password: 'secret' } ``` Example: OAuth 2.0 ```text mail_smtp_options : { port: 587, user: 'info@example.com', token: 'ya29...' } ``` ### mail_smtp_keepalive : 10 minutes Type: `config` How long a connection to the SMTP server stays open for the next messages. Default `10 minutes`. It is used by `message.send2()` while the application runs a web server; the open connection is reused for all messages to the same host. A number is in minutes. `false` opens a new connection for every message. Example: Close after each message ```text mail_smtp_keepalive : false ``` ### mail_from : info@example.com Type: `config` The sender address of messages sent with the configuration. The sender name is the `name` key of the configuration. `mail_address_from` is an older name of this key. Example: Sender ```text name : My app mail_from : info@example.com ``` ### mail_reply : support@example.com Type: `config` A `Reply-To` address added to every message sent with the configuration. Not used when the caller of `DEF.onMail` passes its own `replyTo`. `mail_address_reply` is an older name of this key. Example: Reply to support ```text mail_reply : support@example.com ``` ### mail_cc : office@example.com Type: `config` A `Cc` address added to every message sent with the configuration. Example: Copy ```text mail_cc : office@example.com ``` ### mail_bcc : archive@example.com Type: `config` A `Bcc` address added to every message sent with the configuration. `mail_address_copy` is an older name of this key. Example: Archive every message ```text mail_bcc : archive@example.com ``` ### Mail Type: `class` The global mail module: creates messages and sends them over SMTP. `Mail` is available everywhere. It sends messages to any server (`Mail.send()`), with the configuration (`Mail.send2()`), checks a server (`Mail.try()`, `Mail.use()`) and emits the events `send` and `error`. Example: A message to any server ```js var message = Mail.create('Hello', '<p>Hello.</p>'); message.from('info@example.com'); message.to('peter@example.com'); Mail.send('smtp.example.com', { port: 465, secure: true, user: 'info@example.com', password: 'secret' }, [message], NOOP); ``` ### Mail.create(subject, body) Type: `method` Creates an empty message. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `subject` | `String` | yes | | The subject. | | `body` | `String` | yes | | The body, HTML by default. | Returns: `MailMessage` A new message. The message has no sender and no recipients, and its type is `html`. It is not sent until you call `message.send()`, `message.send2()`, `Mail.send()` or `Mail.send2()`. Example: Create and send ```js var message = Mail.create('Report', '<p>See the attachment.</p>'); message.from('info@example.com', 'My app'); message.to('peter@example.com'); message.attachment(PATH.root('report.pdf')); message.send2(); ``` ### Mail.send(smtp, [options], messages, [callback], [cache]) Type: `method` Sends one message or an array of messages over one connection. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `smtp` | `String` | yes | | The host name of the SMTP server. | | `options` | `Object` | no | `{}` | The connection options, the same as `mail_smtp_options`. | | `messages` | `MailMessage|Array` | yes | | A message or an array of messages. | | `callback` | `Function` | no | | `function(err)`, called once: when the first message has been written, or when the connection fails. | | `cache` | `Boolean|Number|String` | no | `false` | Keeps the connection open: `true` for 10 minutes, a number of minutes, or a text such as `5 minutes`. | Returns: `Mail` The mail module; nothing when the messages join an open connection. All messages go through one connection in their order. `options` can be skipped when `messages` is an array. With `cache`, the connection stays open and later calls for the same host add their messages to it; such a later call does not call its `callback`, so use `message.callback()` there. Example: Two messages ```js Mail.send('smtp.example.com', { port: 465, secure: true, user: 'info@example.com', password: 'secret' }, [a, b], function(err) { err && console.log(err); }); ``` ### Mail.send2(messages, [callback]) Type: `method` Sends messages with `mail_smtp` and `mail_smtp_options`. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `messages` | `MailMessage|Array` | yes | | A message or an array of messages. | | `callback` | `Function` | no | | `function(err)`, called once: when the first message has been written, or when the connection fails. Use `message.callback()` for each message. | Returns: `Mail` The mail module. The same as `Mail.send()` with the server and the options of the configuration. Example: A newsletter ```js var messages = users.map(function(user) { var message = Mail.create('News', html); message.from(CONF.mail_from, CONF.name); message.to(user.email); return message; }); Mail.send2(messages, function(err) { err && console.log(err); }); ``` ### Mail.try(smtp, [options], [callback]) Type: `method` Checks an SMTP server: connects, signs in and quits. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `smtp` | `String` | yes | | The host name of the SMTP server. | | `options` | `Object` | no | `{}` | The connection options, the same as `mail_smtp_options`. | | `callback` | `Function` | no | | `function(err)`. | Returns: `Mail|Promise` The mail module, or a promise without a callback. No message is sent. Without a callback it returns a promise that is rejected with the error. Example: With a callback ```js Mail.try('smtp.example.com', { port: 465, secure: true, user: 'info@example.com', password: 'secret' }, function(err) { console.log(err ? 'Failed' : 'Works'); }); ``` Example: With a promise ```js try { await Mail.try('smtp.example.com', { port: 587, user: 'info@example.com', password: 'secret' }); } catch (err) { console.log('SMTP failed', err); } ``` ### Mail.use(smtp, [options], [callback]) Type: `method` Checks an SMTP server and, when it works, makes it the server of the configuration. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `smtp` | `String` | yes | | The host name of the SMTP server. | | `options` | `Object` | no | | The connection options. | | `callback` | `Function` | no | | `function(err)`. | It calls `Mail.try()`; on success it sets `CONF.mail_smtp` and `CONF.mail_smtp_options` and clears the cached options. Without a callback, an error is logged with `F.error()`. Example: Settings from a database ```js Mail.use(settings.smtp, settings.smtpoptions, function(err) { err && console.log('SMTP is not available', err); }); ``` ### Mail.debug = true Type: `property` Prints the SMTP conversation to the console. Returns: `Boolean` Default `false`. Every command sent and every reply received is printed. Example: Debug a server ```js Mail.debug = true; ``` ### Mail.on('error', function(err, connection) {}) Type: `event` Emitted when a connection or an SMTP command fails. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `err` | `Error|String` | yes | | The error or the reply line of the server. | | `connection` | `Object` | yes | | The internal connection object. | Not emitted for `Mail.try()` or for a connection reset. A message rejected by the server is passed as its reply line. Example: Log SMTP errors ```js Mail.on('error', function(err) { console.log('SMTP error', err); }); ``` ### Mail.on('send', function(connection) {}) Type: `event` Emitted when a connection to the SMTP server is ready and the client starts the conversation. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `connection` | `Object` | yes | | The internal connection object. | Example: Count connections ```js Mail.on('send', function() { console.log('SMTP connection'); }); ``` ### Mail.removeListener(name, fn) Type: `method` Removes a handler of a `Mail` event. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `name` | `String` | yes | | The event name, `error` or `send`. | | `fn` | `Function` | yes | | The handler added with `Mail.on()`. | Returns: `Mail` The mail module. `Mail.once(name, fn)` adds a handler that runs once; `Mail.removeAllListeners([name])` removes all handlers of one event or of all events. Example: Stop logging ```js function log(err) { console.log(err); } Mail.on('error', log); Mail.removeListener('error', log); ``` ### message.to(address, [name], [clear]) Type: `method` Adds a `To` recipient. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `address` | `String` | yes | | The email address. | | `name` | `String` | no | | The name of the recipient. | | `clear` | `Boolean` | no | `false` | Removes the recipients added before. | Returns: `MailMessage` The message. The address can contain the name: `Peter Sirka <peter@example.com>`. `clear` can be the second argument. Example: Two recipients ```js message.to('peter@example.com', 'Peter'); message.to('Lucia <lucia@example.com>'); ``` ### message.cc(address, [name], [clear]) Type: `method` Adds a `Cc` recipient. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `address` | `String` | yes | | The email address. | | `name` | `String` | no | | The name of the recipient. | | `clear` | `Boolean` | no | `false` | Removes the `Cc` addresses added before. | Returns: `MailMessage` The message. The address can contain the name, like in `message.to()`. `clear` can be the second argument. Example: A copy ```js message.cc('office@example.com'); ``` ### message.bcc(address, [clear]) Type: `method` Adds a `Bcc` recipient. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `address` | `String` | yes | | The email address. | | `clear` | `Boolean` | no | `false` | Removes the `Bcc` addresses added before, including `mail_bcc`. | Returns: `MailMessage` The message. The address is not written to the headers. Use a plain address without a name. Example: A hidden copy ```js message.bcc('archive@example.com'); ``` ### message.reply(address, [clear]) Type: `method` Adds a `Reply-To` address. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `address` | `String` | yes | | The email address. | | `clear` | `Boolean` | no | `false` | Removes the reply addresses added before, including `mail_reply`. | Returns: `MailMessage` The message. Use a plain address without a name. Example: Replace the configured address ```js message.reply('billing@example.com', true); ``` ### message.from(address, [name]) Type: `method` Sets the sender. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `address` | `String` | yes | | The email address. | | `name` | `String` | no | | The name of the sender. | Returns: `MailMessage` The message. The address can contain the name: `My app <info@example.com>`. Messages created by `MAIL()` and the other global functions already have the sender from `mail_from` and `name`. Example: Sender with a name ```js message.from('info@example.com', 'My app'); ``` ### message.sender(address, [name]) Type: `method` An alias of `message.from()`. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `address` | `String` | yes | | The email address. | | `name` | `String` | no | | The name of the sender. | Returns: `MailMessage` The message. Example: Sender ```js message.sender('info@example.com', 'My app'); ``` ### message.subject Type: `property` The subject of the message. Returns: `String` You can change it before the message is sent. Non-ASCII characters are encoded for you. Example: Prefix ```js message.subject = '[Test] ' + message.subject; ``` ### message.body Type: `property` The body of the message. Returns: `String` HTML by default; see `message.type`. Example: Set the body later ```js var message = HTMLMAIL('peter@example.com', 'Report', ''); message.manually(); render(function(html) { message.body = html; message.send2(); }); ``` ### message.type Type: `property` The content type of the body: `html` or `plain`. Returns: `String` Default `html`. The body is sent as `text/` plus this value. Example: A plain text message ```js var message = Mail.create('Hello', 'Hello,\nthis is plain text.'); message.type = 'plain'; ``` ### message.attachment(filename, [name], [contentid]) Type: `method` Adds a file from the disk as an attachment. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `filename` | `String` | yes | | The path of the file. | | `name` | `String` | no | `the name of the file` | The file name shown in the email. | | `contentid` | `String` | no | | A Content-ID for an inline attachment, unique in the message. | Returns: `MailMessage` The message. The content type comes from the extension of `name`. With `contentid`, the file is an inline attachment and the HTML refers to it as `cid:contentid`. An `.ics` file is sent as a calendar invitation. Example: A PDF ```js message.attachment(PATH.root('invoices/2024-001.pdf'), 'invoice.pdf'); ``` Example: An inline image ```js var message = HTMLMAIL('peter@example.com', 'Report', '<img src="cid:chart1" />'); message.attachment(PATH.public('img/chart.png'), 'chart.png', 'chart1'); ``` ### message.attachmentfs(storage, id, [name], [contentid]) Type: `method` Adds a file from a `FILESTORAGE()` as an attachment. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `storage` | `String` | yes | | The name of the file storage. | | `id` | `String` | yes | | The identifier of the file. | | `name` | `String` | no | `the stored name` | The file name shown in the email. | | `contentid` | `String` | no | | A Content-ID for an inline attachment. | Returns: `MailMessage` The message. Without `name`, the name and the content type come from the stored file. A file that cannot be read is skipped and the error is logged. Example: A stored file ```js message.attachmentfs('documents', doc.fileid); ``` ### message.unsubscribe(url) Type: `method` Adds the `List-Unsubscribe` headers. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `url` | `String` | yes | | An unsubscribe URL or email address. | Returns: `MailMessage` The message. A URL that starts with `http:` or `https:` is used as a link; any other value is used as a `mailto:` address. The header `List-Unsubscribe-Post: List-Unsubscribe=One-Click` is added too. Example: A newsletter ```js message.unsubscribe('https://example.com/unsubscribe/?id=' + user.id); ``` ### message.callback(fn) Type: `method` Sets the callback of the message. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `fn` | `Function` | yes | | `function(err, message)`. | Returns: `MailMessage` The message. The callback runs when the message has been written to the server, or when the server rejects it; the error is then the reply line of the server. Connection errors are not passed here: they are logged and emitted as `Mail.on('error')`. Example: Mark as sent ```js message.callback(function(err) { if (!err) NOSQL('orders').modify({ mailed: true }).id(order.id); }); ``` ### message.manually() Type: `method` Stops the automatic sending of a message from `MAIL()`, `HTMLMAIL()`, `LOGMAIL()` or `controller.mail()`. Returns: `MailMessage` The message. Call it in the same call stack, then send the message yourself with `message.send2()`. Example: Attach a generated file ```js var message = HTMLMAIL('peter@example.com', 'Export', '<p>The file is attached.</p>'); message.manually(); createexport(function(filename) { message.attachment(filename, 'export.csv'); message.send2(); }); ``` ### message.send2([callback]) Type: `method` Sends the message with `mail_smtp` and `mail_smtp_options`. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `callback` | `Function` | no | | Called when the message has been written, on a new connection. | Returns: `MailMessage` The message. Without `mail_smtp`, the server is `smtp.` plus the domain of the sender; without a sender it throws `Missing SMTP settings`. While the application runs a web server, the connection is kept open for `mail_smtp_keepalive`; when the message goes to such an open connection, `callback` is not called, so prefer `message.callback()`. Example: Send a created message ```js var message = Mail.create('Hello', '<p>Hello.</p>'); message.from(CONF.mail_from, CONF.name); message.to('peter@example.com'); message.callback(function(err) { err && console.log(err); }); message.send2(); ``` ### message.send(smtp, options, [callback], [cache]) Type: `method` Sends the message to an SMTP server. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `smtp` | `String` | yes | | The host name of the SMTP server. | | `options` | `Object` | yes | | The connection options, the same as `mail_smtp_options`; pass `{}` for none. | | `callback` | `Function` | no | | `function(err, message)`. | | `cache` | `Boolean|Number|String` | no | `false` | Keeps the connection open, like in `Mail.send()`. | Returns: `MailMessage` The message. Uses its own connection to `smtp`; the configuration is not used. Example: Another server ```js message.send('smtp.example.com', { port: 465, secure: true, user: 'info@example.com', password: 'secret' }, function(err) { console.log(err ? 'Failed' : 'Sent'); }); ``` --- title: Scheduling and events project: Total.js V4 version: 0.0.99 section: reference language: en license: MIT url: https://totaljs.es/docs/total-js-v4/0-0-99/reference/scheduling-and-events/ updated: 2026-11-16T15:41:15.818Z --- # Scheduling and events > SCHEDULE(), the event functions, every built-in event and the timing helpers. The scheduler `SCHEDULE()`, the event functions `ON()`, `ONCE()`, `OFF()`, `EMIT()` and `EMIT2()`, every built-in framework event, and the timing helpers `WAIT()`, `setTimeout2()`, `clearTimeout2()`, `PAUSESERVER()` and `CLEANUP()`. The guide [Scheduling and events](../../guides/scheduling-and-events/) explains how to use them with examples; this page is the exact reference. ## API ### SCHEDULE(date, [repeat], fn) Type: `method` Registers a job that runs at a time, repeatedly, or by a cron expression. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `date` | `String|Number|Date` | yes | | A cron expression, a date or time string, a timestamp or a Date. | | `repeat` | `String` | no | | A repeat period such as `'1 day'` or `'each hour'`. Not used with a cron expression. | | `fn` | `Function` | yes | | The job. It gets no arguments. | Returns: `Object` The job, with `id`, `remove()` and `exec()`. The framework checks the jobs once a minute, in its service, so a job runs on the first check at or after its time. - A **string with a space** is a cron expression with five fields (minute, hour, day of month, month, day of week). The job runs at every minute that matches; it takes no `repeat`. - A **string without a space** is parsed as a date or time (for example `'03:00'`) in the application time zone (`default_timezone`). If it has already passed and `repeat` is set, the first run moves forward by one `repeat`. - A **number** is a timestamp in milliseconds; a **Date** is used as it is. `repeat` is a period for `Date.add()`, such as `'5 minutes'` or `'1 day'`; the word `each` is read as `1` (`'each day'`). Without `repeat` a date job runs once and is then removed. Cron fields accept `*`, a number, a list (`1,15,30`) and a range (`9-17`). Days of the week are `0`-`6` (Sunday is `0`) or names, of which only the first two letters count (`su`, `mo`, `tu`, `we`, `th`, `fr`, `sa`). Example: Every day at 03:00 ```js SCHEDULE('03:00', '1 day', function() { console.log('Nightly cleanup'); }); ``` Example: Cron: working days at 08:00 ```js SCHEDULE('0 8 * * mo-fr', function() { console.log('Good morning'); }); ``` Example: Once at a specific date ```js SCHEDULE(new Date(2026, 11, 24, 8, 0), function() { console.log('Christmas Eve'); }); ``` ### schedule.id Type: `property` The identifier of the job. Returns: `String` A short random string that `SCHEDULE()` creates for each job. ### schedule.remove() Type: `method` Stops the job and removes it from the scheduler. Use it to stop a repeating or cron job. A one-time job removes itself after it runs. Example: Stop after the first run ```js var job = SCHEDULE('0,30 * * * *', function() { console.log('Run'); job.remove(); }); ``` ### schedule.exec() Type: `method` Runs the job now. Calls the job function immediately. The planned time of the next run does not change. Example: Run at start and then every hour ```js var job = SCHEDULE('0 * * * *', refresh); ON('ready', function() { job.exec(); }); ``` ### ON(name, fn) Type: `method` Adds a listener to an event. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `name` | `String` | yes | | The event name. | | `fn` | `Function` | yes | | The listener. | `fn` is called with the arguments of `EMIT()`, and `this` is the framework. Listeners run in the order they were added. For `init`, `load` and `ready`, if the application has already loaded, `fn` is called immediately (and is not stored). Example: React to the start ```js ON('ready', function() { console.log('Listening on port', F.port); }); ``` ### ONCE(name, fn) Type: `method` Adds a listener that is removed after its first call. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `name` | `String` | yes | | The event name. | | `fn` | `Function` | yes | | The listener. | Works like `ON()`; the listener is removed after the first `EMIT()` of the event. Example: First request only ```js ONCE('request', function(req) { console.log('First request from', req.ip); }); ``` ### OFF([name], [fn]) Type: `method` Removes event listeners. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `name` | `String` | no | | The event name. | | `fn` | `Function` | no | | The listener to remove. | - `OFF(name, fn)` removes that one listener. It must be the same function you passed to `ON()`. - `OFF(name)` removes all listeners of the event, including the framework's own. - `OFF()` removes all listeners of all events. Example: Remove one listener ```js function log(req, res) { console.log(req.url); } ON('request', log); OFF('request', log); ``` ### EMIT(name, [a], [b], [c], [d], [e], [f], [g]) Type: `method` Calls all listeners of an event in the current process. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `name` | `String` | yes | | The event name. | | `a...g` | `Object` | no | | Up to seven arguments for the listeners. | Passes up to seven arguments. The listeners run synchronously, in the order they were added. Listeners added with `ONCE()` are removed afterwards. An event without listeners does nothing. Example: Your own event ```js ON('order_created', function(order) { console.log('New order', order.id); }); EMIT('order_created', { id: 'A100' }); ``` ### EMIT2(name, [a], [b], [c], [d], [e]) Type: `method` Sends an event to the other processes of the application. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `name` | `String` | yes | | The event name. | | `a...e` | `Object` | no | | Up to five serialisable arguments. | The event goes to the threads (from the main process, which also calls its own listeners), to the cluster, or from a thread or worker back to its parent. Up to five arguments, sent as IPC messages, so use plain serialisable values. In a single process without threads or a cluster nothing happens; use `EMIT()` there. Example: Clear a cache in every process ```js ON('products_changed', function() { CACHE.remove('products'); }); EMIT2('products_changed'); ``` ### 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` | yes | | `function(err, success)`. | | `timeout` | `Number` | no | `5000` | Maximum wait in milliseconds. | | `interval` | `Number` | no | `500` | Check interval in milliseconds. | If `validator()` already returns `true`, `callback(null, true)` runs immediately. Otherwise `validator()` is checked every `interval` ms. When it returns `true` the callback gets `(null, true)`; after `timeout` ms it gets `(Error("Timeout"), false)`. Example: Wait for a connection ```js WAIT(() => MAIN.client != null, function(err) { if (err) console.log('Not connected'); else MAIN.client.send('hello'); }, 10000); ``` ### setTimeout2(name, fn, timeout, [limit], [param]) Type: `method` A named timeout: each call with the same name restarts the timer. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `name` | `String` | yes | | The name of the timer. | | `fn` | `Function` | yes | | `function(param)`. | | `timeout` | `Number` | yes | | Delay in milliseconds. | | `limit` | `Number` | no | | Maximum number of postponements before `fn` runs at once. | | `param` | `Object` | no | | An argument for `fn`. | Returns: `Timeout` The Node.js timer, or nothing when `fn` ran immediately. Cancels the previous timer of the same name and starts a new one, so `fn` runs once, `timeout` ms after the last call (a debounce). With `limit`, after `limit` postponements `fn` runs immediately (without `param`) and the counter resets. `param` is passed to `fn`. Example: Save once after a burst of changes ```js function changed() { setTimeout2('save', save, 2000); } function save() { F.Fs.writeFile(PATH.databases('state.json'), JSON.stringify(MAIN.state), NOOP); } ``` ### clearTimeout2(name) Type: `method` Cancels a timer created by setTimeout2(). | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `name` | `String` | yes | | The name used in `setTimeout2()`. | Returns: `Boolean` `true` if a timer was cancelled. Returns `true` if a pending timer with that name was cancelled. Example: Cancel ```js setTimeout2('save', save, 5000); clearTimeout2('save'); ``` ### PAUSESERVER(name, [enable]) Type: `method` Pauses the server: every request gets 503 while a name is paused. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `name` | `String` | yes | | A name for the pause. | | `enable` | `Boolean` | no | | `true` pauses, `false` resumes. When omitted, the state toggles. | Returns: `Boolean` `true` if `name` is now paused. Each `name` is one reason to pause. While at least one name is paused, HTTP requests are answered with `503` and WebSocket upgrades are refused. With `enable` the state is set; without it the state of `name` is toggled. `F.wait()` is the same function. Example: Pause during a migration ```js PAUSESERVER('migration', true); migrate(function() { PAUSESERVER('migration', false); }); ``` ### default_interval_clear_cache : 10 Type: `config` Minutes between clean-ups of the temporary file and view cache. Returns: `Number` Counted in service ticks (one per minute). Each clean-up emits `clear` with the type `'temporary'`. ### default_interval_clear_resources : 20 Type: `config` Minutes between clean-ups of the loaded resources. Returns: `Number` Counted in service ticks. Each clean-up emits `clear` with the type `'resources'`. ### default_interval_clear_dnscache : 30 Type: `config` Minutes between clean-ups of the DNS cache. Returns: `Number` Counted in service ticks. Each clean-up emits `clear` with the type `'dns'`. ### ON('init', function()) Type: `event` Configuration is loaded; the application files are not loaded yet. Emitted once at start, before definitions, models, controllers and the other files load. If you call `ON('init')` after the application has loaded, the function runs immediately. Example: Listen ```js ON('init', function() { console.log('Config ready, port', CONF.port); }); ``` ### ON('load', function()) Type: `event` All application files are loaded. Emitted once, right before `ready`. If the application has already loaded, the function runs immediately. Example: Listen ```js ON('load', function() { console.log('Loaded'); }); ``` ### ON('ready', function()) Type: `event` The application is ready. Emitted once after `load`, when all files are loaded. The usual place for start-up code. If the application has already loaded, the function runs immediately. Example: Listen ```js ON('ready', function() { MAIN.started = NOW; }); ``` ### ON('service', function(counter)) Type: `event` Emitted every minute by the framework service. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `counter` | `Number` | yes | | The number of service runs. | `counter` is the number of runs since the application started (1, 2, 3...). Use the remainder to run code every few minutes. In a worker, adding this listener starts the timer. Example: Listen ```js ON('service', function(counter) { if (counter % 10 === 0) console.log('Ten more minutes'); }); ``` ### ON('exit', function(signal)) Type: `event` The application is stopping. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `signal` | `Number|String` | yes | | The signal; `15` (SIGTERM) when none was given. | Emitted once when the framework stops, after it has sent the signal to its workers and threads. Keep the work synchronous; the process ends soon after. Example: Listen ```js ON('exit', function(signal) { console.log('Stopping with signal', signal); }); ``` ### ON('request', function(req, res)) Type: `event` A request arrived, before routing. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `req` | `Request` | yes | | The request. | | `res` | `Response` | yes | | The response. | Emitted for each HTTP request after the proxies are checked and before redirects and routing. Example: Listen ```js ON('request', function(req, res) { console.log(req.method, req.url); }); ``` ### ON('request_begin', function(req, res)) Type: `event` The request is prepared for routing. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `req` | `Request` | yes | | The request. | | `res` | `Response` | yes | | The response. | Emitted after the request has been parsed (headers, XHR flag), before the route is looked up. Example: Listen ```js ON('request_begin', function(req) { req.started = Date.now(); }); ``` ### ON('request_end', function(req, res)) Type: `event` The response to a request has finished. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `req` | `Request` | yes | | The request. | | `res` | `Response` | yes | | The response. | Emitted when the framework has finished sending a response. Example: Listen ```js ON('request_end', function(req, res) { console.log(req.url, Date.now() - req.started, 'ms'); }); ``` ### ON('controller', function(controller, name, options)) Type: `event` A route action is about to run. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `controller` | `Controller` | yes | | The controller of the request. | | `name` | `String` | yes | | The controller name. | | `options` | `Object` | yes | | The custom options of the route. | Emitted before the action of a route runs. Call `controller.cancel()` to stop the action here. `name` is the name of the controller file that declared the route. Example: Listen ```js ON('controller', function(controller, name) { controller.repository.section = name; }); ``` ### ON('@name', function(controller, name, options)) Type: `event` A route action of one controller is about to run. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `controller` | `Controller` | yes | | The controller of the request. | | `name` | `String` | yes | | The controller name. | | `options` | `Object` | yes | | The custom options of the route. | Like `controller`, but only for routes declared in the controller file `name`: `ON('@admin')` runs for the routes in `controllers/admin.js`. Example: Listen ```js ON('@admin', function(controller) { controller.layout('layout_admin'); }); ``` ### ON('errornnn', function(req, res, exception)) Type: `event` An error response is sent, for example error404. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `req` | `Request` | yes | | The request. | | `res` | `Response` | yes | | The response. | | `exception` | `Error` | yes | | The problem, if any. | The name is `error` plus the HTTP status: `error400`, `error401`, `error404`, `error500`... Emitted when the framework answers with that status. Example: Listen ```js ON('error404', function(req) { console.log('Not found:', req.url); }); ``` ### ON('error', function(obj)) Type: `event` The framework logged an error. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `obj` | `Object` | yes | | `{ error, name, url, date }`. | Emitted by the default `DEF.onError` handler for each error it records. The last five errors are also kept in `F.errors`. Example: Listen ```js ON('error', function(obj) { console.log(obj.name, obj.error); }); ``` ### ON('route', function(type, route)) Type: `event` A route was registered. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `type` | `String` | yes | | `web`, `websocket` or `file`. | | `route` | `Object` | yes | | The internal route object. | `type` is `'web'` for `ROUTE()` routes, `'websocket'` for WebSocket routes and `'file'` for file routes. Example: Listen ```js ON('route', function(type) { console.log('A new route of type', type); }); ``` ### ON('install', function(type, name, module)) Type: `event` A file of the application was installed. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `type` | `String` | yes | | For example `'controller'` or `'model'`. | | `name` | `String` | yes | | The name of the file. | | `module` | `Object` | yes | | The exports of the file. | Emitted after the framework installs a controller, model, definition, plugin, module, source and other types. `module` is what the file exports. Example: Listen ```js ON('install', function(type, name) { console.log('Installed', type, name); }); ``` ### ON('configure', function(CONF)) Type: `event` The configuration was loaded. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `CONF` | `Object` | yes | | The configuration. | Emitted each time the configuration files are read, at start and on reload. Example: Listen ```js ON('configure', function(conf) { console.log('Name:', conf.name); }); ``` ### ON('update', function(err)) Type: `event` UPDATE() has finished. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `err` | `ErrorBuilder` | yes | | The errors, or `null`. | Emitted when the update scripts of `UPDATE()` have run, with the errors if any. Example: Listen ```js ON('update', function(err) { err && console.log('Update failed', err); }); ``` ### ON('clear', function(type, [value])) Type: `event` An internal cache was cleared. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `type` | `String` | yes | | `temporary`, `resources` or `dns`. | | `value` | `Object` | no | | The temporary storage, for `temporary` only. | `type` is `'temporary'` (with the temporary storage as `value`), `'resources'` or `'dns'`. The service clears them by the `default_interval_clear_*` settings. Example: Listen ```js ON('clear', function(type) { console.log('Cleared', type); }); ``` ### ON('cache_set', function(key, value, expire, sync)) Type: `event` A value was stored with CACHE. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `key` | `String` | yes | | The key. | | `value` | `Object` | yes | | The value. | | `expire` | `Date` | yes | | The expiration. | | `sync` | `Boolean` | yes | | An internal flag for synchronised caches. | Emitted by `CACHE.set()`. Example: Listen ```js ON('cache_set', function(key) { console.log('Cached', key); }); ``` ### ON('cache_expired', function(key, value)) Type: `event` A CACHE value expired. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `key` | `String` | yes | | The key. | | `value` | `Object` | yes | | The expired value. | Emitted when the cache removes an expired item (checked every minute) or finds one when reading it. Example: Listen ```js ON('cache_expired', function(key) { console.log('Expired', key); }); ``` ### ON('controller_render_meta', function(controller)) Type: `event` A view is about to print its meta tags. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `controller` | `Controller` | yes | | The controller that renders the view. | Emitted when a layout renders `@{meta}`, before the tags are built. Change `controller.repository` here to adjust them. Example: Listen ```js ON('controller_render_meta', function(controller) { if (!controller.repository.title) controller.repository.title = CONF.name; }); ``` ### ON('websocket', function(req, socket, head)) Type: `event` A WebSocket upgrade request arrived. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `req` | `Request` | yes | | The request. | | `socket` | `Socket` | yes | | The network socket. | | `head` | `Buffer` | yes | | The first packet of the upgraded stream. | Emitted after a matching WebSocket route was found, before the connection is accepted. Example: Listen ```js ON('websocket', function(req) { console.log('WebSocket from', req.ip); }); ``` ### ON('websocket_begin', function(controller, client)) Type: `event` A WebSocket client connected. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `controller` | `WebSocket` | yes | | The WebSocket controller. | | `client` | `WebSocketClient` | yes | | The client. | Emitted when a client is added to its WebSocket controller, before its `open` event. Example: Listen ```js ON('websocket_begin', function(controller, client) { console.log('Online:', controller.online); }); ``` ### ON('websocket_end', function(controller, client)) Type: `event` A WebSocket client disconnected. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `controller` | `WebSocket` | yes | | The WebSocket controller. | | `client` | `WebSocketClient` | yes | | The client. | Emitted when a client is removed from its WebSocket controller. Example: Listen ```js ON('websocket_end', function(controller, client) { console.log('Left:', client.id); }); ``` ### ON('componentator', function(meta)) Type: `event` COMPONENTATOR() is about to download components. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `meta` | `Object` | yes | | `{ name, components }`. | `meta` holds `name` and `components` from the `COMPONENTATOR()` call. Example: Listen ```js ON('componentator', function(meta) { console.log('Components', meta.name); }); ``` ### ON('mail', function(message)) Type: `event` An email message is being sent. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `message` | `MailMessage` | yes | | The message. | Emitted for each message as the SMTP sender writes it. Example: Listen ```js ON('mail', function(message) { console.log('Mail:', message.subject); }); ``` ### ON('message', function(msg, handle)) Type: `event` The process received an IPC message. | 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 the process gets from its parent (`process.on('message')`), after the framework has handled its own. Example: Listen ```js ON('message', function(msg) { if (msg.type === 'reload') console.log('Reload requested'); }); ``` ### ON('watcher', function(app)) Type: `event` The watcher (re)started the application. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `app` | `ChildProcess` | yes | | The application process, or `null`. | Emitted in the main process of `debug` or `release` mode with the file watcher, each time it starts the application process. Example: Listen ```js ON('watcher', function(app) { app && console.log('App PID', app.pid); }); ``` ### ON('debug_start', function()) Type: `event` The application started in debug mode. Emitted in the application process when it starts the first time in debug mode. Example: Listen ```js ON('debug_start', function() { console.log('Debug start'); }); ``` ### ON('debug_restart', function()) Type: `event` The application restarted in debug mode. Emitted instead of `debug_start` when the debug watcher restarts the application after a change. Example: Listen ```js ON('debug_restart', function() { console.log('Restarted after a change'); }); ``` ### CLEANUP(stream, [callback]) Type: `method` · Since: `0.0.96` Destroys a stream after it has finished. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `stream` | `Stream` | yes | | A readable or writable stream. | | `callback` | `Function` | no | | Called after the stream is destroyed. | Returns: `Promise` Only when `callback` is not set. Waits until the stream finishes or fails, destroys it and calls `callback`. Without a callback it returns a Promise. Example: Close a file after piping ```js var stream = F.Fs.createReadStream(PATH.databases('export.csv')); stream.pipe(F.Fs.createWriteStream(PATH.temp('export.csv'))); CLEANUP(stream, function() { console.log('Done'); }); ``` Example: With await ```js async function copy(stream) { await CLEANUP(stream); console.log('Closed'); } ``` --- title: File storage project: Total.js V4 version: 0.0.99 section: reference language: en license: MIT url: https://totaljs.es/docs/total-js-v4/0-0-99/reference/file-storage/ updated: 2026-11-16T15:41:20.819Z --- # File storage > FILESTORAGE(), its methods, the meta object and the controller methods that serve stored files. `FILESTORAGE(name)` returns a storage of binary files in `databases/fs-{name}/`. In this reference `fs` is a storage returned by `FILESTORAGE()` and `meta` the metadata of a file. The guide [File storage](../../guides/file-storage/) explains how to save, read and serve files with examples. ## API ### FILESTORAGE(name) Type: `method` Returns a file storage. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `name` | `String` | yes | | The name of the storage. | Returns: `FileStorage` The storage. Returns the storage `name`, stored in `databases/fs-{name}/`. The object is created on the first call and reused later. The folder is created when the first file is saved. Example: Get a storage ```js var fs = FILESTORAGE('photos'); fs.save(UID(), 'logo.png', PATH.public('img/logo.png')); ``` ### PATH.filestorage(name) Type: `method` Returns the folder of a file storage. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `name` | `String` | yes | | The name of the storage. | Returns: `String` The absolute path of the folder. Returns the path `databases/fs-{name}/` inside the folder set by `directory_databases`. Example: Folder ```js console.log(PATH.filestorage('photos')); // /www/app/databases/fs-photos/ ``` ### fs.name Type: `property` The name of the storage. Returns: `String` The name given to `FILESTORAGE()`. Example: Name ```js console.log(FILESTORAGE('photos').name); // photos ``` ### fs.directory Type: `property` The folder of the storage. Returns: `String` The absolute path of the folder with the files. Change it with `fs.storage()`. Example: Folder ```js console.log(FILESTORAGE('photos').directory); ``` ### fs.total Type: `property` The number of files. Returns: `Number` A counter kept in memory. It starts at `0`; `fs.count()` and `fs.rebuild()` set it, and every saved file adds one. Example: Load the counters ```js var fs = FILESTORAGE('photos'); fs.count(function() { console.log(fs.total, fs.size); }); ``` ### fs.size Type: `property` The total size of the files in bytes. Returns: `Number` A counter kept in memory. It starts at `0`; `fs.count()` and `fs.rebuild()` set it, and every saved file adds its size. Example: Size in MB ```js var fs = FILESTORAGE('photos'); fs.count(function() { console.log((fs.size / 1024 / 1024).floor(2) + ' MB'); }); ``` ### fs.save(id, name, data, [callback], [custom], [expire], [headers]) Type: `method` Saves a file. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `id` | `String` | yes | | The ID of the file. | | `name` | `String` | yes | | The file name with its extension. | | `data` | `String|Buffer|Stream` | yes | | A path, a buffer, a readable stream or a URL. | | `callback` | `Function` | no | | `function(err, meta)`, runs when the file is saved. | | `custom` | `Object` | no | | Any data kept with the file as `meta.custom`. | | `expire` | `String` | no | | A period such as `'1 day'`; after it the file cannot be read. | | `headers` | `Object` | no | | Headers for the request when `data` is a URL. | Returns: `FileStorage|Promise` The storage, or a promise with the meta object. Stores `data` under `id`. The extension of `name` sets the content type; a path in `name` is reduced to the file name. `data` is a path to a file, a `Buffer`, a readable stream or an `http://`/`https://` URL, which is downloaded first. For GIF, PNG, JPEG and SVG images the metadata also gets `width` and `height`. An existing file with the same ID is overwritten. Without a callback the method returns a promise. Alias: `fs.insert()`. Example: Save a buffer ```js FILESTORAGE('documents').save(UID(), 'note.txt', Buffer.from('Hello'), function(err, meta) { console.log(meta.id, meta.size); }); ``` Example: Download from a URL ```js var meta = await FILESTORAGE('photos').save(UID(), 'photo.jpg', 'https://example.com/photo.jpg', null, { source: 'web' }, '30 days'); ``` ### fs.insert(id, name, data, [callback], [custom], [expire], [headers]) Type: `method` Alias of fs.save(). | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `id` | `String` | yes | | The ID of the file. | | `name` | `String` | yes | | The file name with its extension. | | `data` | `String|Buffer|Stream` | yes | | A path, a buffer, a readable stream or a URL. | | `callback` | `Function` | no | | `function(err, meta)`. | | `custom` | `Object` | no | | Any data kept with the file. | | `expire` | `String` | no | | An expiration period. | | `headers` | `Object` | no | | Headers for a URL request. | Returns: `FileStorage|Promise` The storage, or a promise with the meta object. The same method as `fs.save()`. Example: Insert ```js FILESTORAGE('documents').insert(UID(), 'a.txt', Buffer.from('A')); ``` ### fs.savejson(id, value, [callback], [custom], [expire]) Type: `method` Saves an object as JSON. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `id` | `String` | yes | | The ID of the file. | | `value` | `Object` | yes | | The value to store. | | `callback` | `Function` | no | | `function(err, meta)`. | | `custom` | `Object` | no | | Any data kept with the file. | | `expire` | `String` | no | | An expiration period. | Returns: `FileStorage|Promise` The storage, or a promise without a callback. Serializes `value` with `JSON.stringify()` and saves it as `{id}.json`. Example: Save settings ```js FILESTORAGE('data').savejson('settings', { theme: 'dark' }); ``` ### 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 | | `function(err, meta)`. | | `nostream` | `Boolean` | no | `false` | Do not open a stream of the content. | Returns: `FileStorage|Promise` The storage, or a promise with the meta object. Gives the meta object with `meta.stream`, a readable stream of the content. With `nostream` set to `true` the meta object comes without the stream. Errors: `File not found`, `Invalid file`, `File is expired` or an error of the file system. Without a callback the method returns a promise. Example: Pipe to a file ```js FILESTORAGE('documents').read(id, function(err, meta) { if (!err) meta.stream.pipe(F.Fs.createWriteStream(PATH.temp(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 | | `function(err, meta, filename, fd)`. | | `keepfd` | `Boolean` | no | `false` | Keep the file descriptor `fd` open; you must close it. | Returns: `FileStorage|Promise` The storage, or a promise with the meta object. Reads the header of the file. Dates come as `Date` objects. The callback also gets the path of the file on the disk. Unlike `fs.read()`, it does not check the expiration. Without a callback the method returns a promise. Example: Metadata ```js FILESTORAGE('documents').readmeta(id, function(err, meta) { console.log(meta.name, meta.type, meta.size); }); ``` ### fs.readbuffer(id, [callback]) Type: `method` Reads the content of a file into a Buffer. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `id` | `String` | yes | | The ID of the file. | | `callback` | `Function` | no | | `function(err, buffer, meta)`. | Returns: `FileStorage|Promise` The storage, or a promise with the buffer. Reads the whole file into memory. Use `fs.read()` for big files. Without a callback the method returns a promise. The promise gives only the buffer. Example: Buffer ```js var buffer = await FILESTORAGE('documents').readbuffer(id); ``` ### fs.readbase64(id, [callback]) Type: `method` Reads the content of a file as Base64. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `id` | `String` | yes | | The ID of the file. | | `callback` | `Function` | no | | `function(err, base64, meta)`. | Returns: `FileStorage|Promise` The storage, or a promise with the string. Reads the whole file and encodes it as a Base64 string. Without a callback the method returns a promise. The promise gives only the string. Example: Data URI ```js FILESTORAGE('photos').readbase64(id, 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 | | `function(err, value, meta)`. | Returns: `FileStorage` The storage. Reads a file saved by `fs.savejson()` and parses it. The callback is required. Example: Read settings ```js FILESTORAGE('data').readjson('settings', function(err, value) { console.log(value.theme); }); ``` ### fs.image(id, [callback]) Type: `method` Reads a stored picture as an Image. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `id` | `String` | yes | | The ID of the file. | | `callback` | `Function` | no | | `function(err, image, meta)`. | Returns: `FileStorage|Promise` The storage, or a promise with the image. Gives an `Image` object that reads the content of the file, so you can resize or convert it and save the result. Image processing needs GraphicsMagick or ImageMagick. Without a callback the method returns a promise. The promise gives only the image. Example: Thumbnail ```js FILESTORAGE('photos').image(id, function(err, image, meta) { if (err) return; image.resize(200, 200); image.save(PATH.temp('thumb_' + meta.name)); }); ``` ### fs.res(res, options, [checkmeta]) Type: `method` Sends a file to an HTTP response. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `res` | `Response` | yes | | The response object. | | `options` | `Object` | yes | | The options, see above. | | `checkmeta` | `Function` | no | | `function(meta)`; return `false` to answer with `404`. | Returns: `undefined` The method behind `controller.filefs()` and `controller.imagefs()`. `options`: `id` (the file), `download` (`true` for the stored name, a string, or `function(name, type)` that returns the name), `headers`, `done` (a callback), `nocompress`, and for images `image: true`, `make` (`function(image, res)`) and `cache` (default `true`). It supports `If-Modified-Since` (`304`) and `Range` requests (`206`). A missing or expired file, or `checkmeta(meta)` that returns `false`, gives `404`. Example: In a route with req and res ```js ROUTE('GET /files/{id}/', function(id) { FILESTORAGE('documents').res(this.res, { id: id, download: true }); }); ``` ### fs.copy(id, path, [callback]) Type: `method` · Since: `0.0.97` Copies the content of a file to the disk. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `id` | `String` | yes | | The ID of the file. | | `path` | `String` | yes | | A target file, or a folder. | | `callback` | `Function` | no | | `function(err, meta)`. | Returns: `FileStorage|Promise` The storage, or a promise with the meta object. Writes the content of the file (without the header) to `path`. A path with a dot is used as the file name; any other path is a folder and the file keeps its stored name. The folder must exist. Expired files give the error `File is expired`. Without a callback the method returns a promise. Example: Export to a folder ```js FILESTORAGE('documents').copy(id, PATH.temp(), function(err, meta) { console.log(PATH.temp(meta.name)); }); ``` Example: Export to a file ```js await FILESTORAGE('documents').copy(id, PATH.temp('invoice.pdf')); ``` ### fs.clone(id, [newid], [callback]) Type: `method` · Since: `0.0.99` Copies a file inside the storage under a new ID. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `id` | `String` | yes | | The ID of the file. | | `newid` | `String` | no | `UID()` | The ID of the copy. | | `callback` | `Function` | no | | `function(err, meta)`; `meta.id` is the new ID. | Returns: `FileStorage|Promise` The storage, or a promise with the meta object. Creates a copy of the file with the same metadata under `newid` and adds it to `files.log`. When the second argument is the callback, a new ID is generated with `UID()`. Expired files give the error `File is expired`. Without a callback the method returns a promise. In the promise form pass `newid`. Example: Clone ```js FILESTORAGE('documents').clone(id, function(err, meta) { console.log('Copy:', meta.id); }); ``` Example: Clone as a promise ```js var meta = await FILESTORAGE('documents').clone(id, UID()); ``` ### fs.move(id, newid, [callback]) Type: `method` Changes the ID of a file. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `id` | `String` | yes | | The ID of the file. | | `newid` | `String` | yes | | The new ID. | | `callback` | `Function` | no | | `function(err)`. | Returns: `FileStorage|Promise` The storage, or a promise. Moves the file to the name and folder of `newid`. `files.log` is not changed; call `fs.rebuild()` when you list files with `fs.browse()`. Without a callback the method returns a promise. Example: Move ```js FILESTORAGE('documents').move('draft', 'final', function(err) { console.log(err ? 'Error' : 'Moved'); }); ``` ### 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 (at most 250 characters). | | `callback` | `Function` | no | | `function(err, meta)`. | Returns: `FileStorage|Promise` The storage, or a promise with the meta object. Writes the new name into the header and into `files.log`. The content type stays the same. Without a callback the method returns a promise. Example: Rename ```js FILESTORAGE('documents').rename(id, 'contract-2024.pdf'); ``` ### 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 | | `function(err)`. | Returns: `FileStorage|Promise` The storage, or a promise. Deletes the file from the disk and from `files.log`. Without a callback the method returns a promise. Example: Remove ```js FILESTORAGE('documents').remove(id, function(err) { console.log(err ? 'Not found' : 'Removed'); }); ``` ### fs.browse([callback]) Type: `method` Lists files from files.log. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `callback` | `Function` | no | | `function(err, files)`. | Returns: `QueryBuilder` The query builder. Returns a NoSQL query builder over `files.log`, the database with the metadata of all files. Add conditions, sorting and paging, then `callback()`. Example: Latest images ```js FILESTORAGE('photos').browse().where('ext', 'jpg').sort('date_desc').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 | | `function(err, files)`. | Returns: `FileStorage|Promise` The storage, or a promise with the array. Reads the header of every file on the disk and returns their meta objects. Slower than `fs.browse()`, but it does not depend on `files.log`. Without a callback the method returns a promise. Example: All files ```js var files = await FILESTORAGE('photos').browse2(); console.log(files.length); ``` ### fs.stream(onfile, [callback], [workers]) Type: `method` Goes through all files on the disk one by one. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `onfile` | `Function` | yes | | `function(meta, next)`. | | `callback` | `Function` | no | | Runs when all files are processed. | | `workers` | `Number` | no | | How many files are processed at the same time. | Returns: `FileStorage` The storage. Calls `onfile(meta, next)` for every file; call `next()` to continue. `meta.index` is the order of the file. `callback` runs at the end. Example: Find big files ```js FILESTORAGE('documents').stream(function(meta, next) { if (meta.size > 1024 * 1024 * 10) console.log(meta.id, meta.name); next(); }, function() { console.log('Done'); }); ``` ### fs.count([callback]) Type: `method` Counts files and their size from files.log. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `callback` | `Function` | no | | `function(err, response)`. | Returns: `FileStorage` The storage. Gives an object with `count` (the number of files) and `size` (the total size in bytes), and updates `fs.total` and `fs.size`. Example: Count ```js FILESTORAGE('photos').count(function(err, response) { console.log(response.count, response.size); }); ``` ### fs.count2([callback]) Type: `method` Counts files on the disk. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `callback` | `Function` | no | | `function(err, count)`. | Returns: `FileStorage|Promise` The storage, or a promise with the number. Counts the files in the subfolders of the storage, without `files.log`. Without a callback the method returns a promise. Example: Count on disk ```js var count = await FILESTORAGE('photos').count2(); ``` ### fs.rebuild([callback]) Type: `method` Creates files.log again from the files on the disk. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `callback` | `Function` | no | | Runs when the log is written. | Returns: `FileStorage|Promise` The storage, or a promise. Reads all files with `fs.browse2()`, writes a new `files.log` and sets `fs.total` and `fs.size`. Use it after `fs.move()` or when `files.log` was lost. Without a callback the method returns a promise. Example: Rebuild ```js FILESTORAGE('photos').rebuild(function() { console.log('files.log is ready'); }); ``` ### fs.clean([callback]) Type: `method` Removes expired files. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `callback` | `Function` | no | | `function(err, count)`; `count` is the number of removed files. | Returns: `FileStorage|Promise` The storage, or a promise with the number. Finds files whose `expire` date has passed in `files.log` and deletes them. Without a callback the method returns a promise. Example: Clean every day ```js ON('service', function(counter) { if (counter % 1440 === 0) FILESTORAGE('temporary').clean(); }); ``` ### fs.clear([callback]) Type: `method` Removes all files. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `callback` | `Function` | no | | `function(err, count)`; `count` is the number of removed files. | Returns: `FileStorage|Promise` The storage, or a promise with the number. Deletes all files, their subfolders and `files.log`. While it runs, other reads and saves wait. Without a callback the method returns a promise. Alias: `fs.drop()`. Example: Clear ```js var count = await FILESTORAGE('temporary').clear(); ``` ### fs.drop([callback]) Type: `method` Alias of fs.clear(). | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `callback` | `Function` | no | | `function(err, count)`. | Returns: `FileStorage|Promise` The storage, or a promise with the number. The same method as `fs.clear()`. Example: Drop ```js FILESTORAGE('temporary').drop(); ``` ### fs.backup(filename, [callback]) Type: `method` Writes all files into one backup file. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `filename` | `String|Stream` | yes | | The target file or a writable stream. | | `callback` | `Function` | no | | `function(err, response)`; `response` has `filename`, `files` and `size`. | Returns: `FileStorage|Promise` The storage, or a promise with the response. Each file is compressed with GZIP and written as Base64. `filename` is a path or a writable stream. Without a callback the method returns a promise. Example: Backup ```js FILESTORAGE('photos').backup(PATH.temp('photos.backup'), function(err, response) { console.log(response.files, response.size); }); ``` ### fs.restore(filename, [callback]) Type: `method` Restores the storage from a backup file. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `filename` | `String` | yes | | The backup file. | | `callback` | `Function` | no | | `function(err, meta)`. | Returns: `FileStorage|Promise` The storage, or a promise. Removes all current files first (like `fs.clear()`), then unpacks the backup made by `fs.backup()`. Reads and saves wait until it ends. Without a callback the method returns a promise. Example: Restore ```js FILESTORAGE('photos').restore(PATH.temp('photos.backup'), function(err) { FILESTORAGE('photos').rebuild(); }); ``` ### fs.storage(directory) Type: `method` Changes the folder of the storage. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `directory` | `String` | yes | | The absolute path of the folder. | Returns: `FileStorage` The storage. Sets `fs.directory` and the path of `files.log` to another folder. Example: Another disk ```js FILESTORAGE('archive').storage('/mnt/archive/files/'); ``` ### fs.readfilename(id) Type: `method` Returns the path of a file on the disk. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `id` | `String` | yes | | The ID of the file. | Returns: `String` The absolute path. Returns the path of the `.file` for `id`. The file starts with a header of 2000 bytes, so it is not a copy of the original file; use `fs.copy()` for that. Example: Path ```js console.log(FILESTORAGE('photos').readfilename(id)); ``` ### controller.filefs(name, id, [download], [headers], [callback], [checkmeta]) Type: `method` Answers with a file from a storage. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `name` | `String` | yes | | The name of the storage. | | `id` | `String` | yes | | The ID of the file. | | `download` | `Boolean|String|Function` | no | | `true`, a file name, or `function(name, type)` that returns the name. | | `headers` | `Object` | no | | Extra response headers. | | `callback` | `Function` | no | | Runs when the file is sent. | | `checkmeta` | `Function` | no | | `function(meta)`; return `false` to answer with `404`. | Returns: `Controller` The controller. Sends the file `id` of `FILESTORAGE(name)` with its stored content type. `download` set to `true` uses the stored name, a string sets another name. `checkmeta(meta)` that returns `false` gives `404`. `Range` and `If-Modified-Since` requests are supported. The response object has the same method, `res.filefs()`. Example: Download ```js exports.install = function() { ROUTE('GET /download/{id}/', download); }; function download(id) { this.filefs('documents', id, true); } ``` ### controller.imagefs(name, id, make, [headers], [callback], [checkmeta]) Type: `method` Answers with a processed image from a storage. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `name` | `String` | yes | | The name of the storage. | | `id` | `String` | yes | | The ID of the file. | | `make` | `Function` | yes | | `function(image, res)` that changes the image. | | `headers` | `Object` | no | | Extra response headers. | | `callback` | `Function` | no | | Runs when the image is sent. | | `checkmeta` | `Function` | no | | `function(meta)`; return `false` to answer with `404`. | Returns: `Controller` The controller. Reads the picture `id` of `FILESTORAGE(name)`, calls `make(image, res)` to process it and sends the result. The processed image is cached in the temporary folder per URL. Needs GraphicsMagick or ImageMagick. The response object has the same method, `res.imagefs()`. Example: Thumbnail ```js exports.install = function() { ROUTE('GET /thumbnails/{id}/', thumbnail); }; function thumbnail(id) { this.imagefs('photos', id, function(image) { image.resizeCenter(200, 200); image.quality(80); }); } ``` ### file.fs(storage, id, [custom], [expire], [callback]) Type: `method` Saves an uploaded file into a storage. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `storage` | `String` | yes | | The name of the storage. | | `id` | `String` | yes | | The ID of the file. | | `custom` | `Object` | no | | Any data kept with the file. | | `expire` | `String` | no | | An expiration period. | | `callback` | `Function` | no | | `function(err, meta)`. | Returns: `FileStorage|Promise` The storage, or a promise with the meta object. A method of every file in `controller.files`. It calls `FILESTORAGE(storage).save()` with the original file name and the temporary file of the upload. Without a callback it returns a promise. Example: Upload ```js exports.install = function() { ROUTE('POST /api/upload/', upload, ['upload'], 1024 * 5); }; async function upload() { var file = this.files[0]; var meta = await file.fs('documents', UID(), { user: this.user.id }); this.json({ id: meta.id, name: meta.name }); } ``` --- title: Operations and tasks project: Total.js V4 version: 0.0.99 section: reference language: en license: MIT url: https://totaljs.es/docs/total-js-v4/0-0-99/reference/operations-and-tasks/ updated: 2026-11-16T15:41:15.818Z --- # Operations and tasks > Global functions and the $ object of operations and tasks, plus commands, extensions and PROMISIFY(). Operations (`NEWOPERATION()`, `OPERATION()`, `RUN()`) and tasks (`NEWTASK()`, `TASK()`) hold business logic outside of routes. Both receive a `$` object; this page lists its properties and methods, and also commands, extensions and `PROMISIFY()`. The guide [Operations and tasks](../../guides/operations-and-tasks/) explains how to use them with examples; this page is the exact reference. ## API ### NEWOPERATION(name, fn, [repeat], [stop], [binderror], [filter]) Type: `method` Registers an operation. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `name` | `String` | yes | | Name of the operation. | | `fn` | `Function($, value)` | yes | | The operation. `null` removes it. | | `repeat` | `Number` | no | | How many times to run the operation again when it ends with an error. | | `stop` | `Boolean` | no | `true` | Stops a `RUN()` chain when this operation fails. | | `binderror` | `Boolean` | no | `false` | In a `RUN()` chain, stores the error output as the response of this operation. | | `filter` | `String` | no | | Schema for the query string, used by `$.filter`. | The function receives `$` and the value. It must end with `$.callback()`, `$.success()`, `$.invalid()` or another method that calls the callback. A boolean in place of `repeat` is read as `stop`, and a string in any optional position is read as `filter`. Calling `NEWOPERATION(name, null)` removes the operation. Put operations in the `/operations/` directory. Example: An operation ```js NEWOPERATION('users_count', function($, value) { NOSQL('users').count().callback(function(err, count) { if (err) $.invalid(err); else $.callback(count); }); }); ``` Example: Repeat after an error ```js NEWOPERATION('ping', function($) { RESTBuilder.GET('https://example.com/ping').callback($.done()); }, 3); ``` ### OPERATION(name, [value], callback, [options], [controller]) Type: `method` Runs one operation. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `name` | `String` | yes | | Name of the operation, or a URL of a remote operation. | | `value` | `Object` | no | `{}` | Value for `$.value`. | | `callback` | `Function(err, response, options)` | yes | | Called when the operation ends. | | `options` | `Object` | no | | Custom options, available as `$.options`. | | `controller` | `Controller` | no | | Controller of the current request, or a `$` object. | The callback receives `err` (an `ErrorBuilder` or `null`), the response and `options`. When `value` is a function, it is the callback and the value is an empty object. A controller or a `$` object passed as `options` is used as the controller. A missing operation ends with the error `Operation "name" not found.` The name can also be a URL with an optional expiration, for example `'https://example.com/op.js <5 minutes>'` (`once` and `asap` are accepted too). The file is downloaded, compiled and cached until it expires. It can contain a `NEWOPERATION()` declaration or a module with `exports.install`, `exports.make` or `exports.exec`. Example: Call an operation ```js OPERATION('users_count', function(err, response) { console.log(err, response); }); ``` Example: From a route ```js exports.install = function() { ROUTE('GET /api/users/count/', count); }; function count() { var self = this; OPERATION('users_count', self.query, self.callback(), self); } ``` ### RUN(names, [value], callback, [options], [controller], [response_name]) Type: `method` Runs several operations one after another. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `names` | `String|Array` | yes | | Operation names, separated by commas. | | `value` | `Object` | no | `{}` | Shared value for `$.value`. | | `callback` | `Function(err, response, $)` | yes | | Called when the chain ends. | | `options` | `Object` | no | | Custom options, available as `$.options`. | | `controller` | `Controller` | no | | Controller of the current request. | | `response_name` | `String` | no | | Name of the operation whose response is returned alone. | `names` is a comma-separated string or an array. All operations share one `$` and one `$.value`. The callback receives `err`, the response and the `$` object. The response has one key per operation; with `response_name` it is only the response of that operation. When an operation fails and its `stop` option is `true` (the default), the chain stops. Names that do not exist are skipped. A string in place of `options` or `controller` is read as `response_name`. Example: Chain two operations ```js RUN('check, save', { email: 'peter@example.com' }, function(err, response) { // response.check, response.save console.log(err, response); }); ``` Example: Return one response ```js function create() { var self = this; RUN('check, save', self.body, self.callback(), null, self, 'save'); } ``` ### EACHOPERATION(fn) Type: `method` Calls a function for each registered operation. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `fn` | `Function(name)` | yes | | Called with the name of each operation. | The function receives the name of each operation. Example: List operations ```js EACHOPERATION(function(name) { console.log(name); }); ``` ### $.value Type: `property` The value passed to the operation. Returns: `Object` `$.model` is the same value. In a `RUN()` chain, every operation shares this object, so changes are visible to the next operations. Example: Read the value ```js NEWOPERATION('greet', function($) { $.callback('Hello ' + $.value.name); }); ``` ### $.options Type: `property` The options passed to `OPERATION()` or `RUN()`. Returns: `Object` An empty object when no options were passed. `OPERATION()` passes it again as the third argument of the callback. Example: Use options ```js NEWOPERATION('export', function($) { $.callback({ format: $.options.format || 'json' }); }); OPERATION('export', {}, console.log, { format: 'csv' }); ``` ### $.name Type: `property` Name of the running operation. Returns: `String` In a `RUN()` chain it changes with each operation. Example: Log the name ```js NEWOPERATION('sync', function($) { console.log('Running', $.name); $.success(); }); ``` ### $.error Type: `property` The `ErrorBuilder` of the operation. Returns: `ErrorBuilder` `$.invalid()` pushes errors here. In a `RUN()` chain, each operation gets a new `ErrorBuilder`. Example: Push several errors ```js NEWOPERATION('validate', function($) { !$.value.name && $.error.push('name'); !$.value.email && $.error.push('email'); $.callback(); }); ``` ### $.controller Type: `property` The controller passed to the operation, or `undefined`. Returns: `Controller` `$.client` is the same value. Request properties of `$` read from this controller. Example: Check for a controller ```js NEWOPERATION('whoami', function($) { if ($.controller) $.callback($.user); else $.invalid('401'); }); ``` ### $.user Type: `property` The user of the current request. Returns: `Object` Read from the controller, or `null` without a controller. The other request properties work the same way: `$.session`, `$.sessionid`, `$.language`, `$.ip`, `$.id`, `$.req`, `$.res`, `$.url`, `$.uri`, `$.path`, `$.split`, `$.params`, `$.query`, `$.body`, `$.files`, `$.headers`, `$.ua`, `$.mobile` and `$.test`. Example: Use the user and the query ```js NEWOPERATION('my_orders', function($) { NOSQL('orders').find().where('userid', $.user.id).take($.query.take || 20).callback($.callback); }); ``` ### $.filter Type: `property` The query string converted by the `filter` schema of the operation. Returns: `Object` The schema is the `filter` argument of `NEWOPERATION()`, for example `'page:Number,q:String'`. Without a schema it returns the raw query. Without a controller it returns an empty object. Example: Typed query ```js NEWOPERATION('products', function($) { var filter = $.filter; $.callback({ page: filter.page, q: filter.q }); }, 'page:Number,q:String'); ``` ### $.callback([value]) Type: `method` Ends the operation and returns a value. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `value` | `Object` | no | | The response, or an error. | Returns: `$` An `Error` or an `ErrorBuilder` with errors is pushed to `$.error`. You can also call it as `$.callback(err, value)`. When the operation has errors and `repeat` left, it runs again instead. Example: Return a value ```js NEWOPERATION('now', function($) { $.callback(NOW); }); ``` Example: Pass it as a callback ```js NEWOPERATION('users', function($) { NOSQL('users').find().callback($.callback); }); ``` ### $.success([success], [value]) Type: `method` Ends the operation with a success object. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `success` | `Boolean` | no | `true` | The success flag. | | `value` | `Object` | no | | A value added as `value`. | Returns: `$` Returns `{ success: true }` to the callback. `$.success(value)` adds `value`. `$.success(false)` sets `success` to `false`. In a `RUN()` chain, empty keys are left out. Example: Return the new id ```js NEWOPERATION('contact_save', function($) { var id = UID(); $.value.id = id; NOSQL('contacts').insert($.value).callback(function() { $.success(id); }); }); ``` ### $.invalid([name], [error], [path], [index]) Type: `method` Ends the operation with an error. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `name` | `String|Error` | no | | Error name, error message or `Error`. | | `error` | `String` | no | | Error message. | | `path` | `String` | no | | Path of the field. | | `index` | `Number` | no | | Index of the item in an array. | Returns: `$|Function` The arguments go to `$.error.push()`. Without arguments it returns a function `function(err)` that you can pass as a callback. Example: Return an error ```js NEWOPERATION('login', function($) { if (!$.value.email) { $.invalid('email', 'Email is required'); return; } $.success(); }); ``` ### $.done([arg]) Type: `method` Returns a callback that ends the operation with a success object. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `arg` | `Boolean|Object` | no | | `true` adds the response; another value is added as it is. | Returns: `Function(err, response)` The returned function `function(err, response)` pushes `err` and calls back, or calls back with `{ success: true }`. With `arg` set to `true`, the response is added as `value`; any other `arg` is added instead of the response. Example: Return the inserted record ```js NEWOPERATION('save', function($) { NOSQL('contacts').insert($.value).callback($.done(true)); }); ``` ### $.successful(callback) Type: `method` Returns a callback that handles errors for you. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `callback` | `Function(a, b, c)` | yes | | Called when there is no error. | Returns: `Function(err, a, b, c)` The returned function `function(err, a, b, c)` calls `$.invalid(err)` when there is an error, otherwise it calls `callback(a, b, c)` with `$` as `this`. Example: Skip error checks ```js NEWOPERATION('count', function($) { NOSQL('users').count().callback($.successful(function(count) { $.callback({ count: count }); })); }); ``` ### $.redirect(url) Type: `method` Ends the operation with a redirect. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `url` | `String` | yes | | Target URL. | Returns: `$` When the operation was called with `controller.callback()`, the controller redirects to `url`. Example: Redirect after logout ```js NEWOPERATION('logout', function($) { $.cookie('session', null); $.redirect('/'); }); ``` ### $.noop([nocustomresponse]) Type: `method` Ends the operation without calling the callback. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `nocustomresponse` | `Boolean` | no | `false` | `true` does not call `controller.custom()`. | Returns: `$` Use it when the operation answers the request itself. By default it also calls `controller.custom()`, so the framework does not send another response; `true` skips that call. Example: Answer the request yourself ```js NEWOPERATION('ping', function($) { $.controller.plain('pong'); $.noop(true); }); ``` ### $.cookie(name, [value], [expire], [options]) Type: `method` Reads or writes a cookie of the current request. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `name` | `String` | yes | | Cookie name. | | `value` | `String` | no | | New value, or `null` to remove it. | | `expire` | `String|Date` | no | | Expiration, for example `'1 day'`. | | `options` | `Object` | no | | Cookie options. | Returns: `String|$` With only `name` it returns the cookie value. `null` as `value` removes the cookie. Needs a controller. Example: Write a cookie ```js NEWOPERATION('remember', function($) { $.cookie('lang', $.value.lang, '1 year'); $.success(); }); ``` ### $.variables(str, [data]) Type: `method` Replaces `{key}` placeholders in a string. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `str` | `String` | yes | | Text with placeholders. | | `data` | `Object` | no | | Values for `{data.key}`. | Returns: `String` Supported keys start with `user.`, `data.`, `model.` or `value.`, `query.` and `params.`. Unknown keys are kept. Single or double braces work. It exists on the `$` of operations and tasks. Example: Build a message ```js NEWOPERATION('notify', function($) { var text = $.variables('Hello {user.name}, order {data.id} is ready.', { id: $.value.id }); $.callback(text); }); ``` ### $.audit([message], [type]) Type: `method` Writes an audit log entry for the operation. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `message` | `String` | no | | Audit message. | | `type` | `String` | no | | Type of the entry. | Returns: `$` Calls `AUDIT($, message, type)` with data from the user, the request and the value. It exists on the `$` of operations and tasks. Example: Audit a change ```js NEWOPERATION('remove', function($) { $.audit('Removed product ' + $.value.id); $.success(); }); ``` ### $.response Type: `property` Results of the previous operations in a `RUN()` chain. Returns: `Object` An object with one key per operation that has already ended. Only set inside `RUN()`. Example: Use a previous result ```js NEWOPERATION('invoice', function($) { var order = $.response.order; $.callback({ total: order.value.price }); }); ``` ### $.meta Type: `property` Information about a `RUN()` chain. Returns: `Object` `$.meta.items` is the list of names, `$.meta.current` the running operation, `$.meta.prev` the previous one and `$.meta.index` the index of the running operation. Only set inside `RUN()`. Example: Check the previous operation ```js NEWOPERATION('save', function($) { if ($.meta.prev !== 'check') { $.invalid('check'); return; } $.success(); }); ``` ### $.repeated Type: `property` How many times the running operation was repeated in a `RUN()` chain. Returns: `Number` Starts at `0` for each operation and grows each time the `repeat` option runs it again. Only set inside `RUN()`. Example: Give up early ```js NEWOPERATION('fetch', function($) { if ($.repeated > 1) console.log('Second retry'); RESTBuilder.GET('https://example.com/data').callback($.callback); }, 3); ``` ### NEWTASK(name, fn) Type: `method` Declares a task with named steps. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `name` | `String` | yes | | Name of the task. | | `fn` | `Function(push)` | yes | | Declares the steps with `push(step, fn($, value))`. `null` removes the task. | `fn` receives `push(step, fn)`. Each step receives `$` and the value, and `this` is `$`. `NEWTASK(name, null)` removes the task. Put tasks in the `/tasks/` directory. Example: A task with two steps ```js NEWTASK('signup', function(push) { push('check', function($, value) { if (!value.email) { $.invalid('email'); return; } $.next('save'); }); push('save', function($, value) { NOSQL('users').insert(value).callback($.done()); }); }); ``` ### TASK(name, step, callback, [options], [value]) Type: `method` Creates a task and starts it at a step. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `name` | `String` | yes | | Name of the task, or `'name/step'`. | | `step` | `String` | yes | | The first step. | | `callback` | `Function(err, response)` | yes | | Called when the task ends. | | `options` | `Controller|Object` | no | | Controller or `$` object, or the value. | | `value` | `Object` | no | `{}` | Value for `$.value`. | Returns: `TaskBuilder` The task, `$`. `name` and `step` can be one string `'name/step'`; then the arguments are `TASK('name/step', callback, [options], [value])`. A controller or the `$` of a schema, operation or task as `options` shares its request and its errors; any other `options` is used as the value. The step starts on the next tick, so you can add steps with `$.push()` first. Without a step, start it with `$.exec()`. The name can also be a URL with an optional expiration, for example `'https://example.com/task.js <1 hour>'`. The file is downloaded and cached until it expires. Example: Run a task ```js TASK('signup', 'check', function(err, response) { console.log(err, response); }, { email: 'peter@example.com' }); ``` Example: From a schema action, with "name/step" ```js TASK('signup/check', $.callback, $, $.model); ``` ### $.next(step, [step2], [...]) Type: `method` Runs the next step of the task. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `step` | `String` | yes | | Name of the step. More names are tried in order. | Returns: `$` Runs the first step in the list that exists, first in steps added with `$.push()` and then in the task declaration. When none exists, the task ends. Does nothing after the task ended. Example: Go to the next step ```js push('check', function($, value) { $.next(value.paid ? 'ship' : 'pay'); }); ``` ### $.next2([step]) Type: `method` Returns a callback that goes to the next step. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `step` | `String` | no | | Name of the next step. | Returns: `Function(err)` The returned function `function(err)` calls `$.invalid(err)` on an error, otherwise it runs `step`, or ends the task when `step` is empty. Example: Continue after a write ```js push('save', function($, value) { NOSQL('orders').insert(value).callback($.next2('notify')); }); ``` ### $.end([data]) Type: `method` Ends the task. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `data` | `Object` | no | `$.value` | The response. | Returns: `$` Calls the task callback with the errors (or `null`) and `data`, or `$.value` when `data` is empty. Example: End with the value ```js push('price', function($, value) { value.total = value.price * value.count; $.end(); }); ``` ### $.end2([send_value]) Type: `method` Returns a callback that ends the task. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `send_value` | `Boolean` | no | `false` | `true` returns the data of the callback. | Returns: `Function(err, data)` The returned function `function(err, data)` calls `$.invalid(err)` on an error, otherwise it ends the task with `data` when `send_value` is `true`, or with `$.value`. Example: End with the result ```js push('load', function($, value) { NOSQL('orders').one().where('id', value.id).callback($.end2(true)); }); ``` ### $.success([data]) Type: `method` Ends the task with a success object. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `data` | `Object` | no | | A value added as `value`. | Returns: `$` Ends the task with `{ success: true }`, plus `value` when `data` is set. Example: End with success ```js push('notify', function($, value) { MAIL(value.email, 'Order', '=?/mails/order', value); $.success(value.id); }); ``` ### $.done([send_value]) Type: `method` Returns a callback that ends the task with a success object. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `send_value` | `Boolean` | no | `false` | `true` adds the data of the callback as `value`. | Returns: `Function(err, data)` The returned function `function(err, data)` calls `$.invalid(err)` on an error, otherwise it ends the task with `{ success: true }`, plus `value: data` when `send_value` is `true`. Example: Save and finish ```js push('save', function($, value) { NOSQL('orders').insert(value).callback($.done(true)); }); ``` ### $.invalid(err, [msg]) Type: `method` Ends the task with an error. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `err` | `String|Error` | yes | | Error name or `Error`. | | `msg` | `String` | no | | Error message. | Returns: `$` Pushes the error to `$.error` and ends the task. Does nothing after the task ended. Example: Stop the task ```js push('check', function($, value) { if (!value.items.length) $.invalid('items', 'The order is empty'); else $.next('save'); }); ``` ### $.push(step, fn) Type: `method` Adds a step to this task only. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `step` | `String` | yes | | Name of the step. | | `fn` | `Function($, value)` | yes | | The step. | Returns: `$` The step is used before a step of the same name in the task declaration. Call it on the task that `TASK()` returns, before the first step runs. Example: Override a step ```js var task = TASK('signup', 'check', console.log, { email: 'peter@example.com' }); task.push('save', function($, value) { $.success(); }); ``` ### $.exec(step, [callback]) Type: `method` Starts the task at a step. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `step` | `String` | yes | | The first step. | | `callback` | `Function(err, response)` | no | | Called when the task ends. | Returns: `$` Sets the callback when given and runs `step`. Use it with a task created by `TASK(name)` without a step. Example: Start later ```js var task = TASK('signup'); task.value = { email: 'peter@example.com' }; task.exec('check', console.log); ``` ### $.callback(fn) Type: `method` Sets the callback of the task. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `fn` | `Function(err, response)` | yes | | The callback. | Returns: `$` `fn` is called once when the task ends, with the errors (or `null`) and the response. Example: Set the callback ```js var task = TASK('signup'); task.callback(function(err, response) { console.log(err, response); }); task.exec('check'); ``` ### $.value Type: `property` The value shared by all steps of the task. Returns: `Object` `$.model` is the same value. Steps also receive it as the second argument. It is an empty object when no value was passed. Example: Change the value ```js push('price', function($) { $.value.price = 100; $.next('save'); }); ``` ### $.current Type: `property` Name of the running step. Returns: `String` `$.prev` holds the previous step and `$.name` the name of the task. The request properties (`$.user`, `$.query`, `$.params`, `$.body` and others) read from the controller, like in operations. Example: Log the step ```js push('save', function($) { console.log($.name, $.prev, '->', $.current); $.success(); }); ``` ### PROMISIFY(fn, [a], [b]) Type: `method` · Since: `0.0.97` Wraps a function with a callback in a Promise. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `fn` | `Function` | yes | | A function whose last argument is `callback(err, response)`. | | `a` | `Object` | no | | First argument for `fn`. | | `b` | `Object` | no | | Second argument for `fn`. | Returns: `Promise` Calls `fn` with the given arguments and a callback `function(err, response)` as the last argument. The promise resolves with `response` or rejects with `err`. Empty arguments are not passed. Example: Await a callback ```js async function count() { var self = this; try { var response = await PROMISIFY(OPERATION, 'users_count'); self.json(response); } catch (err) { self.invalid(err); } } ``` Example: Read a file ```js var body = await PROMISIFY(F.Fs.readFile, PATH.root('readme.md'), 'utf8'); ``` ### NEWCOMMAND(name, fn) Type: `method` Adds a handler for a command. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `name` | `String` | yes | | Name of the command. | | `fn` | `Function(a, b, c, d)` | yes | | The handler. `null` removes all handlers. | A command can have several handlers; each call adds one. `NEWCOMMAND(name, null)` removes all handlers of the command. Run it with `CMD()`. Example: A command ```js NEWCOMMAND('clear_prices', function(category) { MAIN.prices && delete MAIN.prices[category]; }); ``` ### CMD(name, [a], [b], [c], [d]) Type: `method` Runs all handlers of a command. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `name` | `String` | yes | | Name of the command. | | `a` | `Object` | no | | First argument. | | `b` | `Object` | no | | Second argument. | | `c` | `Object` | no | | Third argument. | | `d` | `Object` | no | | Fourth argument. | Passes up to four arguments to each handler. Does nothing when the command has no handler. Built-in commands include `clear_viewscache`, `clear_smtpcache` and `refresh_tms`. Example: Run a command ```js CMD('clear_prices', 'books'); CMD('clear_viewscache'); ``` ### CMD2(name, [a], [b], [c], [d]) Type: `method` Returns a function that runs a command. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `name` | `String` | yes | | Name of the command. | | `a` | `Object` | no | | First argument. | | `b` | `Object` | no | | Second argument. | | `c` | `Object` | no | | Third argument. | | `d` | `Object` | no | | Fourth argument. | Returns: `Function` The returned function runs all handlers with the given arguments. When the command has no handler, it returns `NOOP`. Example: Run a command later ```js setTimeout(CMD2('clear_viewscache'), 5000); ``` ### NEWEXTENSION(code, [callback], [extend]) Type: `method` Installs an extension from source code or a URL. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `code` | `String` | yes | | Source code, or a URL. | | `callback` | `Function(err, module)` | no | | Called when the extension is installed. | | `extend` | `Function(module)` | no | | Called with the module before it is installed. | `code` is JavaScript that sets `exports`, or a URL to download it from. Optional exports: `id`, `name`, `install(next)`, `make()`, `done()` and `uninstall()`. Without `id` the id is a hash of `name` or the code. An extension with the same id is removed first. The code can also be HTML with a `<script total>` block and `<file name="...">` blocks; `exports.files` then maps each file name to a temporary path. The added `remove()` method uninstalls the extension. Files in the `/extensions/` directory are installed when the app starts. Example: Install from a string ```js var code = 'exports.name = \'Hello\';\nexports.make = function() {\n\tROUTE(\'GET /hello/\', function() { this.plain(\'Hello\'); });\n};'; NEWEXTENSION(code, function(err, module) { console.log(err, module.id); }); ``` Example: Install from a URL ```js NEWEXTENSION('https://example.com/extension.js', function(err, module) { err && console.error(err); }); ``` ### WORKFLOW(declaration, [tasks]) Type: `method` Creates a small in-memory state machine: named steps that move to each other with `$.next()`. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `declaration` | `Function` | yes | | `function($)` that adds the steps. | | `tasks` | `Object` | no | `{}` | Steps as `{ name: function($, value) }`. | Returns: `Object` The workflow `$`. `WORKFLOW()` returns a `$` object and passes it to `declaration($)`, where you add steps with `$.push(name, fn)`. Each step is `function($, value)`. It is a local helper, not a registered task: nothing is stored or named globally. | Member | What it does | | --- | --- | | `$.push(name, fn)` | Adds the step `fn($, value)` | | `$.next(name, [value])` | Runs the step `name` with `value`; `$.trigger()` is an alias. An unknown name destroys the workflow | | `$.next2(name)` | Returns `function(value)` that runs `$.next(name, value)`, for callbacks | | `$.invalid(err)` | Calls `$.error(err, $)` when you set it, then destroys the workflow | | `$.current`, `$.prev` | The name of the current and of the previous step | | `$.tasks` | The steps, as an object | | `$.clone()` | A new workflow with the same steps | | `$.destroy()` | Ends it; later calls of `$.next()` do nothing | `declaration` can be `null` when you pass the steps as `tasks`. Example: Steps in order ```js var flow = WORKFLOW(function($) { $.error = function(err) { console.log('Error:', err); }; $.push('load', function($, id) { NOSQL('orders').one().where('id', id).callback(function(err, order) { if (order) $.next('send', order); else $.invalid('error-orders-404'); }); }); $.push('send', function($, order) { MAIL(order.email, 'Your order', 'mails/order', order); $.destroy(); }); }); flow.next('load', '123'); ``` --- title: Utilities project: Total.js V4 version: 0.0.99 section: reference language: en license: MIT url: https://totaljs.es/docs/total-js-v4/0-0-99/reference/utilities/ updated: 2026-11-16T15:41:15.818Z --- # Utilities > The functions of U (utils.js) and the global helpers and objects of the framework. Total.js defines helpers in the global scope and in the object `U` (`Utils`), so every file of an app can use them without `require()`. The guide [Utilities](../../guides/utilities/) explains how to use them with examples; this page is the exact reference. ## API ### U Type: `property` The utility library of the framework (`utils.js`). Returns: `Object` `U`, `Utils` and `utils` are the same object. It is global, so you use it in controllers, schemas, modules and plugins without `require()`. Example: Use a helper ```js var ext = U.getExtension('photo.JPG'); // 'jpg' ``` ### Total Type: `property` · Since: `0.0.96` A global alias of the framework instance `F`. Returns: `Framework` `Total`, `F` and `framework` refer to the same object. Example: Same object ```js console.log(Total === F); // true ``` ### NOW Type: `property` A `Date` that the framework refreshes regularly. Returns: `Date` Reading `NOW` is cheaper than `new Date()`. The framework sets it again in its internal intervals (about every minute) and in some calls, such as `LOGGER()`. Use it where a precision of a minute is enough; use `new Date()` for an exact time. `F.datetime` reads and writes the same value. Example: Timestamp of a record ```js var model = { id: UID(), dtcreated: NOW }; ``` ### EMPTYOBJECT Type: `property` A frozen empty object. Returns: `Object` Use it as a default value that is never modified. It is frozen, so assignments to it have no effect. Example: Default options ```js function send(options) { options = options || EMPTYOBJECT; return options.timeout || 5000; } ``` ### EMPTYARRAY Type: `property` A frozen empty array. Returns: `Array` Use it as a default value that is never modified. It is frozen, so `push()` throws an error. Example: Default list ```js var items = response.items || EMPTYARRAY; ``` ### NOOP() Type: `method` An empty function. Returns: `undefined` Pass it where a callback is required and you do not need the result. Example: Ignore a callback ```js Fs.unlink(PATH.temp('export.csv'), NOOP); ``` ### MAIN Type: `property` An empty global object for your own shared data. Returns: `Object` The framework creates `MAIN = {}` and does not use it. Store application-wide values in it, for example data loaded at start. Example: Shared settings ```js // definitions/init.js MAIN.settings = { currency: 'EUR' }; // any other file var currency = MAIN.settings.currency; ``` ### REPO Type: `property` An empty global object for your own repository of values. Returns: `Object` The framework creates `REPO = {}` and does not use it. It is a second namespace like `MAIN`. Example: Cache a list ```js REPO.countries = ['SK', 'CZ', 'AT']; ``` ### FUNC Type: `property` An empty global object for your own shared functions. Returns: `Object` The framework creates `FUNC = {}`. Put helpers there that several files of the app call. Example: Shared function ```js // definitions/func.js FUNC.price = function(value) { return value.format(2) + ' EUR'; }; // a controller or a schema var text = FUNC.price(12.5); ``` ### TEMP Type: `property` A global object for temporary data that the framework clears. Returns: `Object` The framework replaces `TEMP` with a new empty object in its periodic cleanup (every `CONF.default_interval_clear_cache` minutes, 10 by default). Do not keep anything there that you need later. Example: Short-lived value ```js if (!TEMP.stats) TEMP.stats = compute(); ``` ### MODS Type: `property` All loaded modules by their name. Returns: `Object` The same object as `F.modules`. A key is the name of the file in `/modules/` (or the `id` the module exports). Example: List modules ```js Object.keys(MODS).forEach(function(name) { console.log(name); }); ``` ### MODULE(name) Type: `method` Returns a loaded module. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `name` | `String` | yes | | Name of the module. | Returns: `Object` The module, or `null`. Reads `F.modules[name]`. The result is the `exports` of the module file, or `null` when no module of that name is loaded. Example: Call a module ```js // modules/mailer.js exports.send = function(email) { /* ... */ }; // anywhere MODULE('mailer').send('info@example.com'); ``` ### LOGGER(name, value1, [value2], [...]) Type: `method` Appends a line to a log file in the `/logs/` directory. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `name` | `String` | yes | | Name of the log file without `.log`. | | `value` | `Object` | yes | | One or more values to write. | Returns: `undefined` The line is `yyyy-MM-dd HH:mm:ss | values` in the file `{name}.log`. Values are separated by a space; objects are formatted with `util.inspect()`. The directory is created when it does not exist, and writes go through `U.queue()` with at most 5 writes at the same time. Example: Log a payment ```js LOGGER('payments', 'order', order.id, 'paid', order.price); // logs/payments.log: // 2021-03-01 10:22:05 | order 1a2b3c paid 39.9 ``` ### PROMISIFY(fn, [a], [b], [c]) Type: `method` · Since: `0.0.97` Calls a callback-style function and returns a Promise. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `fn` | `Function` | yes | | A function that takes a callback as its last argument. | | `a` | `Object` | no | | First argument. | | `b` | `Object` | no | | Second argument. | | `c` | `Object` | no | | Third argument. | Returns: `Promise` `fn` is called with the given arguments and a callback `function(err, response)` as the last argument. The Promise rejects with `err` or resolves with `response`. Up to three arguments are supported; arguments that are `undefined` are not passed. Example: Read a file ```js var Fs = require('fs'); var content = await PROMISIFY(Fs.readFile, PATH.root('readme.md'), 'utf8'); ``` Example: Your own function ```js function load(id, callback) { callback(null, { id: id }); } var item = await PROMISIFY(load, '123'); ``` ### 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` | yes | | `function(err, success)`. | | `timeout` | `Number` | no | `5000` | Maximum time in ms. | | `interval` | `Number` | no | `500` | Time between checks in ms. | Returns: `undefined` `validator()` is checked at once and then every `interval` ms. When it returns `true`, `callback(null, true)` is called. When `timeout` ms pass first, `callback(Error('Timeout'), false)` is called. Example: Wait for a connection ```js WAIT(function() { return MAIN.db != null; }, function(err) { if (err) console.log('Database is not ready'); else console.log('Ready'); }, 10000); ``` ### UID([type], [date]) Type: `method` Creates a short unique identifier. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `type` | `String` | no | | A name of an independent counter. | | `date` | `Date` | no | `NOW` | The time encoded in the ID. | Returns: `String` The ID is a time-based string, for example `24j0y001xn51d`, which sorts by the time it was created. It is unique within the running instance (the framework adds a random instance key). `type` keeps a separate counter for each type, so IDs of different collections do not share a sequence. `date` creates the ID for another time. `CONF.default_uid` selects the version: `r` gives a random ID (`UIDR()`), `f` a base-62 variant; the default is the `d` version. Example: A new record ```js var model = {}; model.id = UID(); model.dtcreated = NOW; ``` Example: Counter per type ```js var orderid = UID('orders'); var invoiceid = UID('invoices'); ``` ### UID16([type], [date]) Type: `method` Creates a unique identifier with the time part in base 16. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `type` | `String` | no | | A name of an independent counter. | | `date` | `Date` | no | `NOW` | The time encoded in the ID. | Returns: `String` Works like `UID()` but encodes the time in hexadecimal, so the ID is a little longer (version `c`). It ignores `CONF.default_uid`. Example: Hex-based ID ```js var id = UID16(); // e.g. '367b52002xn60c' ``` ### GUID([length]) Type: `method` Creates a GUID or a random string of a given length. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `length` | `Number` | no | | Length of a random string. | Returns: `String` Without `length` it returns a string in the UUID form `xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx` built from the current time and random numbers. With `length` it returns random lowercase letters and digits of that length. Also available as `U.GUID()`. Example: UUID form ```js var id = GUID(); // '1a1defc8-efc8-2c86-8d36-938350b51dfd' ``` Example: Random token ```js var token = GUID(30); ``` ### CLONE(obj, [skip], [skipFunctions]) Type: `method` Creates a deep copy of an object or an array. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `obj` | `Object` | yes | | The object or array to copy. | | `skip` | `Object` | no | | Keys to leave out, as `{ key: true }`. | | `skipFunctions` | `Boolean` | no | `false` | Leaves out functions. | Returns: `Object` A new object. Nested objects and arrays are copied; `Date` and `Error` values are kept by reference, and Buffers are copied. `skip` is an object of keys to leave out (`{ password: 1 }`) on the first level of objects. Also available as `U.clone()`. Example: Copy without a key ```js var copy = CLONE(user, { password: 1 }); copy.name = 'Peter'; // user.name is unchanged ``` ### COPY(source, [target]) Type: `method` Copies all properties of `source` to `target`. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `source` | `Object` | yes | | Object to read. | | `target` | `Object` | no | | Object to write. | Returns: `Object` The target. Every key of `source` is cloned into `target`, also keys that `target` does not have. Without `target` it returns a new copy of `source`. It is `U.copy(source, target, true)`. Example: Merge ```js var target = { a: 0 }; COPY({ a: 1, z: 9 }, target); // target: { a: 1, z: 9 } ``` ### HASH(value, [type]) Type: `method` Creates a hash of a string. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `value` | `String` | yes | | The text. | | `type` | `String` | no | | A hash algorithm. | Returns: `Number|String` Without `type` it returns a fast numeric hash (unsigned 32-bit). `type` can be `md5`, `sha1`, `sha256`, `sha512`, `crc32` or `crc32unsigned`. It calls `value.hash()`. Example: Numeric and MD5 ```js HASH('abc'); // 96354 HASH('abc', 'md5'); // '900150983cd24fb0d6963f7d28e17f72' ``` ### QUERIFY([url], obj) Type: `method` Adds an object to a URL as a query string. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `url` | `String` | no | | The URL. | | `obj` | `Object` | yes | | Values of the query string. | Returns: `String` Values that are `null` or `undefined` are left out; dates become ISO strings and arrays are joined with commas. Keys and values are encoded. The URL can start with a method (`GET /api/`); the query is added to the path. Without a URL it returns only `?key=value`. Example: Build a URL ```js QUERIFY('GET /api/products/', { page: 2, q: 'a b' }); // 'GET /api/products/?page=2&q=a%20b' QUERIFY({ page: 1 }); // '?page=1' ``` ### DIFFARR(prop, db, form) Type: `method` Compares two arrays of objects by a key. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `prop` | `String` | yes | | Name of the key, for example `id`. | | `db` | `Object[]` | yes | | The stored items. | | `form` | `Object[]` | yes | | The new items. | Returns: `Object` `{ add: [], upd: [], rem: [] }` Returns `{ add, upd, rem }`: `add` holds items of `form` that are not in `db`, `upd` holds `{ db, form }` pairs that exist in both, and `rem` holds the key values of items of `db` that are missing in `form`. Use it to save a list that a user edited. Example: Sync a list ```js var diff = DIFFARR('id', [{ id: 1 }, { id: 2 }], [{ id: 2, name: 'B' }, { id: 3 }]); // diff.add: [{ id: 3 }] // diff.upd: [{ db: { id: 2 }, form: { id: 2, name: 'B' } }] // diff.rem: [1] ``` ### PATH.root([filename]) Type: `method` Returns a path in the root directory of the app. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `filename` | `String` | no | | A relative path. | Returns: `String` The result always uses `/` as the separator. Example: A file in the root ```js var filename = PATH.root('data/countries.json'); ``` ### PATH.temp([filename]) Type: `method` Returns a path in the temporary directory and creates the directory. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `filename` | `String` | no | | A file name. | Returns: `String` The directory is `CONF.directory_temp`. `PATH.tmp()` and `PATH.temporary()` are aliases. Example: Temporary file ```js var filename = PATH.temp('export-' + UID() + '.csv'); ``` ### PATH.databases([filename]) Type: `method` Returns a path in the databases directory and creates the directory. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `filename` | `String` | no | | A file name. | Returns: `String` The directory is `CONF.directory_databases`. Example: A data file ```js var filename = PATH.databases('settings.json'); ``` ### PATH.logs([filename]) Type: `method` Returns a path in the logs directory and creates the directory. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `filename` | `String` | no | | A file name. | Returns: `String` The directory is `CONF.directory_logs`. `LOGGER()` writes there. Example: Read a log ```js require('fs').readFile(PATH.logs('payments.log'), 'utf8', function(err, text) { console.log(text); }); ``` ### PATH.mkdir(path, [cache]) Type: `method` Creates a directory with all missing parent directories. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `path` | `String` | yes | | An absolute path. | | `cache` | `Boolean` | no | `false` | Skips paths created before. | Returns: `undefined` It works synchronously. With `cache` set to `true`, a path that was already created is not checked again until the framework clears its cache. Example: Directory for uploads ```js var dir = PATH.databases('uploads/2021/'); PATH.mkdir(dir, true); ``` ### U.random([max], [min]) Type: `method` Returns a random integer between `min` and `max`, both included. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `max` | `Number` | no | `100000` | The highest value. | | `min` | `Number` | no | `0` | The lowest value. | Returns: `Number` 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 | | Number of characters. | Returns: `String` Characters are `0-9`, `A-Z` and `a-z`. Example: A code ```js var code = U.random_text(8); // e.g. '1qrWGUa7' ``` ### U.random_string(length) Type: `method` Returns a random string of letters. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `length` | `Number` | yes | | Number of characters. | Returns: `String` Characters are `A-Z` and `a-z`, without digits. Example: Letters only ```js var name = U.random_string(6); ``` ### U.random_number(length) Type: `method` Returns a string of random digits. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `length` | `Number` | yes | | Number of digits. | Returns: `String` The first digit is never `0`, so `+value` has the same number of digits. The result is a string. Example: A PIN ```js var pin = U.random_number(6); // e.g. '986081' ``` ### U.encrypt_uid(value, [key]) Type: `method` Signs an ID so that it cannot be changed by the client. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `value` | `String|Number` | yes | | The ID. | | `key` | `String` | no | `CONF.secret` | A secret key. | Returns: `String` The result contains the ID and a checksum of the ID and the key, for example `n3ck9tg6x123`. The value is not hidden; it is protected against changes. Use `U.decrypt_uid()` to read it back. Example: Link with a signed ID ```js var link = '/download/' + U.encrypt_uid(file.id) + '/'; ``` ### U.decrypt_uid(value, [key]) Type: `method` Reads an ID signed by `U.encrypt_uid()`. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `value` | `String` | yes | | The signed ID. | | `key` | `String` | no | `CONF.secret` | The secret key used to sign it. | Returns: `String|Number` The ID, or `null`. Returns the original ID (a number when a number was signed), or `null` when the checksum does not match. Example: Verify an ID from a URL ```js var id = U.decrypt_uid(this.params.id); if (id == null) { this.throw404(); return; } ``` ### U.copy(source, [target]) Type: `method` Copies the values of `source` to the keys that `target` already has. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `source` | `Object` | yes | | Object to read. | | `target` | `Object` | no | | Object to write. | Returns: `Object` The target. Only keys that exist in `target` (with a value other than `undefined`) are written; values are cloned. Without `target` it returns a new copy of `source`. To copy all keys, use `COPY()`. Example: Update known fields ```js var item = { name: '', price: 0 }; U.copy({ name: 'Book', price: 9, hack: true }, item); // item: { name: 'Book', price: 9 } ``` ### U.extend(target, source, [rewrite]) Type: `method` Adds the properties of `source` to `target`. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `target` | `Object` | yes | | Object to write. | | `source` | `Object` | yes | | Object to read. | | `rewrite` | `Boolean` | no | `true` | Overwrites existing values. | Returns: `Object` The target. Values are cloned. With `rewrite` set to `false`, keys that already have a value in `target` are kept, so `source` acts as a set of defaults. Example: Defaults ```js var options = { timeout: 1000 }; U.extend(options, { timeout: 5000, retry: 3 }, false); // options: { timeout: 1000, retry: 3 } ``` ### U.reduce(source, props, [reverse]) Type: `method` Keeps only some properties of an object. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `source` | `Object|Object[]` | yes | | The object or array of objects. | | `props` | `String[]|Object` | yes | | Keys to keep. | | `reverse` | `Boolean` | no | `false` | Removes the listed keys instead. | Returns: `Object|Object[]` `props` is an array of keys or an object whose keys are used. With `reverse` set to `true`, the listed keys are removed instead. An array as `source` reduces each item. The result is a new object. Example: Public fields ```js var output = U.reduce(user, ['id', 'name']); var safe = U.reduce(user, ['password'], true); ``` ### U.get(obj, path) Type: `method` Reads a value by a path such as `address.city`. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `obj` | `Object` | yes | | The object. | | `path` | `String` | yes | | The path with dots. | Returns: `Object` The value. Returns `undefined` when a part of the path does not exist. Indexes are written as `items[0].name`. Paths that contain code-like characters (spaces, brackets of calls, `__proto__` and similar) return `undefined`. Example: Nested value ```js U.get({ address: { city: 'Bratislava' } }, 'address.city'); // 'Bratislava' U.get({}, 'address.city'); // undefined ``` ### U.set(obj, path, value) Type: `method` Writes a value by a path such as `address.city`. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `obj` | `Object` | yes | | The object. | | `path` | `String` | yes | | The path with dots. | | `value` | `Object` | yes | | The value. | Returns: `Object` The value. Missing objects on the path are created. A path that ends with `[]` pushes the value to an array. Paths that contain code-like characters are ignored. Example: Build an object ```js var obj = {}; U.set(obj, 'address.city', 'Bratislava'); U.set(obj, 'tags[]', 'new'); // { address: { city: 'Bratislava' }, tags: ['new'] } ``` ### U.trim(obj, [clean]) Type: `method` Trims all string values of an object or an array. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `obj` | `Object|Array|String` | yes | | The value to trim. | | `clean` | `Boolean` | no | `false` | Replaces empty strings with `undefined`. | Returns: `Object` The same value. Nested objects and arrays are trimmed too; the object is changed in place. With `clean` set to `true`, empty strings become `undefined`. Example: Clean a form ```js U.trim({ name: ' Peter ', note: ' ' }, true); // { name: 'Peter', note: undefined } ``` ### U.keywords(content, [forSearch], [alternative], [max_count], [max_length], [min_length]) Type: `method` Extracts keywords from a text. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `content` | `String|String[]` | yes | | The text. | | `forSearch` | `Boolean` | no | `true` | Normalizes the words for search. | | `alternative` | `Boolean` | no | `false` | Shortens the words. | | `max_count` | `Number` | no | `200` | Maximum number of words read. | | `max_length` | `Number` | no | `20` | Longer words are skipped. | | `min_length` | `Number` | no | `2` | Shorter words are skipped. | Returns: `String[]` The text is lowercased and split into words; the result is a list of unique words, the most frequent first. With `forSearch` (the default), diacritics are removed and `y` is replaced with `i`, so the same words match in a search. `alternative` shortens each word to 80 % of its length to match word forms. `content` can be an array of texts. Example: Search index ```js var keywords = U.keywords(product.name + ' ' + product.description).join(' '); ``` ### U.queue(name, max, fn, [param]) Type: `method` Runs functions with a limit of how many run at the same time. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `name` | `String` | yes | | Name of the queue. | | `max` | `Number` | yes | | Maximum running functions. | | `fn` | `Function` | yes | | `function(next, param)`. | | `param` | `Object` | no | | A value passed to `fn`. | Returns: `Boolean` Each call adds `fn(next, param)` to the queue `name`. At most `max` functions of that queue run at once; each must call `next()` when it finishes. Returns `true` when `fn` starts at once, `false` when it waits. Example: Three downloads at once ```js urls.forEach(function(url) { U.queue('downloads', 3, function(next, url) { download(url, next); }, url); }); ``` ### U.sortcomparer(sort) Type: `method` Creates a compare function for `Array.sort()` from a text. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `sort` | `String` | yes | | The sort definition. | Returns: `Function` `function(a, b)` `sort` is a list of fields separated by commas, each with an optional `_asc` or `_desc` suffix, for example `price_desc,name`. Nested fields such as `address.city` are supported. Strings, numbers, booleans and dates are compared by their type. Example: Sort products ```js products.sort(U.sortcomparer('price_desc,name_asc')); ``` ### U.combine(path1, [path2], [...]) Type: `method` Joins paths relative to the root directory of the app. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `path` | `String` | yes | | One or more parts of the path. | Returns: `String` An absolute path. A part that starts with `~` is an absolute path and replaces what was before it. On Windows the result uses `/`. Example: Paths in the app ```js U.combine('/public/', 'img'); // '/www/app/public/img' U.combine('~/var/data/', 'file.txt'); // '/var/data/file.txt' ``` ### U.join(path1, [path2], [...]) Type: `method` Joins parts of a path with `/`. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `path` | `String` | yes | | One or more parts. | Returns: `String` Slashes at the start and the end of each part are removed, and the result starts with `/`. Empty parts are skipped. Example: Join ```js U.join('a', '/b/', 'c'); // '/a/b/c' ``` ### U.getExtension(filename, [raw]) Type: `method` Returns the extension of a file name without the dot. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `filename` | `String` | yes | | The file name or URL. | | `raw` | `Boolean` | no | `false` | Keeps the original case. | Returns: `String` The extension is lowercased unless `raw` is `true`. A query string after `?` is ignored. Returns an empty string when there is no extension. Example: Extension ```js U.getExtension('Photo.JPG?width=200'); // 'jpg' ``` ### U.getName(path) Type: `method` Returns the last part of a path. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `path` | `String` | yes | | The path. | Returns: `String` Works with `/` and `\` separators; a trailing separator is ignored. Example: File name ```js U.getName('/www/app/public/logo.png'); // 'logo.png' ``` ### U.getContentType(ext) Type: `method` Returns the content type (MIME type) for an extension. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `ext` | `String` | yes | | The extension. | Returns: `String` The extension can start with a dot. An unknown extension gives `application/octet-stream`. Example: MIME type ```js U.getContentType('json'); // 'application/json' U.getContentType(U.getExtension(filename)); ``` ### U.setContentType(ext, type) Type: `method` Registers or changes the content type of an extension. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `ext` | `String` | yes | | The extension, with or without a dot. | | `type` | `String` | yes | | The content type. | Returns: `Boolean` `true` The framework uses the table to serve static files, so a new extension also becomes a known static file. Example: A new extension ```js // definitions/init.js U.setContentType('gpx', 'application/gpx+xml'); ``` ### U.ls(path, [callback], [filter], [unified]) Type: `method` Lists all files and directories in a directory and its subdirectories. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `path` | `String` | yes | | The directory. | | `callback` | `Function` | no | | `function(files, directories)`. | | `filter` | `String|RegExp|Function` | no | | A filter. | | `unified` | `Boolean` | no | `false` | Uses `/` on Windows. | Returns: `Promise|undefined` A Promise without a callback. `callback(files, directories)` receives arrays of absolute paths. Without a callback the method returns a Promise of `{ files, directories }`. `filter` is a string (part of the name, not case-sensitive), a RegExp, or `function(path, isDirectory)` that returns `true` to keep an item; the string and RegExp filters apply to files only. With `unified` set to `true`, paths on Windows use `/`. Example: Callback ```js U.ls(PATH.public(), function(files, directories) { console.log(files.length, directories.length); }, /\.(jpg|png)$/); ``` Example: Promise ```js var response = await U.ls(PATH.databases(), 'backup'); console.log(response.files); ``` ### U.ls2(path, [callback], [filter], [unified]) Type: `method` Lists files with their stats. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `path` | `String` | yes | | The directory. | | `callback` | `Function` | no | | `function(files, directories)`. | | `filter` | `String|RegExp|Function` | no | | A filter. | | `unified` | `Boolean` | no | `false` | Uses `/` on Windows. | Returns: `Promise|undefined` A Promise without a callback. Works like `U.ls()`, but each file is `{ filename, stats }`, where `stats` is the `fs.Stats` object (size, dates). Directories are still paths. Example: Total size ```js U.ls2(PATH.temp(), function(files) { var size = 0; for (var file of files) size += file.stats.size; console.log(size.filesize()); }); ``` ### U.encode(value) Type: `method` Encodes HTML special characters. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `value` | `Object` | yes | | The value. | Returns: `String` `null` and `undefined` give an empty string; other values are converted to a string first. It calls `String.encode()`. Example: Safe HTML ```js U.encode('<b>'); // '<b>' ``` ### U.decode(value) Type: `method` Decodes HTML entities back to characters. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `value` | `Object` | yes | | The value. | Returns: `String` The opposite of `U.encode()`. `null` and `undefined` give an empty string. Example: Plain text ```js U.decode('<b>'); // '<b>' ``` ### U.btoa(value) Type: `method` Encodes a string or a Buffer to Base64. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `value` | `String|Buffer` | yes | | The value. | Returns: `String` `U.atob(value)` decodes Base64 back to a UTF-8 string. Example: Base64 ```js var encoded = U.btoa('hi'); // 'aGk=' var text = U.atob(encoded); // 'hi' ``` ### U.parseXML(xml, [replace]) Type: `method` Parses XML into a flat object. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `xml` | `String` | yes | | The XML. | | `replace` | `Boolean` | no | `false` | Replaces special characters in keys. | Returns: `Object` Each key is the path of an element joined with dots, for example `root.item`; repeated elements give an array of values. Attributes are stored under the key with `[]`, for example `root.item[]`. With `replace` set to `true`, the characters `[`, `]`, `:`, `.` and `_` in keys become `_`. CDATA is read as text. Example: Read XML ```js var obj = U.parseXML('<root><item id="1">A</item><item>B</item></root>'); // { 'root.item[]': { id: '1' }, 'root.item': ['A', 'B'] } ``` ### U.parseInt(value, [def]) Type: `method` Converts any value to an integer. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `value` | `Object` | yes | | The value. | | `def` | `Number` | no | `0` | Value for empty or invalid input. | Returns: `Number` `null`, `undefined` and an empty string give `def`. A number is returned as it is. `U.parseFloat(value, [def])` and `U.parseBoolean(value, [def])` work the same way for decimals and booleans (`def` is `false` for booleans; a number is `true` when it is greater than 0). Example: Query values ```js var page = U.parseInt(this.query.page, 1); var price = U.parseFloat(this.query.price); var active = U.parseBoolean(this.query.active); ``` ### U.distance(lat1, lon1, lat2, lon2) Type: `method` Returns the distance between two GPS coordinates in kilometres. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `lat1` | `Number` | yes | | Latitude of the first point. | | `lon1` | `Number` | yes | | Longitude of the first point. | | `lat2` | `Number` | yes | | Latitude of the second point. | | `lon2` | `Number` | yes | | Longitude of the second point. | Returns: `Number` Kilometres. Uses the haversine formula on a sphere with a radius of 6371 km; the result has at most 3 decimal places. Example: Bratislava to Prague ```js U.distance(48.1486, 17.1077, 50.0755, 14.4378); // 289.225 ``` ### U.minify_css(value) Type: `method` Minifies CSS with the built-in compiler. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `value` | `String` | yes | | CSS code. | Returns: `String` The same compiler the framework uses for static `.css` files. Example: Minify ```js U.minify_css('a { color: red; }'); // 'a{color:red}' ``` ### U.minify_js(value) Type: `method` Minifies JavaScript with the built-in compiler. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `value` | `String` | yes | | JavaScript code. | Returns: `String` Removes comments and white space. The same compiler the framework uses for static `.js` files. Example: Minify ```js U.minify_js('var a = 1; // note'); ``` ### U.minify_html(value) Type: `method` Minifies HTML with the built-in compiler. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `value` | `String` | yes | | HTML code. | Returns: `String` Removes white space between tags. Example: Minify ```js U.minify_html('<div> <b>x</b> </div>'); // '<div><b>x</b></div>' ``` ### STATUS(id, data, [timeout]) Type: `method` · Since: `0.0.63` Stores a named status of your app and passes it to `DEF.onStatus(meta)`. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `id` | `String|Object` | yes | | The name of the status, or a `$` object. | | `data` | `Object` | yes | | Any value. | | `timeout` | `Number` | no | | Delays the update and merges calls in this time, in milliseconds. | Returns: `undefined` Nothing. Each `id` has one status object `{ id, data, date }`. `STATUS()` replaces its `data`, sets `date` and calls `DEF.onStatus(meta)` when you define it. Instead of an `id` you can pass a `$` object; its `ID` (or `name`) is the id. With `timeout` (in milliseconds), the update is delayed: the first call starts the timer, later calls only change `data`, and `DEF.onStatus()` runs once with the last data when the timer ends. Use it for values that change often, like a progress. With `CONF.allow_stats_status` (default `true`), all statuses are added as `status` to the stats snapshot that Total.js writes to `<main script>.json` (`CONF.allow_stats_snapshot`). Example: Progress of an import ```js DEF.onStatus = function(meta) { console.log(meta.id, meta.data, meta.date); }; for (var i = 0; i < items.length; i++) STATUS('import', { done: i + 1, total: items.length }, 1000); ``` ### U.encrypt_data(value, key, [encode]) Type: `method` Encrypts a string with a key and a random mask. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `value` | `String` | yes | | The text to encrypt. | | `key` | `String` | yes | | The key. | | `encode` | `String` | no | `base64` | A Buffer encoding or `buffer`. | Returns: `String|Buffer` The encrypted value. The output changes on every call because of a random 4-byte mask. `encode` is a Buffer encoding (default `base64`); `buffer` returns the raw Buffer. Read it back with `U.decrypt_data()` and the same key. This is light obfuscation, not a replacement for `U.encrypt_crypto()`. Example: Encrypt a JSON string ```js var token = U.encrypt_data(JSON.stringify({ id: user.id }), CONF.secret); ``` ### U.decrypt_data(value, key, [encode]) Type: `method` Decrypts a value made by `U.encrypt_data()`. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `value` | `String|Buffer` | yes | | The encrypted value. | | `key` | `String` | yes | | The key used for encryption. | | `encode` | `String` | no | `base64` | The encoding of `value`. | Returns: `String` The decrypted text or `null`. `value` is a string in the `encode` encoding (default `base64`) or a Buffer. Returns `null` when the value cannot be read. A wrong key gives a wrong string, not `null`, so check the result (for example with `parseJSON()`). Example: Decrypt a token ```js var data = (U.decrypt_data(token, CONF.secret) || '').parseJSON(); if (!data) return $.invalid(401); ``` ### U.encrypt_crypto(type, key, value) Type: `method` Encrypts data with a Node.js cipher. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `type` | `String` | yes | | A cipher name, for example `aes-256-cbc`. | | `key` | `String` | yes | | The key. | | `value` | `String|Buffer` | yes | | The data. | Returns: `Buffer` The encrypted data. Uses `Crypto.createCipheriv(type, key, CONF.default_crypto_iv)`. The key length must fit the cipher (32 characters for `aes-256-cbc`). `CONF.default_crypto_iv` is created from the app by default, so set it in the config when other apps must decrypt the data. Example: AES ```js var key = 'a6e4c7d1b9f2038e5a7c1d4b6e8f0a2c'; var buffer = U.encrypt_crypto('aes-256-cbc', key, 'Hello'); var text = buffer.toString('base64'); ``` ### U.decrypt_crypto(type, key, value) Type: `method` Decrypts data made by `U.encrypt_crypto()`. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `type` | `String` | yes | | The cipher name. | | `key` | `String` | yes | | The key. | | `value` | `Buffer` | yes | | The encrypted data. | Returns: `Buffer` The decrypted data or `undefined`. Uses `Crypto.createDecipheriv(type, key, CONF.default_crypto_iv)`. Returns `undefined` when the data cannot be decrypted. Example: AES ```js var buffer = U.decrypt_crypto('aes-256-cbc', key, Buffer.from(text, 'base64')); buffer && console.log(buffer.toString('utf8')); ``` ### U.convert62(number) Type: `method` · Since: `0.0.85` Converts a number to a base-62 string. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `number` | `Number` | yes | | A positive number. | Returns: `String` The alphabet is digits, then upper-case and lower-case letters. Decimals are floored. Read it back with `U.from62()`. Example: Short code ```js U.convert62(123456789); // '8M0kX' ``` ### U.from62(value) Type: `method` · Since: `0.0.85` Converts a base-62 string from `U.convert62()` back to a number. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `value` | `String` | yes | | A base-62 string. | Returns: `Number` Example: Back to a number ```js U.from62(U.convert62(1000)); // 1000 ``` ### U.groupify(id, [count]) Type: `method` · Since: `0.0.88` Returns a fixed-length numeric group for an identifier. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `id` | `String` | yes | | An identifier. | | `count` | `Number` | no | `4` | The number of digits. | Returns: `String` A string of digits. The value is `HASH(id, true)` modulo `10^count`, padded with zeros to `count` digits. The same id always gives the same group, so it is useful for spreading files into sub-directories. Example: Sub-directories ```js var id = UID(); var filename = PATH.databases('files/' + U.groupify(id) + '/' + id + '.json'); ``` ### U.parseBoolean(value, [def]) Type: `method` Converts any value to a boolean. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `value` | `Object` | yes | | A value. | | `def` | `Boolean` | no | `false` | The default value. | Returns: `Boolean` A boolean is returned as it is, a number is `true` when greater than `0`, other values are converted to a string and parsed with `String.parseBoolean()`. `null` and `undefined` return `def`. Example: Query value ```js var active = U.parseBoolean($.query.active); ``` ### U.parseFloat(value, [def]) Type: `method` Converts any value to a decimal number. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `value` | `Object` | yes | | A value. | | `def` | `Number` | no | `0` | The default value. | Returns: `Number` A number is returned as it is, other values are converted to a string and parsed with `String.parseFloat()`. `null`, `undefined` and an empty string return `def`. Example: Price ```js var price = U.parseFloat(model.price, 0); ``` ### U.isDate(value) Type: `method` Checks that a value is a valid `Date`. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `value` | `Object` | yes | | A value. | Returns: `Boolean` Returns `false` for an invalid date such as `new Date('abc')`. Example: Validate a date ```js U.isDate(new Date()); // true U.isDate(new Date('abc')); // false U.isDate('2024-01-01'); // false ``` ### U.DAYS Type: `property` English names of the days of the week. Returns: `String Array` The array starts with `Sunday`, so it matches `Date.getDay()`. Example: Day name ```js var name = U.DAYS[new Date().getDay()]; ``` ### U.MONTHS Type: `property` English names of the months. Returns: `String Array` The array starts with `January`, so it matches `Date.getMonth()`. Example: Month name ```js var name = U.MONTHS[new Date().getMonth()]; ``` ### U.httpstatus(code, [addCode]) Type: `method` Returns the text of an HTTP status code. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `code` | `Number` | yes | | An HTTP status code. | | `addCode` | `Boolean` | no | `true` | Adds the code to the text. | Returns: `String` The text comes from `http.STATUS_CODES`. With `addCode` (default `true`) the code is added in front. Example: Status text ```js U.httpstatus(404); // '404: Not Found' U.httpstatus(404, false); // 'Not Found' ``` ### U.toURLEncode(obj) Type: `method` Serializes an object into a URL-encoded query string. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `obj` | `Object` | yes | | An object. | Returns: `String` For example `q=total&page=2`. Strings are encoded with `encodeURIComponent()`, numbers and booleans are added as they are, arrays are joined with `,`. `null`, `undefined`, empty strings and other objects (including dates) are skipped. Returns an empty string when nothing is added. Example: Query string ```js var url = 'https://example.com/api/?' + U.toURLEncode({ q: 'total js', page: 2, tags: ['a', 'b'] }); // q=total%20js&page=2&tags=a%2Cb ``` ### U.atob(value) Type: `method` Decodes a base64 string to a UTF-8 string. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `value` | `String` | yes | | A base64 string. | Returns: `String` The reverse of `U.btoa()`. Example: Decode ```js U.atob(U.btoa('Hello')); // 'Hello' ``` ### U.isrelative(url) Type: `method` Checks that a URL is relative. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `url` | `String` | yes | | A URL. | Returns: `Boolean` Returns `false` when the URL starts with `//` or contains `http://` or `https://`. Example: Safe redirect ```js var url = $.query.redirect || '/'; if (!U.isrelative(url)) url = '/'; $.redirect(url); ``` ### U.isStaticFile(url) Type: `method` Checks that a URL looks like a file. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `url` | `String` | yes | | A URL path. | Returns: `Boolean` Returns `true` when the last 8 characters of the URL contain a dot, for example `/img/logo.png`. Example: File or route ```js U.isStaticFile('/img/logo.png'); // true U.isStaticFile('/api/users/'); // false ``` ### U.resolve(url, [callback], [param]) Type: `method` Resolves the IPv4 address of a URL and caches it. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `url` | `String` | yes | | A URL. | | `callback` | `Function` | no | | `function(err, uri, param, addresses)`. | | `param` | `Object` | no | | A value passed to the callback. | Returns: `Array|undefined` The cached addresses when no callback is given. `callback(err, uri, param, addresses)` receives the parsed URL with `uri.host` replaced by the first address. The addresses are cached per host; without a callback the method returns the cached addresses (or `undefined`). A failed lookup is tried once more. The `clear_dnscache` command clears the cache. Example: DNS lookup ```js U.resolve('https://www.totaljs.com', function(err, uri, param, addresses) { console.log(err, addresses); }); ``` ### U.link(path1, [path2], [...]) Type: `method` · Since: `0.0.39` Joins URL parts with exactly one `/` between them. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `path` | `String` | yes | | One or more URL parts. | Returns: `String` Unlike `U.join()`, it does not add a leading `/` and keeps the parts as they are. Example: Build a URL ```js U.link('https://example.com/', '/api/', 'users'); // 'https://example.com/api/users' ``` ### U.normalize(path) Type: `method` · Since: `0.0.39` Adds `/` to the start and the end of a path when it is missing. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `path` | `String` | yes | | A path. | Returns: `String` Example: Normalize ```js U.normalize('admin'); // '/admin/' ``` ### U.path(path, [delimiter]) Type: `method` Adds a trailing delimiter to a path when it is missing. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `path` | `String` | yes | | A path. | | `delimiter` | `String` | no | `/` | The delimiter. | Returns: `String` An empty path returns the delimiter. Example: Directory path ```js U.path('/www/app'); // '/www/app/' ``` ### U.getExtensionFromContentType(contentType) Type: `method` · Since: `0.0.63` Returns the file extension of a content type. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `contentType` | `String` | yes | | A content type. | Returns: `String` Searches the content types known to `U.getContentType()` (including the ones added with `U.setContentType()`). Returns the first match without a dot, or `undefined`. Example: Extension ```js U.getExtensionFromContentType('image/png'); // 'png' ``` ### U.ObjectToArray(obj) Type: `method` Converts an object into an array of `{ key, value }` items. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `obj` | `Object` | yes | | An object. | Returns: `Array` `null` or `undefined` returns `EMPTYARRAY`. Example: Key-value list ```js U.ObjectToArray({ a: 1, b: 2 }); // [{ key: 'a', value: 1 }, { key: 'b', value: 2 }] ``` ### U.createBuffer([value], [encoding]) Type: `method` Shortcut for `Buffer.from(value || '', encoding)`. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `value` | `String|Array|Buffer` | no | `''` | The data. | | `encoding` | `String` | no | `utf8` | The encoding of a string. | Returns: `Buffer` Example: From base64 ```js var buffer = U.createBuffer(body, 'base64'); ``` ### U.createBufferSize([size]) Type: `method` Shortcut for `Buffer.alloc(size || 0)`. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `size` | `Number` | no | `0` | The size in bytes. | Returns: `Buffer` A buffer filled with zeros. Example: Empty buffer ```js var buffer = U.createBufferSize(4); buffer.writeInt32BE(100); ``` ### U.json2replacer(key, value) Type: `method` A `JSON.stringify()` replacer that removes `null` and `undefined` values. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `key` | `String` | yes | | The key. | | `value` | `Object` | yes | | The value. | Returns: `Object` Example: Smaller JSON ```js JSON.stringify({ id: 1, name: null }, U.json2replacer); // '{"id":1}' ``` ### U.queuecache Type: `property` The state of the queues created by `U.queue()`. Returns: `Object` An object keyed by the queue name. Each item has `limit`, `running` and `pending` (the waiting callbacks). Read it for monitoring only. Example: Waiting items ```js var item = U.queuecache.import; item && console.log(item.running, item.pending.length); ``` ### new U.EventEmitter2([obj]) Type: `class` A small event emitter. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `obj` | `Object` | no | | An object to extend. | Returns: `EventEmitter2` `new U.EventEmitter2()` creates an emitter. `U.EventEmitter2(obj)` (without `new`) adds `emit()`, `on()`, `once()`, `off()`, `removeListener()` and `removeAllListeners()` to an existing object and returns it; `U.EventEmitter2.extend(obj)` does the same. Listeners are kept in `$events`. `emit()` passes up to 7 arguments and `this` is the emitter. Example: Extend an object ```js var service = {}; U.EventEmitter2(service); service.on('ready', function(value) { console.log('ready', value); }); service.emit('ready', 1); ``` ### emitter.off(name, [fn]) Type: `method` · Since: `0.0.90` Removes a listener or all listeners of an event. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `name` | `String` | yes | | The event name. | | `fn` | `Function` | no | | The listener. | Returns: `EventEmitter2` The emitter. Without `fn` all listeners of `name` are removed. `removeListener()` is an alias. `removeAllListeners([name])` removes the listeners of one event or of all events. Example: Remove a listener ```js var fn = function() {}; emitter.on('change', fn); emitter.off('change', fn); ``` ### U.Callback(count, [callback]) Type: `method` Calls a callback after `next()` was called `count` times. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `count` | `Number` | yes | | How many `next()` calls to wait for. | | `callback` | `Function` | no | | The function to call. | Returns: `Callback` An instance with `next()` and `done(fn)`. Returns an instance with `next()` and `done(callback)`. The callback runs once, when the pending count reaches zero. The class is also available as the global `Callback`. Example: Wait for 3 tasks ```js var cb = U.Callback(3, function() { console.log('all done'); }); for (var i = 0; i < 3; i++) setTimeout(() => cb.next(), 100 * i); ``` ### U.chunker(name, [max]) Type: `method` Stores many items in temporary files, page by page. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `name` | `String` | yes | | A unique name, used in the file names. | | `max` | `Number` | no | `50` | The number of items per file. | Returns: `Chunker` Every `max` items written with `write()` go to one file `{name}-{index}.chunker` in the temp directory, compressed with deflate. Read them back page by page with `each()` or `read()`. Properties: `compress` (default `true`), `autoremove` (default `true`, removes each file after it is read), `count`, `pages` and `percentage` (progress of `each()`). The class is available as `U.Chunker`. Example: Export in pages ```js var chunker = U.chunker('export', 100); for (var item of items) chunker.write(item); chunker.end(); chunker.each(function(items, next, index) { console.log('page', index, items.length); next(); }, function() { console.log('done'); }); ``` ### chunker.write(item) Type: `method` Adds an item. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `item` | `Object` | yes | | An item that can be serialized to JSON. | Returns: `Chunker` When `max` items are waiting, they are written to a new file. `append()` is an alias. Call `end()` after the last item. Example: Write ```js chunker.write({ id: 1, name: 'Peter' }); ``` ### chunker.end() Type: `method` Writes the remaining items to the last file. Returns: `Chunker` Example: Finish writing ```js chunker.end(); ``` ### chunker.each(onItem, [onEnd]) Type: `method` Reads all pages one by one. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `onItem` | `Function` | yes | | `function(items, next, index)`. | | `onEnd` | `Function` | no | | Runs after the last page. | Returns: `Chunker` `onItem(items, next, index)` gets the items of one page; call `next()` to read the next page. `onEnd()` runs after the last page. `percentage` shows the progress. Example: Process pages ```js chunker.each(function(items, next) { items.wait(save, next); }, () => console.log('done')); ``` ### chunker.read(index, callback) Type: `method` Reads one page. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `index` | `Number` | yes | | The page index from `0`. | | `callback` | `Function` | yes | | `function(err, items)`. | Returns: `Chunker` `callback(err, items)` gets the items of the page, or an empty array when the file does not exist. It waits while files are still being written. Example: First page ```js chunker.read(0, function(err, items) { console.log(items); }); ``` ### chunker.clear() Type: `method` Removes all files of the chunker. Returns: `Chunker` `destroy()` also removes the files and releases the instance. Example: Clean up ```js chunker.clear(); ``` ### U.reader([items]) Type: `method` Queries an array of objects with the NoSQL query builder. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `items` | `Array|Object|String` | no | | The items or a URL. | Returns: `Reader` `items` is an array (or one object), or a URL of TextDB content that is downloaded and streamed. Without `items`, add data with `reader.push(items)` and finish with `reader.push(null)`, or use `reader.stream(stream)`. `find()`, `list()`, `read()`, `count()`, `scalar(type, key, [key2])` and `stats(groupfield, datefield, key, [type])` return a NoSQL query builder (`where()`, `sort()`, `take()`, `callback()`...). `list()` returns `{ page, pages, limit, count, items }`. `assign(data)` creates a query from a serialized query object. Example: Filter an array ```js var reader = U.reader(users); reader.find().where('age', '>', 18).sort('name').take(10).callback(function(err, response) { console.log(response); }); reader.count().callback(function(err, response) { console.log(response); }); ``` ### reader.push(items) Type: `method` Adds items to the reader. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `items` | `Array|Object|null` | yes | | The data, or `null` at the end. | Returns: `undefined` Pass an array or one object for each chunk of data, then `null` to finish and get the results. Example: Push data ```js var reader = U.reader(); reader.find().where('active', true).callback(console.log); reader.push(page1); reader.push(page2); reader.push(null); ``` ### U.streamer(beg, [end], callback, [skip], [stream]) Type: `method` Splits a stream of chunks into parts by delimiters. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `beg` | `String|Buffer` | yes | | The delimiter or the start of a part. | | `end` | `String|Buffer` | no | | The end of a part. | | `callback` | `Function` | yes | | `function(value, index)`. | | `skip` | `Number` | no | `0` | The number of parts to skip. | | `stream` | `Stream` | no | | A stream for the `end` event. | Returns: `Function` `function(chunk)`. Returns `function(chunk)` that you pass every chunk to. Without `end`, every part ends with `beg` (and includes it), for example a line ending with `\n`. With `end`, every part starts with `beg` and ends with `end`. `callback(value, index)` gets each part as a string; return `false` to stop. `skip` skips the first parts. With `stream`, the remaining data is processed on the stream `end` event. `U.streamer2()` is the same but gives Buffers. Example: Read lines ```js var stream = F.Fs.createReadStream(PATH.databases('log.txt')); stream.on('data', U.streamer('\n', function(line, index) { console.log(index, line.trim()); }, stream)); ``` ### U.streamer2(beg, [end], callback, [skip], [stream]) Type: `method` Same as `U.streamer()`, but the parts are Buffers. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `beg` | `String|Buffer` | yes | | The delimiter or the start of a part. | | `end` | `String|Buffer` | no | | The end of a part. | | `callback` | `Function` | yes | | `function(buffer, index)`. | | `skip` | `Number` | no | `0` | The number of parts to skip. | | `stream` | `Stream` | no | | A stream for the `end` event. | Returns: `Function` `function(chunk)`. Example: Binary parts ```js stream.on('data', U.streamer2('<item>', '</item>', function(buffer) { console.log(buffer.length); })); ``` ### U.filestreamer(filename) Type: `method` · Since: `0.0.59` Reads a text file line by line in batches. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `filename` | `String` | yes | | The file. | Returns: `Object` A stream reader. Returns a TextDB stream reader. Set `ondocuments` (called with `this.docs`, the lines of one batch joined by `,`; return `false` to stop) and `$callback` (called at the end), then call `openread()`. Set `array = true` to get `docs` as an array of lines. Lines that start with `-` are skipped. Example: Read a JSON-lines file ```js var reader = U.filestreamer(PATH.databases('items.nosql')); reader.ondocuments = function() { var items = JSON.parse('[' + reader.docs + ']'); console.log(items.length); }; reader.$callback = () => console.log('done'); reader.openread(); ``` ### PATH.join(path1, [path2], [...]) Type: `method` · Since: `0.0.39` Alias for Node.js `path.join()`. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `path` | `String` | yes | | One or more parts of the path. | Returns: `String` Example: Join ```js var filename = PATH.join(PATH.root(), 'data', 'file.json'); ``` ### PATH.exists(path, callback) Type: `method` Checks that a file or directory exists. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `path` | `String` | yes | | A path. | | `callback` | `Function` | yes | | `function(exists, size, isFile)`. | Returns: `undefined` `callback(exists, size, isFile)`. Example: Check a file ```js PATH.exists(PATH.public('robots.txt'), function(exists, size, isFile) { console.log(exists, size, isFile); }); ``` ### PATH.verify(name) Type: `method` Creates an app directory if it does not exist. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `name` | `String` | yes | | The directory name. | Returns: `undefined` `name` is the name of a `CONF.directory_{name}` setting, for example `databases`. The check runs once per name. Example: Make sure the directory exists ```js PATH.verify('private'); ``` ### PATH.ls(path, [callback], [filter], [unified]) Type: `method` Alias for `U.ls()`. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `path` | `String` | yes | | The directory. | | `callback` | `Function` | no | | `function(files, directories)`. | Returns: `Promise|undefined` `PATH.ls2()` is an alias for `U.ls2()`. Example: List files ```js PATH.ls(PATH.private(), function(files) { console.log(files); }); ``` ### PATH.unlink(files, [callback]) Type: `method` Removes files one by one. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `files` | `String|String Array` | yes | | The files. | | `callback` | `Function` | no | | Runs at the end. | Returns: `undefined` Errors are ignored. Example: Remove files ```js PATH.unlink([PATH.temp('a.tmp'), PATH.temp('b.tmp')], () => console.log('removed')); ``` ### PATH.rmdir(directories, [callback]) Type: `method` Removes directories with all their content. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `directories` | `String|String Array` | yes | | The directories. | | `callback` | `Function` | no | | Runs at the end. | Returns: `undefined` Errors are ignored. Example: Remove a directory ```js PATH.rmdir(PATH.temp('import'), () => console.log('removed')); ``` ### PATH.private([filename]) Type: `method` Returns a path in the private directory. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `filename` | `String` | no | | A file name. | Returns: `String` An absolute path. The directory is `CONF.directory_private` (default `/private/`). Example: Path ```js var filename = PATH.private('data.json'); ``` ### PATH.models([filename]) Type: `method` Returns a path in the models directory. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `filename` | `String` | no | | A file name. | Returns: `String` An absolute path. The directory is `CONF.directory_models` (default `/models/`). Example: Path ```js var filename = PATH.models('file.js'); ``` ### PATH.builds([filename]) Type: `method` Returns a path in the builds directory. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `filename` | `String` | no | | A file name. | Returns: `String` An absolute path. The directory is `CONF.directory_builds` (default `/builds/`). Example: Path ```js var filename = PATH.builds('file.js'); ``` ### PATH.views([filename]) Type: `method` Returns a path in the views directory. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `filename` | `String` | no | | A file name. | Returns: `String` An absolute path. The directory is `CONF.directory_views` (default `/views/`). Example: Path ```js var filename = PATH.views('index.html'); ``` ### PATH.updates([filename]) Type: `method` Returns a path in the updates directory. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `filename` | `String` | no | | A file name. | Returns: `String` An absolute path. The directory is `CONF.directory_updates` (default `/updates/`). Example: Path ```js var filename = PATH.updates('file.js'); ``` ### PATH.modules([filename]) Type: `method` Returns a path in the modules directory. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `filename` | `String` | no | | A file name. | Returns: `String` An absolute path. The directory is `CONF.directory_modules` (default `/modules/`). Example: Path ```js var filename = PATH.modules('file.js'); ``` ### PATH.schemas([filename]) Type: `method` Returns a path in the schemas directory. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `filename` | `String` | no | | A file name. | Returns: `String` An absolute path. The directory is `CONF.directory_schemas` (default `/schemas/`). Example: Path ```js var filename = PATH.schemas('file.js'); ``` ### PATH.extensions([filename]) Type: `method` Returns a path in the extensions directory. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `filename` | `String` | no | | A file name. | Returns: `String` An absolute path. The directory is `CONF.directory_extensions` (default `/extensions/`). Example: Path ```js var filename = PATH.extensions('file.js'); ``` ### PATH.operations([filename]) Type: `method` Returns a path in the operations directory. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `filename` | `String` | no | | A file name. | Returns: `String` An absolute path. The directory is `CONF.directory_operations` (default `/operations/`). Example: Path ```js var filename = PATH.operations('file.js'); ``` ### PATH.tasks([filename]) Type: `method` Returns a path in the tasks directory. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `filename` | `String` | no | | A file name. | Returns: `String` An absolute path. The directory is `CONF.directory_tasks` (default `/tasks/`). Example: Path ```js var filename = PATH.tasks('file.js'); ``` ### PATH.controllers([filename]) Type: `method` Returns a path in the controllers directory. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `filename` | `String` | no | | A file name. | Returns: `String` An absolute path. The directory is `CONF.directory_controllers` (default `/controllers/`). Example: Path ```js var filename = PATH.controllers('file.js'); ``` ### PATH.definitions([filename]) Type: `method` Returns a path in the definitions directory. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `filename` | `String` | no | | A file name. | Returns: `String` An absolute path. The directory is `CONF.directory_definitions` (default `/definitions/`). Example: Path ```js var filename = PATH.definitions('file.js'); ``` ### PATH.tests([filename]) Type: `method` Returns a path in the tests directory. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `filename` | `String` | no | | A file name. | Returns: `String` An absolute path. The directory is `CONF.directory_tests` (default `/tests/`). Example: Path ```js var filename = PATH.tests('file.js'); ``` ### PATH.services([filename]) Type: `method` Returns a path in the services directory. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `filename` | `String` | no | | A file name. | Returns: `String` An absolute path. The directory is `CONF.directory_services` (default `/services/`). Example: Path ```js var filename = PATH.services('file.js'); ``` ### PATH.packages([filename]) Type: `method` Returns a path in the packages directory. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `filename` | `String` | no | | A file name. | Returns: `String` An absolute path. The directory is `CONF.directory_packages` (default `/packages/`). Example: Path ```js var filename = PATH.packages('file.js'); ``` ### PATH.themes([filename]) Type: `method` Returns a path in the themes directory. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `filename` | `String` | no | | A file name. | Returns: `String` An absolute path. The directory is `CONF.directory_themes` (default `/themes/`). Example: Path ```js var filename = PATH.themes('default/index.html'); ``` ### PATH.components([filename]) Type: `method` Returns a path in the components directory. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `filename` | `String` | no | | A file name. | Returns: `String` An absolute path. The directory is `CONF.directory_components` (default `/components/`). Example: Path ```js var filename = PATH.components('file.js'); ``` ### PATH.templates([filename]) Type: `method` Returns a path in the templates directory. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `filename` | `String` | no | | A file name. | Returns: `String` An absolute path. The directory is `CONF.directory_templates` (default `/templates/`). Example: Path ```js var filename = PATH.templates('email.html'); ``` ### PATH.plugins([filename]) Type: `method` · Since: `0.0.88` Returns a path in the plugins directory. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `filename` | `String` | no | | A file name. | Returns: `String` An absolute path. The directory is `CONF.directory_plugins` (default `/plugins/`). Example: Path ```js var filename = PATH.plugins('file.js'); ``` ### PATH.flowstreams([filename]) Type: `method` Returns a path in the flowstreams directory. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `filename` | `String` | no | | A file name. | Returns: `String` An absolute path. The directory is `CONF.directory_flowstreams` (default `/flowstreams/`). Example: Path ```js var filename = PATH.flowstreams('file.js'); ``` ### OBSOLETE(name, message) Type: `method` Prints a warning about obsolete code. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `name` | `String` | yes | | What is obsolete. | | `message` | `String` | yes | | What to use instead. | It writes the date, the name and the message to the console and increases `F.stats.other.obsolete`. Nothing is printed when `CONF.nowarnings` is `true` (the framework sets it when the watcher restarts the application with `--restart`). Example: Warn ```js function oldsave(model) { OBSOLETE('oldsave()', 'Use save() instead.'); return save(model); } ``` ### UID1([type], [date]) Type: `method` Generates a unique identifier with a decimal time part. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `type` | `String` | no | | A name of a separate counter. | | `date` | `Date` | no | `NOW` | The time of the identifier. | Returns: `String` The identifier. Like `UID()`, but the time part is the number of minutes since 2020-01-31 23:00 UTC written in decimal digits. Identifiers end with the version letter `b`. With `type`, every type has its own counter. `date` builds the identifier for another time. Example: Identifier ```js var id = UID1(); var orderid = UID1('orders'); ``` --- title: Prototypes project: Total.js V4 version: 0.0.99 section: reference language: en license: MIT url: https://totaljs.es/docs/total-js-v4/0-0-99/reference/prototypes/ updated: 2026-11-16T15:41:15.818Z --- # Prototypes > Methods of String, Number, Date and Array added by Total.js 4. Methods that Total.js 4 adds to `String`, `Number`, `Date` and `Array`. The guide [Prototypes](../../guides/prototypes/) explains how to use them with examples; this page is the exact reference. ## API ### String.format([arg0], [arg1], [...]) Type: `method` Replaces indexed placeholders `{0}`, `{1}`... with the arguments. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `arg0` | `Object` | no | | The value for `{0}`. Any number of arguments can follow. | Returns: `String` The formatted string. Each `{n}` is replaced with the argument at index `n`. A `null` or `undefined` argument gives an empty string. For named placeholders use `String.args()`. Example: Indexed placeholders ```js var text = 'Hello {0}, you have {1} new messages.'.format('Peter', 5); // Hello Peter, you have 5 new messages. ``` ### String.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` | `Boolean|String|Function` | no | | `true` (URL encoding), `'html'`, `'json'` or a function `function(value, key)`. | | `def` | `String` | no | | The text for a missing value. It is ignored when `encode` is a string. | Returns: `String` The string with the values. Keys may contain letters, numbers, `_`, `$`, `.` and `-`. A missing value keeps the placeholder, or uses `def` when you set it. The `encode` argument changes how values are written: `true` encodes them with `encodeURIComponent()`, `'html'` encodes HTML entities, `'json'` writes `JSON.stringify(value)`, and a function `function(value, key)` returns the text itself. `String.arg()` is an alias. Example: Named placeholders ```js var model = { name: 'Peter', city: 'Bratislava' }; var text = 'Hello {name} from {{city}}'.args(model); // Hello Peter from Bratislava ``` Example: HTML encoding ```js var html = '<b>{name}</b>'.args({ name: '<Peter>' }, 'html'); // <b><Peter></b> ``` Example: A default for missing values ```js '{name} ({age})'.args({ name: 'Peter' }, null, '-'); // Peter (-) ``` ### String.slug([max]) Type: `method` Creates a URL-friendly slug from the text. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `max` | `Number` | no | `60` | The maximum length. | Returns: `String` The slug. The text is trimmed, lower-cased and converted to ASCII (diacritics removed). Spaces and punctuation become a single `-`; a trailing `-` is removed. The result is cut at `max` characters. When the text has no usable Latin characters (for example Chinese or Cyrillic), the method returns a short hash built from the text instead. Example: Slug from a title ```js var slug = 'Hello World: Total.js 4'.slug(); // hello-world-total-js-4 ``` ### String.max(length, [chars]) Type: `method` Cuts 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 cut string. | Returns: `String` The shortened text. When the text is longer than `length`, it is cut so that the result with `chars` has exactly `length` characters. A shorter text is returned unchanged. Example: Shorten a description ```js 'A long description'.max(10); // A long ... ``` ### String.capitalize([first]) Type: `method` Upper-cases the first letter of every word. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `first` | `Boolean` | no | `false` | Capitalize only the first letter. | Returns: `String` The capitalized text. The text is lower-cased and each letter after a space, tab or new line is upper-cased. With `first` set to `true`, only the first letter of the whole text is upper-cased. Example: Words and first letter ```js 'hello WORLD'.capitalize(); // Hello World 'hello WORLD'.capitalize(true); // Hello world ``` ### String.parseInt([def]) Type: `method` Converts the whole string to a number. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `def` | `Number` | no | `0` | The value returned when the string is not a number. | Returns: `Number` The number, or `def`. The string is trimmed and converted with the unary `+` operator, so the whole string must be a number: `'12px'` is not a number and gives `def`. To read a number from a longer text, use `String.parseInt2()`. Example: Query parameter ```js var page = (this.query.page || '').parseInt(1); '42'.parseInt(); // 42 'abc'.parseInt(-1); // -1 ``` ### String.parseInt2([def]) Type: `method` Reads the first integer found in the text. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `def` | `Number` | no | `0` | The value returned when the text contains no number. | Returns: `Number` The number, or `def`. Unlike `String.parseInt()`, the number may be surrounded by other text. A leading `-` is kept. `String.parseFloat2()` works the same way for decimal numbers (a `,` decimal separator is accepted). Example: Number inside text ```js 'Width: 120px'.parseInt2(); // 120 'Price: 12,50 EUR'.parseFloat2(); // 12.5 ``` ### String.parseFloat([def]) Type: `method` Converts the string to a decimal number. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `def` | `Number` | no | `0` | The value returned when the string is not a number. | Returns: `Number` The number, or `def`. The string is trimmed and a `,` decimal separator is replaced with `.`. The whole string must be a number, otherwise `def` is returned. Example: Decimal comma ```js '12,5'.parseFloat(); // 12.5 'x'.parseFloat(0.1); // 0.1 ``` ### String.parseBoolean() Type: `method` Converts `true`, `1` or `on` to `true`. Returns: `Boolean` The comparison ignores case. Every other value gives `false`. Example: Checkbox value ```js var enabled = (this.body.enabled || '').parseBoolean(); 'ON'.parseBoolean(); // true ``` ### String.parseDate([format]) Type: `method` Converts the string to a `Date`. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `format` | `String` | no | | The format of the input, for example `'dd/MM/yyyy'`. | Returns: `Date` The parsed date. Without `format`, the method reads ISO strings (`2024-01-15T10:30:00.000Z`), `yyyy-MM-dd HH:mm:ss`, `dd.MM.yyyy HH:mm` and any value that `new Date()` understands. A missing date part uses today. With `format`, the digits of the string are read in the order of the format letters (`yyyy`, `MM`, `dd`, `HH`, `mm`, `ss`). A `pm` in the text adds 12 hours. Example: Parse dates ```js var a = '2024-01-15 10:30'.parseDate(); var b = '15/01/2024'.parseDate('dd/MM/yyyy'); ``` ### String.parseJSON([date]) Type: `method` Parses JSON without throwing an exception. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `date` | `Boolean` | no | `false` | Convert ISO date strings to dates. | Returns: `Object` The parsed value, or `undefined` for invalid JSON. Invalid JSON returns `undefined` instead of an error. With `date` set to `true`, ISO date strings are converted to `Date` objects. Example: Safe parse ```js var obj = '{"name":"Peter","created":"2024-01-15T10:30:00.000Z"}'.parseJSON(true); // obj.created instanceof Date === true var bad = '{name'.parseJSON(); // undefined ``` ### String.parseENV() Type: `method` Parses `KEY=value` lines (the `.env` format) into an object. Returns: `Object` The keys and their string values. Empty lines and lines starting with `#` or `//` are skipped. Values in double or single quotes lose the quotes, and `\n` becomes a new line. Unquoted values are trimmed. Example: Read a .env file ```js require('fs').readFile(PATH.root('.env'), 'utf8', function(err, text) { if (!err) { var env = text.parseENV(); console.log(env.DATABASE); } }); ``` ### String.isEmail() Type: `method` Checks whether the string is an email address. Returns: `Boolean` The test uses the `DEF.validators.email` regular expression, so you can replace it. Strings of 4 characters or less are always `false`. Example: Validate input ```js if (!this.body.email.isEmail()) { this.invalid('Invalid email'); return; } ``` ### String.isPhone() Type: `method` Checks whether the string is a phone number. Returns: `Boolean` The test uses the `DEF.validators.phone` regular expression. Strings shorter than 6 characters are always `false`. Example: Phone number ```js '+421903123456'.isPhone(); // true ``` ### String.isURL() Type: `method` Checks whether the string is a URL address. Returns: `Boolean` The test uses the `DEF.validators.url` regular expression. Strings of 7 characters or less are always `false`. Example: URL address ```js 'https://www.totaljs.com'.isURL(); // true ``` ### String.isUID() Type: `method` Checks whether the string is a valid identifier created by `UID()`. Returns: `Boolean` The method tests the format with `DEF.validators.uid` and then the checksum that `UID()` writes into every identifier, so a random string with the right characters is not accepted. Example: Validate an id from the URL ```js function detail(id) { if (!id.isUID()) { this.throw404(); return; } // ... } ``` ### String.isJSON() Type: `method` Checks whether the string looks like JSON. Returns: `Boolean` Only the first and last non-white characters are tested: `{...}`, `[...]`, `"..."` or a number. The content is not parsed; use `String.parseJSON()` for that. Example: Quick test ```js '{"a":1}'.isJSON(); // true 'hello'.isJSON(); // false ``` ### String.hash([type], [salt]) Type: `method` Creates a hash of the string. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `type` | `String|Boolean` | no | | The algorithm, or `true` for an unsigned number hash. | | `salt` | `String` | no | | Text appended before hashing. | Returns: `String|Number` A hex string for md5/sha*, otherwise a number. The `type` selects the algorithm: `'md5'`, `'sha1'`, `'sha256'`, `'sha512'` (hex strings), `'crc32'` or `'crc32unsigned'` (numbers). Without a type, the method returns a fast 32-bit number hash; `true` makes it unsigned. The `salt` is appended to the string before hashing. Example: Different hashes ```js 'hello'.hash(); // a 32-bit number 'hello'.hash(true); // an unsigned 32-bit number 'hello'.hash('sha256'); // a hex string 'hello'.hash('crc32unsigned'); ``` ### String.md5([salt]) Type: `method` Returns the MD5 hash as a hex string. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `salt` | `String` | no | | Text appended before hashing. | Returns: `String` A 32-character hex string. The `salt` is appended to the string before hashing. Use it for checksums and cache keys, not for passwords. Example: Cache key ```js var key = JSON.stringify(this.query).md5(); ``` ### String.sha256([salt]) Type: `method` Returns the SHA-256 hash as a hex string. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `salt` | `String` | no | | Text appended before hashing. | Returns: `String` A 64-character hex string. The `salt` is appended to the string before hashing. `String.sha1([salt])` and `String.sha512([salt])` work the same way with the other algorithms. Example: Hash with a salt ```js var hash = model.password.sha256(CONF.secret); var short = 'hello'.sha1(); var long = 'hello'.sha512(); ``` ### String.encode() Type: `method` Encodes HTML special characters. Returns: `String` The encoded text. Replaces `<`, `>`, `"`, `'` and `&` with HTML entities, so the text can be written safely into HTML. Example: Escape user input ```js '<script>alert("x")</script>'.encode(); // <script>alert("x")</script> ``` ### String.decode() Type: `method` Decodes HTML entities back to characters. Returns: `String` The decoded text. Named entities and numeric entities (`A`, `A`) are converted. It is the opposite of `String.encode()`. Example: Decode ```js '<b>Hello</b>'.decode(); // <b>Hello</b> ``` ### String.encrypt(key, [isUnique], [secret]) Type: `method` Encrypts the string with a key. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `key` | `String` | yes | | The encryption key. | | `isUnique` | `Boolean` | no | `false` | Make every result different. | | `secret` | `String` | no | `CONF.secret` | An additional secret. | Returns: `String` The encrypted string. With `isUnique` set to `true`, every call gives a different result for the same input. The result contains a checksum made from `secret` (default `CONF.secret`) and the key, which `String.decrypt()` checks. Use it for tokens and URLs, not for storing passwords. Example: Encrypt a token ```js var token = JSON.stringify({ id: user.id }).encrypt('my-key', true); ``` ### String.decrypt(key, [secret]) Type: `method` Decrypts a string created by `String.encrypt()`. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `key` | `String` | yes | | The encryption key. | | `secret` | `String` | no | `CONF.secret` | The additional secret. | Returns: `String` The original string, or `null`. Use the same `key` and `secret` as for encryption. A wrong key, a wrong secret or a changed string returns `null`. Example: Decrypt a token ```js var data = (this.query.token || '').decrypt('my-key'); var obj = data ? data.parseJSON() : null; ``` ### String.keywords([forSearch], [alternative], [max_count], [max_length], [min_length]) Type: `method` Extracts keywords from the text, sorted by frequency. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `forSearch` | `Boolean` | no | `true` | Normalize the words for search. | | `alternative` | `Boolean` | no | `false` | Shorten every word to 80% of its length. | | `max_count` | `Number` | no | `200` | The maximum number of words read. | | `max_length` | `Number` | no | `20` | The maximum length of a word. | | `min_length` | `Number` | no | `2` | The minimum length of a word. | Returns: `String[]` Unique words, the most frequent first. With `forSearch` (default `true`) the text is converted to ASCII and `y` becomes `i`, which makes searching tolerant. With `alternative`, each word is shortened to 80% of its length. Words shorter than `min_length` or longer than `max_length` are skipped. `String.toKeywords()` is an alias. Example: Keywords for a search index ```js var words = (item.name + ' ' + item.description).keywords(); item.search = words.join(' '); ``` ### String.toSearch() Type: `method` Normalizes the text for a full-text search. Returns: `String` The normalized text. The text is lower-cased and converted to ASCII, special characters are removed, `y` becomes `i` and repeated letters are merged. Apply it to both the stored text and the searched phrase. Example: Search value ```js var q = (this.query.q || '').toSearch(); ``` ### String.toASCII() Type: `method` Removes diacritics from the text. Returns: `String` The text without diacritics. Accented letters are replaced with their basic Latin letters, for example `á` with `a`. Example: Remove diacritics ```js 'Žltý kôň'.toASCII(); // Zlty kon ``` ### String.removeTags() Type: `method` Removes HTML tags from the text. Returns: `String` The plain text. Only the tags are removed; the text between them stays. HTML entities are not decoded. Example: Plain text ```js '<p>Hello <b>world</b></p>'.removeTags(); // Hello world ``` ### String.padLeft(max, [c]) Type: `method` Pads the string on the left to the length `max`. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `max` | `Number` | yes | | The final length. | | `c` | `String` | no | `' '` | The padding character. | Returns: `String` The padded string. A string that is already `max` characters or longer is returned unchanged. Example: Leading zeros ```js '7'.padLeft(3, '0'); // 007 ``` ### String.padRight(max, [c]) Type: `method` Pads the string on the right to the length `max`. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `max` | `Number` | yes | | The final length. | | `c` | `String` | no | `' '` | The padding character. | Returns: `String` The padded string. A string that is already `max` characters or longer is returned unchanged. Example: Fixed-width column ```js 'Name'.padRight(10) + '|'; // 'Name |' ``` ### String.startsWith(text, [ignoreCase]) Type: `method` Checks whether the string starts with `text`, optionally ignoring case. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `text` | `String` | yes | | The text to find. | | `ignoreCase` | `Boolean|Number` | no | | `true` to ignore case, or a start position. | Returns: `Boolean` Total.js replaces the native method. With `ignoreCase` set to `true` the comparison ignores case; a number is used as the start position. `String.endsWith(text, [ignoreCase])` works the same way at the end of the string. Example: Ignore case ```js 'Hello World'.startsWith('hello', true); // true 'photo.JPG'.endsWith('.jpg', true); // true ``` ### String.markdown([opt]) Type: `method` · Since: `0.0.92` Converts Markdown to HTML. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `opt` | `Object` | no | | The options described above. | Returns: `String` The HTML. The result is wrapped in `<div class="markdown markdown-container">` unless `opt.wrap` is `false`. Most features are on by default and you turn one off with `false`: `ul`, `code`, `images`, `links`, `formatting`, `icons`, `tables`, `br`, `headlines`, `hr`, `blockquotes`, `sections`, `footnotes`, `urlify`, `keywords`, `emptynewline`, `bookmarks`. Other options: `linetag` (the tag of a paragraph, default `'p'`), `prefix` (a prefix for generated ids), `custom` (a function that changes each line) and `html` (a function `function(html, type)` that changes the generated HTML). Example: Render Markdown ```js var html = '# Title\n\nSome **bold** text.'.markdown(); ``` Example: Without wrapper and images ```js var html = text.markdown({ wrap: false, images: false }); ``` ### String.tslash() Type: `method` · Since: `0.0.95` Removes trailing slashes. Returns: `String` The string without trailing slashes. All `/` characters at the end are removed, but a single `/` is kept, so `'/'` stays `'/'`. Example: Clean a URL ```js 'https://www.totaljs.com/'.tslash(); // https://www.totaljs.com '/products//'.tslash(); // /products ``` ### String.toJSONSchema([name], [url]) Type: `method` Creates a JSON schema object from an inline definition. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `name` | `String` | no | | The name of the schema used in `$id`. | | `url` | `String` | no | `CONF.url` | The base URL of `$id`. | Returns: `Object` The JSON schema. The definition is a list of `name:type` pairs separated by commas or new lines. A `*` or `!` before the name makes the field required. Types: `string`, `email`, `phone`, `url`, `uid`, `name`, `zip`, `lower`, `upper`, `capitalize`, `color`, `icon`, `base64`, `number`, `int`, `float`, `boolean`, `date`, `object`. `string(50)` sets a maximum length, `[string]` makes an array, `{draft|published}` an enum, and `@name` uses another schema. The `$id` is built from `url` (default `CONF.url`) and `name`. Example: Inline schema ```js var schema = '*name:string(50), *email:email, age:number, tags:[string], status:{draft|published}'.toJSONSchema('user'); // schema.required: ['name', 'email'] ``` ### Number.format([decimals], [separator], [separatorDecimal]) Type: `method` Formats the number with a thousands separator and 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 default thousands separator is a space. Decimals are cut (not rounded) or padded with zeros to `decimals`. The decimal separator is `.`, or `,` when the thousands separator is `.`. You can also pass the separator first: `format(',', 2)`. Example: Format prices ```js (1234567.891).format(2); // 1 234 567.89 (1234.5).format(2, '.'); // 1.234,50 (1234.5).format(2, ',', '.'); // 1,234.50 ``` ### Number.pluralize(zero, one, few, other) Type: `method` Chooses a word form by the number. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `zero` | `String` | yes | | The form for 0, or all forms separated by commas. | | `one` | `String` | no | | The form for 1. | | `few` | `String` | no | | The form for 2 to 4. | | `other` | `String` | no | | The form for other numbers. | Returns: `String` The chosen form. `zero` is used for 0, `one` for 1, `few` for 2 to 4 and `other` for the rest. A `#` in the chosen form is replaced with the number. You can also pass all forms as one comma-separated string. Example: Item count ```js var count = 3; count.pluralize('no items', '# item', '# items', '# items'); // 3 items count.pluralize('no items,# item,# items,# items'); // 3 items ``` ### Number.padLeft(max, [c]) Type: `method` Converts the number to a string padded on the left. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `max` | `Number` | yes | | The final length. | | `c` | `String` | no | `'0'` | The padding character. | Returns: `String` The padded number. The default padding character is `0`. Example: Invoice number ```js (42).padLeft(6); // 000042 ``` ### Number.padRight(max, [c]) Type: `method` Converts the number to a string padded on the right. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `max` | `Number` | yes | | The final length. | | `c` | `String` | no | `'0'` | The padding character. | Returns: `String` The padded number. The default padding character is `0`. Example: Pad right ```js (42).padRight(5); // 42000 ``` ### Number.round([precision]) Type: `method` Rounds the number to a number of decimals. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `precision` | `Number` | no | `0` | The number of decimals. | Returns: `Number` The rounded number. Without `precision` the number is rounded to an integer. Example: Round ```js (3.14159).round(2); // 3.14 (2.5).round(); // 3 ``` ### Number.floor(decimals) Type: `method` Rounds the number down to a number of decimals. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `decimals` | `Number` | yes | | The number of decimals. | Returns: `Number` The number rounded down. It works like `Math.floor()` with decimals. Example: Floor ```js (3.14959).floor(2); // 3.14 ``` ### Number.between(condition, otherwise) Type: `method` Returns a value from a map of number ranges. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `condition` | `Object` | yes | | Ranges as keys and results as values. | | `otherwise` | `Object` | yes | | The value when no range matches. | Returns: `Object` The value of the matching range. Keys of `condition` are ranges: `'1-5'` (from 1 to 5), `'10-'` (10 and more) or `'-5'` (5 and less). The value of the first matching range is returned, otherwise `otherwise`. Example: Rating label ```js var label = (4).between({ '1-2': 'bad', '3-4': 'good', '5-': 'excellent' }, 'none'); // good ``` ### Number.add(value, [decimals]) Type: `method` Applies a math operation written as a string. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `value` | `Number|String` | yes | | A number, or an operation such as `'-5'` or `'+20%'`. | | `decimals` | `Number` | no | | Round the result down to these decimals. | Returns: `Number` The result. A number is added. A string starts with an operator `+`, `-`, `*` or `/` followed by a number, for example `'+10'`. With `%` at the end the operand is a percentage of the number: `'+20%'` adds 20%. With `decimals` the result is rounded down to that number of decimals. Example: Operations ```js (100).add('+20%'); // 120 (100).add('-5'); // 95 (100).add('*2'); // 200 ``` ### Number.VAT(percentage, [decimals], [includedVAT]) Type: `method` Adds VAT to the price, or removes it. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `percentage` | `Number` | yes | | The VAT rate in percent. | | `decimals` | `Number` | no | `2` | The number of decimals. | | `includedVAT` | `Boolean` | no | `false` | The number already includes VAT. | Returns: `Number` The price. Without `includedVAT` the method returns the price with VAT. With `includedVAT` set to `true`, the number is a price with VAT and the method returns the price without it. The result is rounded to `decimals`. Example: With and without VAT ```js (100).VAT(20); // 120 (120).VAT(20, 2, true); // 100 ``` ### Number.discount(percentage, [decimals]) Type: `method` Subtracts a percentage discount. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `percentage` | `Number` | yes | | The discount in percent. | | `decimals` | `Number` | no | `2` | The number of decimals. | Returns: `Number` The discounted number. The result is rounded down to `decimals`. Example: Discount ```js (80).discount(15); // 68 ``` ### Number.filesize([decimals], [type]) Type: `method` Formats a number of bytes as a readable file size. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `decimals` | `Number` | no | | The number of decimals. | | `type` | `String` | no | | The unit: `'bytes'`, `'KB'`, `'MB'`, `'GB'` or `'TB'`. | Returns: `String` The size with the unit. Without `type` the unit is chosen automatically (`bytes`, `KB`, `MB`, `GB` or `TB`). With `type` the value is converted to that unit. Without `decimals` the value has up to 2 decimals. Example: File size ```js (1536).filesize(); // 1.50 KB (5242880).filesize(0, 'MB'); // 5 MB ``` ### Number.async(fn, [callback]) Type: `method` Runs an asynchronous function the number of times, counting down. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `fn` | `Function` | yes | | The function `function(number, next)`. | | `callback` | `Function` | no | | Called after the last run. | Returns: `Number` The function gets the current number (from the start value down to 1) and `next`. The next run starts after you call `next()`. When the count reaches zero, `callback` is called. Example: Three runs ```js (3).async(function(number, next) { console.log(number); // 3, 2, 1 setTimeout(next, 100); }, function() { console.log('Done'); }); ``` ### Date.add(type, [value]) Type: `method` Returns a new date moved by a time period. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `type` | `String|Number` | yes | | The unit, an expression such as `'5 days'`, or milliseconds. | | `value` | `Number` | no | | The amount. | Returns: `Date` A new date. Pass a type and a value (`add('days', 5)`) or one expression (`add('5 days')`). Types: `seconds`, `minutes`, `hours`, `days`, `weeks`, `months`, `years`, also the short forms `s`, `m`, `h`, `d`, `w`, `M`, `y`. Negative values move back. A number adds milliseconds. The original date is not changed. Example: Move dates ```js var expire = NOW.add('1 month'); var yesterday = NOW.add('days', -1); var later = NOW.add('2 hours'); ``` ### Date.format([format], [resource]) Type: `method` Formats the date as a string. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `format` | `String` | no | | The format, for example `'dd.MM.yyyy HH:mm'`. | | `resource` | `String` | no | | The resource file with translated month and day names. | Returns: `String` The formatted date. Without `format` the date is returned as an ISO string in UTC. Format tokens use the local time: `yyyy`, `yy`, `MM`, `M`, `MMM` (short month name), `MMMM` (month name), `dd`, `d`, `ddd` (short day name), `dddd` (day name), `HH`, `H`, `mm`, `m`, `ss`, `s`, `ww` (ISO week), `a` (AM/PM). Month and day names are English; with `resource` they are read from that resource file. Example: Formats ```js var dt = new Date(2024, 0, 15, 9, 5); dt.format('yyyy-MM-dd'); // 2024-01-15 dt.format('dd.MM.yyyy HH:mm'); // 15.01.2024 09:05 dt.format('dddd, d. MMMM'); // Monday, 15. January dt.format(); // ISO string in UTC ``` ### Date.diff([date], type) Type: `method` Returns the difference between two dates in a unit. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `date` | `Date|Number|String` | no | `now` | The date to compare with. | | `type` | `String` | yes | | The unit. | Returns: `Number` The difference. The difference is `this - date`, rounded up. Without `date` the method compares with now. Units: `seconds`, `minutes`, `hours`, `days`, `months`, `years` and the short forms `s`, `m`, `h`, `d`, `M`, `y`. A month counts as 28 days. An unknown unit gives `NaN`. Example: Days left ```js var left = item.expire.diff('days'); var age = NOW.diff(user.dtcreated, 'hours'); ``` ### Date.toUTC([ticks]) Type: `method` Shifts the date by the local timezone offset. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `ticks` | `Boolean` | no | `false` | Return milliseconds. | Returns: `Date|Number` The result shows the UTC time in the local fields of the date. With `ticks` set to `true`, the method returns milliseconds instead of a date. Example: UTC date ```js var utc = new Date().toUTC(); var ticks = new Date().toUTC(true); ``` ### Date.extend(date) Type: `method` Returns a new date with parts set from a string. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `date` | `String` | yes | | The date or time parts, for example `'12:00'` or `'2024-12-24 18:00'`. | Returns: `Date` A new date. The string may contain a date (`yyyy-MM-dd` or `dd.MM.yyyy`) and a time (`HH:mm` or `HH:mm:ss`). Only the given parts are changed; they are set in UTC. Example: Set time ```js var noon = NOW.extend('12:00'); var eve = NOW.extend('2024-12-24 18:00'); ``` ### Date.setTimeZone(timezone) Type: `method` Returns a new date converted to a timezone. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `timezone` | `String` | yes | | The IANA timezone name. | Returns: `Date` A new date. The `timezone` is an IANA name such as `'Europe/Bratislava'`. Example: Time in New York ```js var dt = new Date().setTimeZone('America/New_York'); ``` ### Array.findItem(cb, [value]) Type: `method` Returns the first matching item, or `null`. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `cb` | `Function|String` | yes | | A function or a property name. | | `value` | `Object` | no | | The value of the property. | Returns: `Object` The item, or `null`. `cb` is a function `function(item, index)`, or a property name compared with `value` (`===`). With a single non-function argument the items themselves are compared. Example: By property and by function ```js var user = users.findItem('id', id); var admin = users.findItem(item => item.role === 'admin'); ``` ### Array.findAll(cb, [value]) Type: `method` Returns all matching items. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `cb` | `Function|String` | yes | | A function `function(item, index)` or a property name. | | `value` | `Object` | no | | The value of the property. | Returns: `Array` The matching items. The arguments are the same as in `Array.findItem()`. The result is a new array. Example: Filter ```js var active = users.findAll('active', true); var adults = users.findAll(item => item.age >= 18); ``` ### Array.findIndex(cb, [value]) Type: `method` Returns the index of the first matching item, or `-1`. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `cb` | `Function|String` | yes | | A function or a property name. | | `value` | `Object` | no | | The value of the property. | Returns: `Number` The index, or `-1`. Total.js replaces the native method so it also accepts a property name and a value. A function is called as `function(item, index)`. `Array.TfindIndex()` is the same method under a name that other modules do not override. Example: Index by property ```js var index = users.findIndex('id', id); if (index !== -1) users.splice(index, 1); ``` ### Array.TfindIndex(cb, [value]) Type: `method` · Since: `0.0.95` An alias of `Array.findIndex()` that other modules do not override. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `cb` | `Function|String` | yes | | A function or a property name. | | `value` | `Object` | no | | The value of the property. | Returns: `Number` The index, or `-1`. Some NPM modules replace `Array.prototype.findIndex` with their own version. `TfindIndex()` keeps the Total.js behaviour (property name and value) in that case. `findItem()` and `findValue()` use it internally. Example: Safe index ```js var index = users.TfindIndex('id', id); ``` ### Array.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 function or a property name. | | `value` | `Object` | yes | | The value of the property. | | `path` | `String` | yes | | The property to return. | | `def` | `Object` | no | | The default value. | Returns: `Object` The property value, or `def`. The item is found like in `Array.findItem()`; then its property `path` is returned. When there is no item or the property is `null`/`undefined`, `def` is returned. Example: Name by id ```js var name = users.findValue('id', id, 'name', 'Unknown'); ``` ### Array.remove(cb, [value]) Type: `method` Returns a new array without the matching items. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `cb` | `Function|String|Object` | yes | | A function, a property name or an item. | | `value` | `Object` | no | | The value of the property. | Returns: `Array` A new array. The arguments are the same as in `Array.findItem()`. The original array is not changed, so assign the result. Example: Remove items ```js users = users.remove('id', id); numbers = [1, 2, 3, 2].remove(2); // [1, 3] ``` ### Array.take(count) Type: `method` Returns the first `count` items. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `count` | `Number` | yes | | The number of items. | Returns: `Array` A new array. The result is a new array. Example: First three ```js [1, 2, 3, 4, 5].take(3); // [1, 2, 3] ``` ### Array.skip(count) Type: `method` Returns the items after the first `count` items. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `count` | `Number` | yes | | The number of skipped items. | Returns: `Array` A new array. Together with `Array.take()` it makes simple paging. Example: Paging ```js var page = 2; var limit = 10; var items = all.skip((page - 1) * limit).take(limit); ``` ### Array.first([def]) Type: `method` Returns the first item, or `def` for an empty array. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `def` | `Object` | no | | The value for an empty array. | Returns: `Object` Example: First item ```js var item = response.items.first(null); ``` ### Array.last([def]) Type: `method` Returns the last item, or `def` for an empty array. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `def` | `Object` | no | | The value for an empty array. | Returns: `Object` Example: Last item ```js [1, 2, 3].last(); // 3 ``` ### Array.quicksort([sort], [desc]) Type: `method` Sorts the array in place. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `sort` | `String|Boolean` | no | | The properties to sort by, or `true` for descending primitive values. | | `desc` | `Boolean` | no | `false` | Sort descending. | Returns: `Array` The same array. `sort` is a property name with an optional `_asc` or `_desc` suffix, for example `'name'` or `'price_desc'`. Several properties are separated by commas (`'name_asc,price_desc'`) and nested properties use dots. Strings, numbers, booleans and dates are compared by their type. With `desc` set to `true`, the order is reversed. Without arguments, primitive values are sorted ascending; `quicksort(true)` sorts them descending. Example: Sort objects ```js products.quicksort('price_desc'); products.quicksort('category,name'); users.quicksort('dtcreated', true); ``` ### Array.toObject([name]) Type: `method` Creates an object (a lookup map) from the array. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `name` | `String` | no | | The property used as the key. | Returns: `Object` The lookup object. With `name`, each item is stored under the value of its property `name`. Without it, each item becomes a key with the value `true`. Example: Lookups ```js var byid = users.toObject('id'); var user = byid[id]; var allowed = ['admin', 'editor'].toObject(); // { admin: true, editor: true } ``` ### Array.trim() Type: `method` Trims strings and removes empty items. Returns: `Array` A new array. Strings are trimmed, and items that are empty after trimming (or are `null`, `0`, `false`) are removed. It returns a new array. Example: Clean a list ```js 'a, b, ,c'.split(',').trim(); // ['a', 'b', 'c'] ``` ### Array.wait(onItem, [callback], [thread]) Type: `method` Processes items one by one with an asynchronous function. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `onItem` | `Function` | yes | | The function `function(item, next, index)`. | | `callback` | `Function` | no | | Called after the last item. | | `thread` | `Number|Boolean` | no | `1` | The number of parallel items, or `true` to remove items. | Returns: `Array` The same array. `onItem(item, next, index)` is called for each item; call `next()` to continue. `callback` is called after the last item. `thread` sets how many items are processed at once (default 1). With `thread` set to `true`, the items are removed from the array while they are processed. Call `next('cancel')` to stop; `callback` then gets `'cancel'`. Example: Send emails one by one ```js users.wait(function(user, next) { MAIL(user.email, 'News', '=mails/news', user, next); }, function() { console.log('All sent'); }); ``` ### Array.async([thread], [callback]) Type: `method` Runs an array of asynchronous functions. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `thread` | `Number` | no | `1` | The number of parallel functions. | | `callback` | `Function` | no | | Called at the end. | Returns: `Array` The same array. Each item is a function `function(next)`. The items are removed from the array as they run. `thread` sets how many functions run at once (default 1). `callback` is called after the last function, or with `'cancel'` when a function calls `next('cancel')`. Example: A list of tasks ```js var tasks = []; tasks.push(function(next) { // load something next(); }); tasks.push(function(next) { // save something next(); }); tasks.async(function() { console.log('Done'); }); ``` ### Array.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 | | The function `function(items, next, beg, end)`. | | `callback` | `Function` | no | | Called after the last chunk. | Returns: `Array` The same array. `fn(items, next, beg, end)` gets the next chunk; call `next()` to continue with the following chunk. `callback` is called after the last chunk. Example: Insert in batches ```js rows.limit(100, function(items, next) { // insert 100 items at once next(); }, function() { console.log('Imported'); }); ``` ### Array.random([item]) Type: `method` Shuffles the array, or returns a random item. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `item` | `Boolean` | no | `false` | Return one random item. | Returns: `Array|Object` Without arguments the array is shuffled in place (Fisher-Yates) and returned. With `item` set to `true`, one random item is returned and the array is not changed. Example: Shuffle and pick ```js var deck = [1, 2, 3, 4, 5].random(); var winner = users.random(true); ``` ### String.parseCSV([delimiter]) Type: `method` Parses CSV text into an array of objects. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `delimiter` | `String` | no | `','` | The column delimiter. | Returns: `Object[]` One object per line, with the keys `a`, `b`, `c`... Every line becomes one object. The columns are named by letters: the first is `a`, the second `b` and so on. Values in double quotes may contain the delimiter and new lines, and `""` inside quotes is an escaped quote. All values stay strings, and an empty column has no key in the object. A header line is not detected, so it comes back as the first object. Example: Read a CSV file ```js var csv = 'Peter,30,"Bratislava, SK"\nAnna,25,Prague'; var rows = csv.parseCSV(); // [{ a: 'Peter', b: '30', c: 'Bratislava, SK' }, { a: 'Anna', b: '25', c: 'Prague' }] 'name;age\nPeter;30'.parseCSV(';'); ``` ### String.parseUA([structured]) Type: `method` Reads the operating system, browser and device type from a user agent string. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `structured` | `Boolean` | no | `false` | Return an object instead of a text. | Returns: `String|Object` The detected names, or `{ os, browser, device }`. Without an argument the method returns a short text with the detected names, such as `Mac Chrome` or `iOS iPhone Mobile Safari`. With `structured` set to `true` it returns an object `{ os, browser, device }`, where `device` is `desktop`, `mobile`, `tablet` or `tv`. An empty string returns an empty string. Example: Detect the client ```js var ua = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0 Safari/537.36'; ua.parseUA(); // Mac Chrome ua.parseUA(true); // { os: 'Mac', browser: 'Chrome', device: 'desktop' } // in a controller var info = (self.req.headers['user-agent'] || '').parseUA(true); ``` ### String.parseEncoded() Type: `method` Parses `application/x-www-form-urlencoded` text into an object. Returns: `Object` The parsed keys and values. The text looks like a query string: `key=value&key2=value2`. `+` becomes a space and `%xx` sequences are decoded. All values stay strings; a repeated key joins its values with a comma. Keys may contain only letters, digits and `-`, `_`, `.`, `[`, `]`, and parsing stops at the first other character in a key. The number of keys is limited by `CONF.default_request_maxkeys` and the length of a key by `CONF.default_request_maxkey`. Example: Parse a form body ```js var data = 'name=Peter+Sirka&tags=a&tags=b&city=Bratislava%2C%20SK'.parseEncoded(); // { name: 'Peter Sirka', tags: 'a,b', city: 'Bratislava, SK' } ``` ### String.parseXML([replace]) Type: `method` Parses XML into a flat object of paths and values. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `replace` | `Boolean` | no | `false` | Replace special characters in the keys with `_`. | Returns: `Object` The flat object of paths. Every element with text becomes a key made of the element names joined with dots, for example `book.title`. A repeated element gives an array of values. The attributes of an element are stored as an object under the path followed by `[]`. `CDATA` sections are read as text and comments are skipped. With `replace` set to `true`, the characters `[`, `]`, `:`, `.` and `_` in the keys are replaced with `_`. Example: Read an XML feed ```js var xml = '<book id="1"><title>Total.jsnodeweb'; var obj = xml.parseXML(); // obj['book.title'] === 'Total.js' // obj['book.tag'] => ['node', 'web'] // obj['book[]'] => { id: '1' } ``` ### String.parseHTML([trim]) Type: `method` · Since: `0.0.67` Parses HTML into a tree of elements that you can search and change. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `trim` | `Boolean` | no | `false` | Trim the text content. | Returns: `HTMLElement` The root element of the parsed document. The method uses the built-in HTML parser and returns the root element. Elements have `tagName`, `attrs`, `children` and `parentNode`, and the methods `find(selector)`, `closest(selector)`, `parent()`, `attr()`, `aclass()`, `rclass()`, `hclass()`, `tclass()`, `css()`, `append()`, `prepend()`, `remove()`, `text()` and `html([formatted])`. With `trim` set to `true`, the text inside the elements is trimmed. Example: Read and change HTML ```js var dom = ''.parseHTML(true); var links = dom.find('a'); for (var i = 0; i < links.length; i++) links[i].attr('target', '_blank'); console.log(dom.html()); ``` ### String.parseComponent(tags) Type: `method` Cuts tagged blocks out of a text and returns their content by name. | Parameter | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `tags` | `Object` | yes | | The name and the opening tag of each block. | Returns: `Object` The content of every block that was found. `tags` maps a name to an opening tag, for example `{ js: '\n
    '; var parts = html.parseComponent({ css: '