---
title: Application structure
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/application-structure/
updated: 2026-11-16T15:41:20.819Z
---

# Application structure

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

The functions, flags and options that define how a Total.js 4 application is started and loaded. The guide [Application structure and modes](../../guides/application-structure/) 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](../testing/).

## API

### require('total4/debug')(options)

Type: `command`

Starts the application in debug mode with a watcher that restarts it on changes.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `options` | `Object` | no | `{}` | Start options (`port`, `ip`, `watch`, `livereload`, `inspector`, `servicemode`, `https`, `config`...). |

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.

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

### require('total4/release')(options)

Type: `command`

Starts the application in release mode.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `options` | `Object` | no | `{}` | Start options. |

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.

Example: index.js
```js
var options = {};
// options.port = 8000;
require('total4/release')(options);
```

Example: Run with a supervisor
```bash
node index.js --watcher
```

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

Type: `method`

Starts the HTTP server and loads the application.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `mode` | `String` | yes |  | `'debug'` or `'release'`. |
| `options` | `Object` | no | `{}` | Start options (`port`, `ip`, `unixsocket`, `config`, `bundling`...). |
| `middleware` | `Function(listen)` | no |  | 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()`.

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

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

Type: `method`

Starts an HTTPS server and loads the application.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `mode` | `String` | yes |  | `'debug'` or `'release'`. |
| `options` | `Object` | no | `{}` | Start options with `https: { key, cert }`. |
| `middleware` | `Function(listen)` | no |  | Called instead of `listen()`. |

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

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

### options.port

Type: `config`

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`.

Example: Port
```js
options.port = 8000;
```

### options.ip

Type: `config`

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.

Example: Localhost only
```js
options.ip = '127.0.0.1';
```

### options.config

Type: `config`

Configuration values that override the configuration files.

Returns: `Object`

The object is merged into `CONF` when the server starts.

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

### options.watch

Type: `config`

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.

Example: Watch a directory
```js
options.watch = ['adminer', 'lib'];
```

### options.livereload

Type: `config`

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.

Example: Live reload
```js
options.livereload = true;
```

### options.inspector

Type: `config`

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.

Example: Inspector
```js
options.inspector = 9229;
```

### options.servicemode

Type: `config`

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.

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

### options.watcher

Type: `config`

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.

Example: Supervisor
```js
options.watcher = true;
require('total4/release')(options);
```

### options.bundling

Type: `config`

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.

Example: Skip extracting
```js
options.bundling = false;
```

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

Type: `method`

Installs the application without starting the HTTP server.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `types` | `String|String[]` | no | `['nobundles', 'nopackages', 'nocomponents', 'nothemes']` | What to load. |
| `directory` | `String` | no | `the directory of the script` | The application directory. |
| `callback` | `Function` | no |  | 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.

Example: A script
```js
require('total4');

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

Example: Promise
```js
require('total4');

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

main();
```

### exports.install = function([options])

Type: `delegate`

Runs once when the framework installs a file.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `options` | `Object` | no |  | 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)`.

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

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

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

### MODULE(name)

Type: `method`

Returns an installed module.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | 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.

Example: Use a module
```js
MODULE('mail').send('info@example.com', 'Hello');
```

### MODS

Type: `property`

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`.

Example: Iterate
```js
for (var name in MODS)
	console.log(name);
```

### PLUGINS

Type: `property`

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`.

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

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

### MODEL(name)

Type: `method`

Returns an installed model.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | 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.

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

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

### INCLUDE(name)

Type: `method`

Loads a script from `/source/` the first time you ask for it.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | 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.

Example: Lazy loading
```js
var pdf = INCLUDE('pdf');
pdf && pdf.render(data);
```

### REQUIRE(path)

Type: `method`

Requires a script relative to the application directory.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `path` | `String` | yes |  | 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.

Example: A library
```js
var tools = REQUIRE('lib/tools.js');
```

### IMPORT(url, [callback])

Type: `method`

Downloads a script from a URL and requires it.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `url` | `String` | yes |  | The URL of a JavaScript file. |
| `callback` | `Function(err, module, response)` | no |  | 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.

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

### F.version

Type: `property`

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.

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

### F.version_header

Type: `property`

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()`.

### F.version_node

Type: `property`

The version of Node.js.

Returns: `String`

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

### F.version_node2

Type: `property` · 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`.

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

### F.isBundle

Type: `property`

`true` when the application runs from extracted bundles.

Returns: `Boolean`

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

### F.isLoaded

Type: `property`

`true` when all directories are installed.

Returns: `Boolean`

It is set before `load` and `ready` are emitted.

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

### isWORKER

Type: `property`

`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.

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

### is_server

Type: `property`

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.

Example: Shared code
```js
if (typeof(is_server) !== 'undefined' && is_server)
	exports.format = format;
```

### /bundles/{name}.bundle

Type: `type`

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`.

Example: Structure
```text
/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
```

### /bundles.debug

Type: `type`

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.

### /.bundleignore

Type: `type`

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.

Example: Rules
```text
/tests/
/public/img/*.psd
/views/demo.html
```

### bundling

Type: `config`

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.

Example: config
```text
bundling		  : shallow
```

### total4 bundle [filename]

Type: `command`

Creates a bundle from the current directory.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `filename` | `String` | no | `app.bundle` | The name of the bundle file, with the `.bundle` extension. |

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.

Example: Create
```bash
total4 bundle cms.bundle
```

Example: Extract
```bash
total4 extract cms.bundle
```

### PATH.package(name, [filename])

Type: `method`

Returns the path to a file in an extracted package.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | The name of the package. |
| `filename` | `String` | no |  | 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.

Example: Read a template
```js
var html = F.Fs.readFileSync(PATH.package('invoices/template.html'), 'utf8');
```
