---
title: Application structure and modes
project: Total.js V5
version: 0.0.20
section: reference
language: en
license: MIT
url: https://totaljs.es/docs/total-js-v5/0-0-20/reference/application-structure/
updated: 2026-11-18T16:57:34.578Z
---

# Application structure and modes

> F.run() and its start options, LOAD(), IMPORT(), REQUIRE(), MODS and the framework statistics.

The functions that start and load a Total.js 5 application: `F.run()` with every start option, `F.http()`, `LOAD()`, `IMPORT()`, `REQUIRE()`, `MODS`, `F.restart()`, `F.exit()`, the statistics in `F.stats` and `F.consumption`, the watcher events and the `bundling` key.

The guide [Application structure and modes](../../guides/application-structure/) explains the folders, the loading order, debug and release mode, bundles and remote editing.

The `Test` runner has its own page: [Unit tests](../unit-tests/).

## API

### F.run([options])

Type: `method`

Starts the application in debug mode with the watcher, or in release mode.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `options` | `Object` | no | `{}` | The start options: `ip`, `port`, `unixsocket`, `config`, `load`, `watcher`, `release`, `servicemode`, `watch`, `livereload`, `inspector`, `debugger`, `cluster`, `limit`, `edit`, `editmcp`. |

Returns: `undefined`

The usual last line of the start script. Without `options.watcher = false` it starts the debug watcher (`debug.js`): the application runs in a child process and restarts when a file changes. With `watcher: false` it starts release mode (`release.js`): the application runs in the same process with `DEBUG = false`. The options are passed to `F.http()` (or to `LOAD()` in service mode) in the application process. `Total.run()` is the same function.

Example: Debug mode
```js
require('total5');
F.run({ port: 8000 });
```

Example: Release mode
```js
require('total5');
F.run({ watcher: false, port: 8000 });
```

Example: Mode from the command line
```js
require('total5');

var options = {};
options.port = 8000;

if (process.argv.includes('--release'))
	options.watcher = false;

F.run(options);
```

### F.http([options])

Type: `method`

Loads the application and starts the HTTP server in the current process.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `options` | `Object` | no | `{}` | `ip`, `port`, `unixsocket`, `unixsocket777`, `config`, `load` (alias `type`) and `clear`. |

Returns: `undefined`

Applies `options.config` with `LOADCONFIG()`, calls `LOAD()` with `options.load` and then starts the server. When the application is already loaded, it only (re)starts the server; a running server is closed first. With the default `CONF.$port = 'auto'`, the port is taken from `options.port`, then from the `PORT` environment variable, then from the first argument of the process with 3 to 5 digits (`node index.js 8000`), and the default is `8000`. When the process has no parent, it prints the start information.

`F.run()` calls it for you; call it directly in scripts that start the server without a watcher (tests, tools).

Example: Server for tests
```js
require('total5');
F.http({ port: 8001, config: { name: 'Test' } });
```

### LOAD([types], [callback], [clear])

Type: `method`

Loads the configuration, the resources and the JavaScript files of the application.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `types` | `String|Array` | no | `''` | The parts to load, as a comma-separated string or an array; empty loads everything. |
| `callback` | `Function` | no |  | `function()` called when everything is loaded. |
| `clear` | `Boolean` | no | `true` | Clears the temporary folder before loading. |

Returns: `Promise` Resolves when everything is loaded.

`F.load()` is the same function. It sets the directories, builds bundles, removes the `.js`, `.css`, `.html`, `.htm`, `.tmp` and `.upload` files from the temporary folder (when `clear` is `true`) and then loads the parts in the order of the guide. Without `types` it loads everything. The names are `env`, `config`, `version`, `resources`, `jsonschemas`, `extensions`, `modules`, `actions`, `schemas`, `models`, `definitions`, `controllers`, `middleware`, `plugins`, `flowstreams` and `stats`; any other name, such as `none`, loads nothing. When `types` is given without `stats`, the statistics and the source maps are turned off.

At the end it starts the service timer, sets `F.isLoaded`, `F.stats.compiled` and `F.stats.compilation`, calls `callback` and emits `ready` and `load`. It does not start the HTTP server.

Example: Background process
```js
require('total5');

LOAD('config,modules,actions', function() {
	ACTION('Jobs/run').callback(console.log);
});
```

Example: With await
```js
require('total5');

(async function() {
	await LOAD('env,config');
	console.log(CONF.name);
})();
```

### IMPORT(url, [callback])

Type: `method`

Downloads a JavaScript file and loads it as a module.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `url` | `String` | yes |  | URL of a `.js` file. |
| `callback` | `Function` | no |  | `function(err, module, response)` |

Returns: `Promise` When `callback` is not set.

The file is downloaded into the temporary folder and loaded with `require()`. Further calls with the same URL in the same process return the loaded module without downloading it again. An answer with the status `400` or more gives the error `The address answered with the status <status>` and nothing is loaded. A file that is not a valid module gives the error of `require()`, for example a `SyntaxError`. The callback receives `(err, module, response)`; without a callback the function returns a Promise with the module.

Example: Promise
```js
var helpers = await IMPORT('https://cdn.example.com/helpers.js');
helpers.hello();
```

Example: Callback
```js
IMPORT('https://cdn.example.com/helpers.js', function(err, helpers) {
	if (err)
		console.error(err);
	else
		helpers.hello();
});
```

### REQUIRE(name)

Type: `method`

Loads a Node.js module or an NPM package.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | The name of the module or package. |

Returns: `Object` The module.

Names with the `node:` prefix and Node.js built-in modules (`fs`, `path`, `crypto`, ...) are loaded directly. Other names are loaded with `require()` and, when that fails, from the folder in `CONF.$nodemodules` (`<application>/node_modules` by default), so packages installed with `NPMINSTALL()` are found. It throws when the module cannot be loaded.

Example: Load
```js
var Fs = REQUIRE('fs');
var mqtt = REQUIRE('mqtt');
```

### MODS

Type: `property`

The loaded modules from the `modules` folder, by their id.

Returns: `Object`

The same object as `F.modules`. Each file in `modules` is registered under its `exports.id`, or under the file name without `.js` when `id` is missing, before its `install()` is called. Use it to call the functions that a module exports.

Example: Call a module
```js
// modules/counter.js
exports.id = 'counter';

var count = 0;

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

// a controller or an action
MODS.counter.increment();
```

### F.isLoaded

Type: `property`

`true` when the application is loaded.

Returns: `Boolean`

Set by `LOAD()` after all files are loaded, just before the `ready` and `load` events.

Example: Check
```js
if (F.isLoaded)
	console.log('Ready');
```

### F.directory

Type: `property`

The root folder of the application.

Returns: `String`

The current working directory of the process when `total5` is loaded. When the application runs from bundles, it points to the `.src` folder. All `PATH.root()` paths start here.

Example: Read
```js
console.log(F.directory);
console.log(PATH.root('config'));
```

### F.isBundle

Type: `property`

`true` when the application runs from bundles.

Returns: `Boolean`

Set when the `bundles` folder contains bundles (or `bundles.debug` exists) and the application was built into `.src`.

Example: Check
```js
if (F.isBundle)
	console.log('Running from', F.directory);
```

### F.dir([directory])

Type: `method`

Sets the root folder and recomputes the folders of the application.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `directory` | `String` | no |  | A new root folder. |

Returns: `undefined`

With `directory` it changes `F.directory`. Then it sets the paths in `F.temporary.directories` for `public`, `tmp`, `logs`, `databases`, `controllers`, `resources`, `plugins`, `modules`, `views`, `definitions`, `schemas`, `models`, `flowstreams`, `bundles`, `actions`, `extensions`, `source`, `services`, `updates`, `templates`, `private` and `scripts`: each one is the value of `CONF.$dir<name>` when it is set, otherwise `<root>/<name>`. `LOAD()` calls it at the start.

Example: Read a folder
```js
F.dir();
console.log(F.temporary.directories.public);
```

### F.restart()

Type: `method`

Asks the watcher to restart the application.

Returns: `undefined`

Sends `total:restart` to the parent process. The debug watcher, and the release watcher started with `--watcher`, print `RES` and start the application again. Without a watcher nothing happens.

Example: After an update
```js
NEWACTION('Settings/save', {
	input: '*name:String',
	action: function($, model) {
		F.Fs.writeFile(PATH.root('config'), 'name : ' + model.name, function() {
			$.success();
			F.restart();
		});
	}
});
```

### F.exit([signal])

Type: `method`

Stops the application.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `signal` | `Number` | no | `15` | The signal for the child processes. |

Returns: `undefined`

Kills the workers and Python pipelines with `signal`, destroys the FlowStream instances, emits `exit`, tells the parent process `total:stop`, stops the service timer and closes the HTTP server. The process ends 300 ms later. The framework calls it on `SIGTERM`, `SIGINT` and when the process exits.

Example: Stop
```js
ON('exit', function() {
	console.log('Bye');
});

F.exit();
```

### F.console()

Type: `method`

Prints the start information.

Returns: `undefined`

Prints the PID, the versions of Node.js and Total.js, the system, the memory, the user, the name, version and author of the application, the date with the time zone, the mode (`debug` or `release`), the number of compiled files with the time, the root, directory and `node_modules` paths and the address of the server. Nothing is printed when `CONF.$imprint` is `false`. The framework calls it after the start.

Example: Print it again
```js
ON('ready', function() {
	F.console();
});
```

### F.remote(url, [directory])

Type: `method`

Connects the folder of the application to the Total.js Code Editor.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `url` | `String` | yes |  | The URL from the editor, `wss://...?id=project`. |
| `directory` | `String` | no | `F.directory` | The folder to edit. |

Returns: `undefined`

Starts the remote editing client in the current process: a WebSocket connection to `url` that lets the editor browse and change the files in `directory`. It reconnects every 10 seconds when the connection is lost. The `edit` start option does the same in the watcher process.

Example: Connect
```js
F.remote('wss://code.example.com/?id=myproject');
```

### F.consumption

Type: `property`

The usage statistics of the process, updated once a minute.

Returns: `Object`

The same object every minute (the first time 5 seconds after the application is loaded); `ON('$stats')` gets it too and, with `CONF.$stats`, it is written into `<script>.json`. Fields: `id`, `pid`, `thread`, `mode` (`debug` or `release`), `version` (`node`, `total`, `build`, `app` from `CONF.version`), `app` (`name` and `url` from the configuration), `date`, `memory` (used heap in MB), `requests`, `pending`, `external`, `errors`, `timeouts`, `online` (WebSocket clients), `download` and `upload` (MB in total), `lasterror`, `lasttimeout`, `usage` (percent), `overload` (hours with high load), `uptime` (minutes since the start) and the per-minute counters `rm`, `fm`, `wm`, `em`, `mm`, `om`, `dm`, `um`, `pm`, `sm`, `cm`, `dbrm` and `dbwm`.

Example: Read
```js
setInterval(function() {
	console.log(F.consumption.memory, 'MB', F.consumption.requests, 'requests');
}, 60000);
```

### F.stats

Type: `property`

Counters of the framework for the whole life of the process.

Returns: `Object`

`F.stats.request` counts requests (`request`, `web`, `xhr`, `file`, `websocket`, `get`, `post`, `put`, `patch`, `delete`, `upload`, `mobile`, `desktop`, `blocked`, `pending`, `size` ...), `F.stats.response` counts responses by type (`json`, `html`, `file`, `redirect`, `stream`, `timeout`, `error404`, `error500` ...), `F.stats.performance` holds the per-minute values, `F.stats.error` the number of errors, and `F.stats.compiled` and `F.stats.compilation` the number of loaded files and the loading time in ms.

Example: Simple report
```js
ROUTE('GET /stats/', function($) {
	var s = F.stats;
	$.json({ requests: s.request.request, errors: s.error, notfound: s.response.error404 });
});
```

### ON('$watcher', function(child) {})

Type: `event`

Emitted in the debug watcher after it starts the application process.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `child` | `ChildProcess` | yes |  | The process of the application. |

It runs in the watcher process, not in the application, after each start or restart. `child` is the `ChildProcess` of the application. Register it in the start script before `F.run()`.

Example: Log restarts
```js
require('total5');

ON('$watcher', function(child) {
	console.log('Application PID:', child.pid);
});

F.run();
```

### ON('watcher', function(child) {})

Type: `event`

Emitted in the release watcher after it starts the application process.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `child` | `ChildProcess` | yes |  | The process of the application. |

Release mode started with `--watcher` only. It runs in the watcher process after each start. `child` is the `ChildProcess` of the application.

Example: Log starts
```js
require('total5');

ON('watcher', function(child) {
	console.log('Started PID:', child.pid);
});

F.run({ watcher: false });
```

### options.ip = String

Type: `property`

The IP address the server listens on.

Returns: `String` Default: `CONF.$ip` (`0.0.0.0`)

Stored into `CONF.$ip`. The default `0.0.0.0` listens on all interfaces.

Example: Local only
```js
F.run({ ip: '127.0.0.1', port: 8000 });
```

### options.port = Number

Type: `property`

The port of the server.

Returns: `Number` Default: `8000`

Stored into `CONF.$port`. Without it the port comes from the `PORT` environment variable or a numeric argument of the process (`node index.js 8000`), and the default is `8000`.

Example: Port from the arguments
```js
F.run({ port: parseInt(process.argv[2]) || 8000 });
```

### options.unixsocket = String

Type: `property`

Listens on a Unix socket instead of a port.

Returns: `String`

An existing socket file is removed first. On Windows the path is placed into the named pipe space. Stored into `CONF.$unixsocket`.

Example: Socket
```js
F.run({ unixsocket: require('node:path').join(require('node:os').tmpdir(), 'app_name') });
```

### options.unixsocket777 = Boolean

Type: `property`

Gives the Unix socket the permissions 777.

Returns: `Boolean` Default: `false`

With `unixsocket`, the socket file gets `chmod 777` when it is created, so another user (for example the web server) can connect to it.

Example: Socket for nginx
```js
F.run({ unixsocket: '/tmp/app.socket', unixsocket777: true });
```

### options.config = Object

Type: `property`

Configuration keys applied before the application is loaded.

Returns: `Object`

Every key is applied with `LOADCONFIG()` before `LOAD()`. The `config` file is read later and can override them. Use it for keys that are needed before the `config` file is read, such as `bundling`.

Example: Name and bundling
```js
F.run({ config: { name: 'My app', bundling: 'shallow' } });
```

### options.load = String

Type: `property`

The parts of the application that are loaded.

Returns: `String` Default: `''`

Passed to `LOAD()`: a comma-separated list such as `'config,controllers'`. Empty loads everything; `'none'` starts only the web server. `options.type` is an alias.

Example: Static file server
```js
F.http({ load: 'none', port: 8000 });
```

### options.watcher = Boolean

Type: `property`

`false` starts release mode.

Returns: `Boolean` Default: `true`

With `F.run()`, `false` runs the application in release mode in the current process; any other value starts the debug watcher. In release mode the `--watcher` argument of the process starts a release watcher that restarts the application when it ends.

Example: Release
```js
F.run({ watcher: false });
```

### options.release = Boolean

Type: `property`

Runs the application with `DEBUG = false` under the debug watcher or the cluster.

Returns: `Boolean` Default: `false`

In debug mode the watcher still restarts the application on changes, but the application runs with `DEBUG = false`. With `cluster` it starts the threads in release mode without the watcher.

Example: Release cluster
```js
F.run({ cluster: 4, release: true });
```

### options.servicemode = Boolean|String

Type: `property`

Loads the application without the HTTP server.

Returns: `Boolean|String`

`true` loads everything, a string loads the listed parts (the names of `LOAD()`), for example `'config,modules,actions'`.

Example: Worker process
```js
F.run({ servicemode: 'config,modules,actions' });
```

### options.watch = Array

Type: `property`

More folders for the debug watcher.

Returns: `Array`

Paths relative to the root of the application. A leading and a trailing slash are removed.

Example: Watch a folder
```js
F.run({ watch: ['adminer', '/libs/'] });
```

### options.livereload = String

Type: `property`

Sends changed files to the Total.js live reload service.

Returns: `String`

The hostname of your application (`http://` and `https://` are removed). The debug watcher connects to `wss://livereload.totaljs.com/?hostname=<hostname>` and sends the name of each changed `.js`, `.ts`, `.py`, `.css`, `.html`, `.htm`, `.jpg`, `.png`, `.gif`, `.ico`, `.svg`, `.webp` or `.resource` file, including files in `public` and `views` (other files in the folders are not watched); changes in `public` and `views` do not restart the application.

Example: Live reload
```js
F.run({ livereload: 'myapp.example.com' });
```

### options.inspector = Number

Type: `property`

Starts the application process with the Node.js inspector.

Returns: `Number` Default: `9229`

The debug watcher adds `--inspect=<port>` to the Node.js arguments of the application. The same happens when the watcher itself was started with `--inspect`, with the port `9229`.

Example: Inspector
```js
F.run({ inspector: 9229 });
```

### options.debugger = Number

Type: `property`

Starts the application process with `--debug=<port>`.

Returns: `Number` Default: `40894`

The debug watcher adds `--debug=<port>` to the Node.js arguments of the application. The same happens when the watcher was started with `--debug`, with the port `40894`.

Example: Debugger
```js
F.run({ debugger: 40894 });
```

### options.cluster = Number|String

Type: `property`

Runs the application in several cluster threads.

Returns: `Number|String`

A number of threads, or `'auto'`: it starts with one thread and adds a thread when the average latency of the threads is above 70 ms, up to `options.limit`. In debug mode the watcher restarts all threads after a change; with `release: true` there is no watcher. Every thread loads the whole application.

Example: Four threads
```js
F.run({ cluster: 4, port: 8000 });
```

Example: Automatic
```js
F.run({ cluster: 'auto', limit: 8, release: true });
```

### options.limit = Number

Type: `property`

The maximum number of threads for `cluster: 'auto'`.

Returns: `Number`

Without it, the automatic cluster adds threads without a limit.

Example: Limit
```js
F.run({ cluster: 'auto', limit: 4 });
```

### options.edit = String

Type: `property`

Connects the application to the Total.js Code Editor.

Returns: `String`

The URL from the editor (`wss://...?id=project`; `http` is changed to `ws`). The client runs in the debug watcher, or in the release watcher started with `--watcher`, and starts the application one second later.

Example: Remote editing
```js
F.run({ edit: 'wss://code.example.com/?id=myproject' });
```

### options.editmcp = String

Type: `property`

Connects the application to an MCP edit proxy, so an AI agent can work on its files.

Returns: `String`

The URL of the WebSocket route of the proxy with the id of the project (`wss://proxy.example.com/$mcp/?id=myproject`; `http` is changed to `ws`). The client runs in the watcher (so not with `watcher: false`), reconnects every 10 seconds and starts the application one second later. When `edit` is set too, `edit` is used.

The proxy is another Total.js application with `$mcp : true` that passes its WebSocket route to `require('total5/edit-mcp').proxy()`. Its MCP endpoint `/$mcp/?id=myproject` lists the tools `App_info`, `App_tree`, `App_read`, `App_write`, `App_delete`, `App_restore`, `App_move`, `App_mkdir`, `App_search`, `App_logs`, `App_shell` and `App_restart` and runs them in the connected application with the id `myproject`; without a connected application the tools answer `App is offline.`. Paths are relative to the application root, with or without the leading `/`. `App_write` saves every written content as a numbered revision in the folder `revisions/` of the application, `App_read` returns the current revision number and `App_restore` the content of a revision, `App_move` moves the revisions with the files and `App_delete` removes them (`/` cannot be deleted). `App_shell` runs any shell command in the application folder, so protect the proxy with `Total.mcp.auth`.

Example: The application
```js
F.run({ editmcp: 'wss://proxy.example.com/$mcp/?id=myproject' });
```

Example: The proxy
```js
// config: $mcp : true
const editmcp = require('total5/edit-mcp');

ROUTE('SOCKET /$mcp/', function($) {
	editmcp.proxy($);
});

Total.mcp.auth = function($) {
	if ($.token === CONF.mcp_token)
		$.success({ id: 'agent', name: 'Agent', sa: true });
	else
		$.invalid();
};

// the AI client connects to https://proxy.example.com/$mcp/?id=myproject
```

### bundling : shallow

Type: `config`

`shallow` reuses the extracted `.src` folder instead of building it again.

Returns: `String`

When it is `shallow` and `.src/bundle.json` exists, the bundles are not extracted and the files are not copied; the application runs from the existing `.src`. Bundles are processed before the `config` file is read, so set the key in `options.config`.

Example: Shallow bundling
```js
F.run({ watcher: false, config: { bundling: 'shallow' } });
```
