Spanish Total.js
English
Documentation For AI agents
Contents

Application structure

Start scripts, directories, bundles, packages and global loaders.

.md GitHub
On this page

The functions, flags and options that define how a Total.js 4 application is started and loaded. The guide Application structure and modes explains the load order, the debug and release modes and bundles with examples; this page is the exact reference.

Testing has its own page: Testing.

API

command

require('total4/debug')(options)

Starts the application in debug mode with a watcher that restarts it on changes.
ParameterTypeDescription
options? Object Start options (port, ip, watch, livereload, inspector, servicemode, https, config...). Default: {}

The module exports a function that takes the start options. The calling process becomes the watcher: it forks the start script as a child process, watches the application directories and restarts the child when a file changes. The child runs HTTP('debug', options) (or HTTPS() with options.https, or LOAD() with options.servicemode). DEBUG is true. The watcher writes {script}.pid; deleting the file ends both processes.

index.js
var options = {};
// options.port = 8000;
// options.watch = ['adminer'];
require('total4/debug')(options);
command

require('total4/release')(options)

Starts the application in release mode.
ParameterTypeDescription
options? Object Start options. Default: {}

The module exports a function that takes the same start options as total4/debug. RELEASE is true and files are not watched. By default the application runs in the current process. With the --watcher argument or options.watcher, the process becomes a supervisor: it forks the start script and starts it again when it exits or sends total:restart. The process writes {script}.pid; deleting the file ends it.

index.js
var options = {};
// options.port = 8000;
require('total4/release')(options);
Run with a supervisor
node index.js --watcher
method

HTTP(mode, [options], [middleware])

Starts the HTTP server and loads the application.
ParameterTypeDescription
mode String 'debug' or 'release'.
options? Object Start options (port, ip, unixsocket, config, bundling...). Default: {}
middleware? Function(listen) Called instead of listen() when the application is loaded.

total4/debug and total4/release call it for you. mode is 'debug' or 'release'. It extracts bundles, reads the configuration, loads all directories in their order, starts listening and emits load and ready. With middleware, the server is not started until you call listen().

Without the start modules
require('total4');
HTTP('release', { port: 8000 });
method

HTTPS(mode, [options], [middleware])

Starts an HTTPS server and loads the application.
ParameterTypeDescription
mode String 'debug' or 'release'.
options? Object Start options with https: { key, cert }. Default: {}
middleware? Function(listen) Called instead of listen().

Works like HTTP(). Pass the certificate in options.https as { key, cert }: Buffers, file paths, or base64 strings.

Certificate files
require('total4');
HTTPS('release', { port: 443, https: { key: 'keys/server.key', cert: 'keys/server.crt' } });
config

options.port

The port of the HTTP server.

Returns Number

When it is missing, a free numeric command-line argument is used, then CONF.default_port. CONF.default_port = 'auto' reads process.env.PORT. The fallback is 8000.

Port
options.port = 8000;
config

options.ip

The IP address the server listens on.

Returns String

Defaults to CONF.default_ip, then '0.0.0.0'. The values 'null', 'undefined' and 'auto' let Node.js choose.

Localhost only
options.ip = '127.0.0.1';
config

options.config

Configuration values that override the configuration files.

Returns Object

The object is merged into CONF when the server starts.

Name
options.config = { name: 'Shop' };
config

options.watch

More directories for the debug watcher.

Returns String[]

An array of paths relative to the application directory. Changes in them restart the application, like changes in the standard directories. Only total4/debug reads it.

Watch a directory
options.watch = ['adminer', 'lib'];
config

options.livereload

Reloads the browser when views, public files or scripts change.

Returns Boolean|Number|String

Only for total4/debug. true starts a WebSocket server on port 35729; a number sets another port. A string (a hostname) connects to the Total.js live reload service instead. Views and public files do not restart the application, they only reload the page.

Live reload
options.livereload = true;
config

options.inspector

Starts the application with the Node.js inspector.

Returns Number

The value is the port of --inspect (default 9229). Only for total4/debug; the watcher adds the argument to the forked process.

Inspector
options.inspector = 9229;
config

options.servicemode

Starts the application without the HTTP server.

Returns Boolean|String|String[]

true loads everything with LOAD(); a string or an array is passed to LOAD() as the list of types. Use it for background services.

Service
options.servicemode = 'config,definitions,modules,operations';
require('total4/release')(options);
config

options.watcher

Runs total4/release with a supervisor process.

Returns Boolean

With true, the release process forks the application and starts it again when it exits. The --watcher command-line argument does the same.

Supervisor
options.watcher = true;
require('total4/release')(options);
config

options.bundling

Controls whether bundles are extracted on start.

Returns Boolean

false skips extracting /bundles/ into /.src/, but the application still runs from /.src/ when /bundles/ exists. Use it when the bundles are already extracted.

Skip extracting
options.bundling = false;
method

LOAD([types], [directory], [callback])

Installs the application without starting the HTTP server.
ParameterTypeDescription
types? String|String[] What to load. Default: ['nobundles', 'nopackages', 'nocomponents', 'nothemes']
directory? String The application directory. Default: the directory of the script
callback? Function Called when the application is loaded.

Returns Promise Only when callback is missing.

types is an array or a string separated by commas or spaces: jsonschemas, modules, packages, models, schemas, actions, tasks, operations, themes, definitions, controllers, components, middleware, builds, extensions, plugins, flowstreams, preferences, bundles, versions, sitemap, service. A name with the prefix no excludes it ('nocontrollers'). When at least one name has no prefix, only the listed types are loaded. Without types everything is loaded except bundles, packages, components and themes. Add debug to run in debug mode (otherwise RELEASE is true). Without service, the internal cache timer is stopped. directory sets the application directory; '..' means the parent of the script. The configuration is always read. ready is emitted 500 ms after loading. Without a callback it returns a Promise.

A script
require('total4');

LOAD('config,definitions,models', function() {
	MODEL('product').refresh();
});
Promise
require('total4');

async function main() {
	await LOAD('definitions,operations', '..');
	OPERATION('cleanup', NOOP);
}

main();
delegate

exports.install = function([options])

Runs once when the framework installs a file.
ParameterTypeDescription
options? Object The configuration value for this file, or undefined.

Every script in an installed directory can export it. The framework calls it right after require() and then deletes it. options is the configuration value CONF['{type}_{name}'], for example CONF.module_mail for /modules/mail.js. Types are module, model, schema, action, task, operation, definition, controller, middleware, theme, plugin, package and source. After it, the framework emits ON('install', type, name, module) and ON('{type}_{name}', module).

A module
// /modules/counter.js
var count = 0;

exports.install = function(options) {
	count = (options && options.start) || 0;
};

exports.increment = function() {
	return ++count;
};
method

MODULE(name)

Returns an installed module.
ParameterTypeDescription
name String The name of the module.

Returns Object The exports of the module, or null.

Modules come from /modules/ and packages. The name is the file name without the extension (with subdirectories, folder/name). A module that exports id is also available under that id. Returns null when the module does not exist.

Use a module
MODULE('mail').send('info@example.com', 'Hello');
property

MODS

All installed modules by name.

Returns Object

The same object as F.modules. MODS.mail equals MODULE('mail'), except that a missing module gives undefined.

Iterate
for (var name in MODS)
	console.log(name);
property

PLUGINS

All installed plugins by name.

Returns Object

The same object as F.plugins. A plugin is plugins/{name}/index.js or (an .html plugin) plugins/{name}.html. Each plugin gets id (its name). An .html plugin runs the code of its <script total> block, and every <file name="..."> block is written to a temporary file listed in plugin.files.

A plugin
// /plugins/dashboard/index.js
exports.install = function() {
	ROUTE('GET /dashboard/', function() {
		this.plain('Dashboard');
	});
};

// anywhere else
PLUGINS.dashboard.id; // 'dashboard'
method

MODEL(name)

Returns an installed model.
ParameterTypeDescription
name String The name of the model.

Returns Object The exports of the model.

Models come from /models/. The name is the file name without the extension. Returns undefined when the model does not exist.

A model
// /models/product.js
exports.price = function(item) {
	return item.price * 1.2;
};

// anywhere else
var price = MODEL('product').price({ price: 10 });
method

INCLUDE(name)

Loads a script from /source/ the first time you ask for it.
ParameterTypeDescription
name String The file name without the extension.

Returns Object The exports of the script, or null.

SOURCE() is an alias. The file /source/{name}.js is installed (its exports.install() runs) and cached. The next calls return the cached exports. Returns null when the file does not exist.

Lazy loading
var pdf = INCLUDE('pdf');
pdf && pdf.render(data);
method

REQUIRE(path)

Requires a script relative to the application directory.
ParameterTypeDescription
path String The path relative to the application directory.

Returns Object The exports of the script.

It is require(F.directory + '/' + path). Use it to load your own libraries without relative paths that depend on the current file.

A library
var tools = REQUIRE('lib/tools.js');
method

IMPORT(url, [callback])

Downloads a script from a URL and requires it.
ParameterTypeDescription
url String The URL of a JavaScript file.
callback? Function(err, module, response) Called when the script is loaded.

The script is saved to the temporary directory and require()d. The next calls in the same process return the same module without downloading. Import only code from a source you trust: it runs with the full rights of the application.

Remote code
IMPORT('https://example.com/helpers.js', function(err, helpers) {
	if (!err)
		helpers.init();
});
property

F.version

The version of the framework as a number.

Returns Number

It is 4099. F.is4 has the same value. Use it to check a minimal version.

Check
if (F.version < 4096)
	console.warn('Update Total.js');
property

F.version_header

The major version as a string.

Returns String

It is '4'. It is part of the user agent of ACTION() requests and of the version in F.usage().

property

F.version_node

The version of Node.js.

Returns String

The value of process.version, for example 'v18.17.0'.

property

F.version_node2

since 0.0.96 The version of Node.js as a number.

Returns Number

process.version without v and dots, parsed as an integer: 'v18.17.0' gives 18170.

Compare
if (F.version_node2 >= 18000)
	console.log('Node.js 18 or newer');
property

F.isBundle

true when the application runs from extracted bundles.

Returns Boolean

The application directory is then /.src/, not the directory of the start script.

property

F.isLoaded

true when all directories are installed.

Returns Boolean

It is set before load and ready are emitted.

Wait for loading
WAIT(() => F.isLoaded, function() {
	// the application is ready
});
property

isWORKER

true when the application was started with LOAD().

Returns Boolean

It is false otherwise. F.isWorker is similar, but it is true until HTTP() or HTTPS() starts the server.

Skip in scripts
if (!isWORKER)
	SCHEDULE('03:00', '1 day', cleanup);
property

is_server

Always true in the framework.

Returns Boolean

is_client is always false. They let code that is shared with the browser detect where it runs.

Shared code
if (typeof(is_server) !== 'undefined' && is_server)
	exports.format = format;
type

/bundles/{name}.bundle

A file that contains a whole application or a part of it.

Bundles in /bundles/ are extracted into /.src/ on start, then the files of the application are copied over them and the application runs from /.src/. config*, sitemap, versions, workflows, dependencies and .resource files are merged. A file whose name starts with -- is appended to the file of the same name without the prefix. Existing files in /databases/ and /updates/ are kept. A {name}.url file with a URL downloads the bundle on start. Files that end with -bk.bundle or _bk.bundle are skipped. Create a bundle with total4 bundle.

Structure
/bundles/cms.bundle
/bundles/extra.url
/views/index.html		  <- overrides the view from the bundle
/public/css/--custom.css   <- appended to /public/css/custom.css
/config					 <- merged with the config of the bundle
type

/bundles.debug

Runs the application from /.src/ without extracting the bundles again.

When this file exists in the root, the framework uses /.src/ as it is and the debug watcher watches the files there, together with the views and public files. Use it to edit the extracted files of a bundle directly.

type

/.bundleignore

Paths that are not copied into /.src/ when bundles are extracted.

One rule per line: /path/ skips the directory with everything in it, /path/*.ext skips files with the extension in that directory, /path/file.ext skips one file. The older name .bundlesignore also works.

Rules
/tests/
/public/img/*.psd
/views/demo.html
config

bundling

Set to shallow to keep the extracted bundles.

Returns String

With bundling : shallow in the configuration, the framework does not clean /.src/ and does not extract the bundles again when /.src/bundle.json exists.

config
bundling		  : shallow
command

total4 bundle [filename]

Creates a bundle from the current directory.
ParameterTypeDescription
filename? String The name of the bundle file, with the .bundle extension. Default: app.bundle

The default file name is app.bundle. The start scripts, .pid files, package.json, readme.md, license.txt, /bundles/, /tmp/, /.src/ and /.git/ are left out. The opposite command, total4 extract <filename>, extracts a bundle or a package into the current directory.

Create
total4 bundle cms.bundle
Extract
total4 extract cms.bundle
method

PATH.package(name, [filename])

Returns the path to a file in an extracted package.
ParameterTypeDescription
name String The name of the package.
filename? String A file inside the package.

Returns String The absolute path.

Packages in /packages/ (name.package files or directories) are extracted into the temporary directory and their index.js is installed. PATH.package('name/file') is the same as PATH.package('name', 'file'). WORKER('@name/file') and similar functions use it for the @ prefix.

Read a template
var html = F.Fs.readFileSync(PATH.package('invoices/template.html'), 'utf8');
Made in Europe