Application structure and modes
F.run() and its start options, LOAD(), IMPORT(), REQUIRE(), MODS and the framework statistics.
On this page
The functions that start and load a Total.js 5 application: F.run() with every start option, F.http(), LOAD(), IMPORT(), REQUIRE(), MODS, F.restart(), F.exit(), the statistics in F.stats and F.consumption, the watcher events and the bundling key.
The guide Application structure and modes explains the folders, the loading order, debug and release mode, bundles and remote editing.
The Test runner has its own page: Unit tests.
API
method
F.run([options])
Starts the application in debug mode with the watcher, or in release mode.
F.run([options])| Parameter | Type | Description |
|---|---|---|
options? |
Object |
The start options: ip, port, unixsocket, config, load, watcher, release, servicemode, watch, livereload, inspector, debugger, cluster, limit, edit, editmcp. Default: {} |
Returns undefined
The usual last line of the start script. Without options.watcher = false it starts the debug watcher (debug.js): the application runs in a child process and restarts when a file changes. With watcher: false it starts release mode (release.js): the application runs in the same process with DEBUG = false. The options are passed to F.http() (or to LOAD() in service mode) in the application process. Total.run() is the same function.
require('total5');
F.run({ port: 8000 });
require('total5');
F.run({ watcher: false, port: 8000 });
require('total5');
var options = {};
options.port = 8000;
if (process.argv.includes('--release'))
options.watcher = false;
F.run(options);
method
F.http([options])
Loads the application and starts the HTTP server in the current process.
F.http([options])| Parameter | Type | Description |
|---|---|---|
options? |
Object |
ip, port, unixsocket, unixsocket777, config, load (alias type) and clear. Default: {} |
Returns undefined
Applies options.config with LOADCONFIG(), calls LOAD() with options.load and then starts the server. When the application is already loaded, it only (re)starts the server; a running server is closed first. With the default CONF.$port = 'auto', the port is taken from options.port, then from the PORT environment variable, then from the first argument of the process with 3 to 5 digits (node index.js 8000), and the default is 8000. When the process has no parent, it prints the start information.
F.run() calls it for you; call it directly in scripts that start the server without a watcher (tests, tools).
require('total5');
F.http({ port: 8001, config: { name: 'Test' } });
method
LOAD([types], [callback], [clear])
Loads the configuration, the resources and the JavaScript files of the application.
LOAD([types], [callback], [clear])| Parameter | Type | Description |
|---|---|---|
types? |
String|Array |
The parts to load, as a comma-separated string or an array; empty loads everything. Default: '' |
callback? |
Function |
function() called when everything is loaded. |
clear? |
Boolean |
Clears the temporary folder before loading. Default: true |
Returns Promise Resolves when everything is loaded.
F.load() is the same function. It sets the directories, builds bundles, removes the .js, .css, .html, .htm, .tmp and .upload files from the temporary folder (when clear is true) and then loads the parts in the order of the guide. Without types it loads everything. The names are env, config, version, resources, jsonschemas, extensions, modules, actions, schemas, models, definitions, controllers, middleware, plugins, flowstreams and stats; any other name, such as none, loads nothing. When types is given without stats, the statistics and the source maps are turned off.
At the end it starts the service timer, sets F.isLoaded, F.stats.compiled and F.stats.compilation, calls callback and emits ready and load. It does not start the HTTP server.
require('total5');
LOAD('config,modules,actions', function() {
ACTION('Jobs/run').callback(console.log);
});
require('total5');
(async function() {
await LOAD('env,config');
console.log(CONF.name);
})();
method
IMPORT(url, [callback])
Downloads a JavaScript file and loads it as a module.
IMPORT(url, [callback])| Parameter | Type | Description |
|---|---|---|
url |
String |
URL of a .js file. |
callback? |
Function |
function(err, module, response) |
Returns Promise When callback is not set.
The file is downloaded into the temporary folder and loaded with require(). Further calls with the same URL in the same process return the loaded module without downloading it again. An answer with the status 400 or more gives the error The address answered with the status <status> and nothing is loaded. A file that is not a valid module gives the error of require(), for example a SyntaxError. The callback receives (err, module, response); without a callback the function returns a Promise with the module.
var helpers = await IMPORT('https://cdn.example.com/helpers.js');
helpers.hello();
IMPORT('https://cdn.example.com/helpers.js', function(err, helpers) {
if (err)
console.error(err);
else
helpers.hello();
});
method
REQUIRE(name)
Loads a Node.js module or an NPM package.
REQUIRE(name)| Parameter | Type | Description |
|---|---|---|
name |
String |
The name of the module or package. |
Returns Object The module.
Names with the node: prefix and Node.js built-in modules (fs, path, crypto, ...) are loaded directly. Other names are loaded with require() and, when that fails, from the folder in CONF.$nodemodules (<application>/node_modules by default), so packages installed with NPMINSTALL() are found. It throws when the module cannot be loaded.
var Fs = REQUIRE('fs');
var mqtt = REQUIRE('mqtt');
property
MODS
The loaded modules from the modules folder, by their id.
MODSReturns Object
The same object as F.modules. Each file in modules is registered under its exports.id, or under the file name without .js when id is missing, before its install() is called. Use it to call the functions that a module exports.
// modules/counter.js
exports.id = 'counter';
var count = 0;
exports.increment = function() {
return ++count;
};
// a controller or an action
MODS.counter.increment();
property
F.isLoaded
true when the application is loaded.
F.isLoadedReturns Boolean
Set by LOAD() after all files are loaded, just before the ready and load events.
if (F.isLoaded)
console.log('Ready');
property
F.directory
The root folder of the application.
F.directoryReturns String
The current working directory of the process when total5 is loaded. When the application runs from bundles, it points to the .src folder. All PATH.root() paths start here.
console.log(F.directory);
console.log(PATH.root('config'));
property
F.isBundle
true when the application runs from bundles.
F.isBundleReturns Boolean
Set when the bundles folder contains bundles (or bundles.debug exists) and the application was built into .src.
if (F.isBundle)
console.log('Running from', F.directory);
method
F.dir([directory])
Sets the root folder and recomputes the folders of the application.
F.dir([directory])| Parameter | Type | Description |
|---|---|---|
directory? |
String |
A new root folder. |
Returns undefined
With directory it changes F.directory. Then it sets the paths in F.temporary.directories for public, tmp, logs, databases, controllers, resources, plugins, modules, views, definitions, schemas, models, flowstreams, bundles, actions, extensions, source, services, updates, templates, private and scripts: each one is the value of CONF.$dir<name> when it is set, otherwise <root>/<name>. LOAD() calls it at the start.
F.dir();
console.log(F.temporary.directories.public);
method
F.restart()
Asks the watcher to restart the application.
F.restart()Returns undefined
Sends total:restart to the parent process. The debug watcher, and the release watcher started with --watcher, print RES and start the application again. Without a watcher nothing happens.
NEWACTION('Settings/save', {
input: '*name:String',
action: function($, model) {
F.Fs.writeFile(PATH.root('config'), 'name : ' + model.name, function() {
$.success();
F.restart();
});
}
});
method
F.exit([signal])
Stops the application.
F.exit([signal])| Parameter | Type | Description |
|---|---|---|
signal? |
Number |
The signal for the child processes. Default: 15 |
Returns undefined
Kills the workers and Python pipelines with signal, destroys the FlowStream instances, emits exit, tells the parent process total:stop, stops the service timer and closes the HTTP server. The process ends 300 ms later. The framework calls it on SIGTERM, SIGINT and when the process exits.
ON('exit', function() {
console.log('Bye');
});
F.exit();
method
F.console()
Prints the start information.
F.console()Returns undefined
Prints the PID, the versions of Node.js and Total.js, the system, the memory, the user, the name, version and author of the application, the date with the time zone, the mode (debug or release), the number of compiled files with the time, the root, directory and node_modules paths and the address of the server. Nothing is printed when CONF.$imprint is false. The framework calls it after the start.
ON('ready', function() {
F.console();
});
method
F.remote(url, [directory])
Connects the folder of the application to the Total.js Code Editor.
F.remote(url, [directory])| Parameter | Type | Description |
|---|---|---|
url |
String |
The URL from the editor, wss://...?id=project. |
directory? |
String |
The folder to edit. Default: F.directory |
Returns undefined
Starts the remote editing client in the current process: a WebSocket connection to url that lets the editor browse and change the files in directory. It reconnects every 10 seconds when the connection is lost. The edit start option does the same in the watcher process.
F.remote('wss://code.example.com/?id=myproject');
property
F.consumption
The usage statistics of the process, updated once a minute.
F.consumptionReturns Object
The same object every minute (the first time 5 seconds after the application is loaded); ON('$stats') gets it too and, with CONF.$stats, it is written into <script>.json. Fields: id, pid, thread, mode (debug or release), version (node, total, build, app from CONF.version), app (name and url from the configuration), date, memory (used heap in MB), requests, pending, external, errors, timeouts, online (WebSocket clients), download and upload (MB in total), lasterror, lasttimeout, usage (percent), overload (hours with high load), uptime (minutes since the start) and the per-minute counters rm, fm, wm, em, mm, om, dm, um, pm, sm, cm, dbrm and dbwm.
setInterval(function() {
console.log(F.consumption.memory, 'MB', F.consumption.requests, 'requests');
}, 60000);
property
F.stats
Counters of the framework for the whole life of the process.
F.statsReturns Object
F.stats.request counts requests (request, web, xhr, file, websocket, get, post, put, patch, delete, upload, mobile, desktop, blocked, pending, size ...), F.stats.response counts responses by type (json, html, file, redirect, stream, timeout, error404, error500 ...), F.stats.performance holds the per-minute values, F.stats.error the number of errors, and F.stats.compiled and F.stats.compilation the number of loaded files and the loading time in ms.
ROUTE('GET /stats/', function($) {
var s = F.stats;
$.json({ requests: s.request.request, errors: s.error, notfound: s.response.error404 });
});
event
ON('$watcher', function(child) {})
Emitted in the debug watcher after it starts the application process.
ON('$watcher', function(child) {})| Parameter | Type | Description |
|---|---|---|
child |
ChildProcess |
The process of the application. |
It runs in the watcher process, not in the application, after each start or restart. child is the ChildProcess of the application. Register it in the start script before F.run().
require('total5');
ON('$watcher', function(child) {
console.log('Application PID:', child.pid);
});
F.run();
event
ON('watcher', function(child) {})
Emitted in the release watcher after it starts the application process.
ON('watcher', function(child) {})| Parameter | Type | Description |
|---|---|---|
child |
ChildProcess |
The process of the application. |
Release mode started with --watcher only. It runs in the watcher process after each start. child is the ChildProcess of the application.
require('total5');
ON('watcher', function(child) {
console.log('Started PID:', child.pid);
});
F.run({ watcher: false });
property
options.ip = String
The IP address the server listens on.
options.ip = StringReturns String Default: CONF.$ip (0.0.0.0)
Stored into CONF.$ip. The default 0.0.0.0 listens on all interfaces.
F.run({ ip: '127.0.0.1', port: 8000 });
property
options.port = Number
The port of the server.
options.port = NumberReturns Number Default: 8000
Stored into CONF.$port. Without it the port comes from the PORT environment variable or a numeric argument of the process (node index.js 8000), and the default is 8000.
F.run({ port: parseInt(process.argv[2]) || 8000 });
property
options.unixsocket = String
Listens on a Unix socket instead of a port.
options.unixsocket = StringReturns String
An existing socket file is removed first. On Windows the path is placed into the named pipe space. Stored into CONF.$unixsocket.
F.run({ unixsocket: require('node:path').join(require('node:os').tmpdir(), 'app_name') });
property
options.unixsocket777 = Boolean
Gives the Unix socket the permissions 777.
options.unixsocket777 = BooleanReturns Boolean Default: false
With unixsocket, the socket file gets chmod 777 when it is created, so another user (for example the web server) can connect to it.
F.run({ unixsocket: '/tmp/app.socket', unixsocket777: true });
property
options.config = Object
Configuration keys applied before the application is loaded.
options.config = ObjectReturns Object
Every key is applied with LOADCONFIG() before LOAD(). The config file is read later and can override them. Use it for keys that are needed before the config file is read, such as bundling.
F.run({ config: { name: 'My app', bundling: 'shallow' } });
property
options.load = String
The parts of the application that are loaded.
options.load = StringReturns String Default: ''
Passed to LOAD(): a comma-separated list such as 'config,controllers'. Empty loads everything; 'none' starts only the web server. options.type is an alias.
F.http({ load: 'none', port: 8000 });
property
options.watcher = Boolean
false starts release mode.
options.watcher = BooleanReturns Boolean Default: true
With F.run(), false runs the application in release mode in the current process; any other value starts the debug watcher. In release mode the --watcher argument of the process starts a release watcher that restarts the application when it ends.
F.run({ watcher: false });
property
options.release = Boolean
Runs the application with DEBUG = false under the debug watcher or the cluster.
options.release = BooleanReturns Boolean Default: false
In debug mode the watcher still restarts the application on changes, but the application runs with DEBUG = false. With cluster it starts the threads in release mode without the watcher.
F.run({ cluster: 4, release: true });
property
options.servicemode = Boolean|String
Loads the application without the HTTP server.
options.servicemode = Boolean|StringReturns Boolean|String
true loads everything, a string loads the listed parts (the names of LOAD()), for example 'config,modules,actions'.
F.run({ servicemode: 'config,modules,actions' });
property
options.watch = Array
More folders for the debug watcher.
options.watch = ArrayReturns Array
Paths relative to the root of the application. A leading and a trailing slash are removed.
F.run({ watch: ['adminer', '/libs/'] });
property
options.livereload = String
Sends changed files to the Total.js live reload service.
options.livereload = StringReturns String
The hostname of your application (http:// and https:// are removed). The debug watcher connects to wss://livereload.totaljs.com/?hostname=<hostname> and sends the name of each changed .js, .ts, .py, .css, .html, .htm, .jpg, .png, .gif, .ico, .svg, .webp or .resource file, including files in public and views (other files in the folders are not watched); changes in public and views do not restart the application.
F.run({ livereload: 'myapp.example.com' });
property
options.inspector = Number
Starts the application process with the Node.js inspector.
options.inspector = NumberReturns Number Default: 9229
The debug watcher adds --inspect=<port> to the Node.js arguments of the application. The same happens when the watcher itself was started with --inspect, with the port 9229.
F.run({ inspector: 9229 });
property
options.debugger = Number
Starts the application process with --debug=<port>.
options.debugger = NumberReturns Number Default: 40894
The debug watcher adds --debug=<port> to the Node.js arguments of the application. The same happens when the watcher was started with --debug, with the port 40894.
F.run({ debugger: 40894 });
property
options.cluster = Number|String
Runs the application in several cluster threads.
options.cluster = Number|StringReturns Number|String
A number of threads, or 'auto': it starts with one thread and adds a thread when the average latency of the threads is above 70 ms, up to options.limit. In debug mode the watcher restarts all threads after a change; with release: true there is no watcher. Every thread loads the whole application.
F.run({ cluster: 4, port: 8000 });
F.run({ cluster: 'auto', limit: 8, release: true });
property
options.limit = Number
The maximum number of threads for cluster: 'auto'.
options.limit = NumberReturns Number
Without it, the automatic cluster adds threads without a limit.
F.run({ cluster: 'auto', limit: 4 });
property
options.edit = String
Connects the application to the Total.js Code Editor.
options.edit = StringReturns String
The URL from the editor (wss://...?id=project; http is changed to ws). The client runs in the debug watcher, or in the release watcher started with --watcher, and starts the application one second later.
F.run({ edit: 'wss://code.example.com/?id=myproject' });
property
options.editmcp = String
Connects the application to an MCP edit proxy, so an AI agent can work on its files.
options.editmcp = StringReturns String
The URL of the WebSocket route of the proxy with the id of the project (wss://proxy.example.com/$mcp/?id=myproject; http is changed to ws). The client runs in the watcher (so not with watcher: false), reconnects every 10 seconds and starts the application one second later. When edit is set too, edit is used.
The proxy is another Total.js application with $mcp : true that passes its WebSocket route to require('total5/edit-mcp').proxy(). Its MCP endpoint /$mcp/?id=myproject lists the tools App_info, App_tree, App_read, App_write, App_delete, App_restore, App_move, App_mkdir, App_search, App_logs, App_shell and App_restart and runs them in the connected application with the id myproject; without a connected application the tools answer App is offline.. Paths are relative to the application root, with or without the leading /. App_write saves every written content as a numbered revision in the folder revisions/ of the application, App_read returns the current revision number and App_restore the content of a revision, App_move moves the revisions with the files and App_delete removes them (/ cannot be deleted). App_shell runs any shell command in the application folder, so protect the proxy with Total.mcp.auth.
F.run({ editmcp: 'wss://proxy.example.com/$mcp/?id=myproject' });
// config: $mcp : true
const editmcp = require('total5/edit-mcp');
ROUTE('SOCKET /$mcp/', function($) {
editmcp.proxy($);
});
Total.mcp.auth = function($) {
if ($.token === CONF.mcp_token)
$.success({ id: 'agent', name: 'Agent', sa: true });
else
$.invalid();
};
// the AI client connects to https://proxy.example.com/$mcp/?id=myproject
config
bundling : shallow
shallow reuses the extracted .src folder instead of building it again.
bundling : shallowReturns String
When it is shallow and .src/bundle.json exists, the bundles are not extracted and the files are not copied; the application runs from the existing .src. Bundles are processed before the config file is read, so set the key in options.config.
F.run({ watcher: false, config: { bundling: 'shallow' } });