Application structure
Start scripts, directories, bundles, packages and global loaders.
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.
require('total4/debug')(options)| Parameter | Type | Description |
|---|---|---|
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.
var options = {};
// options.port = 8000;
// options.watch = ['adminer'];
require('total4/debug')(options);
command
require('total4/release')(options)
Starts the application in release mode.
require('total4/release')(options)| Parameter | Type | Description |
|---|---|---|
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.
var options = {};
// options.port = 8000;
require('total4/release')(options);
node index.js --watcher
method
HTTP(mode, [options], [middleware])
Starts the HTTP server and loads the application.
HTTP(mode, [options], [middleware])| Parameter | Type | Description |
|---|---|---|
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().
require('total4');
HTTP('release', { port: 8000 });
method
HTTPS(mode, [options], [middleware])
Starts an HTTPS server and loads the application.
HTTPS(mode, [options], [middleware])| Parameter | Type | Description |
|---|---|---|
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.
require('total4');
HTTPS('release', { port: 443, https: { key: 'keys/server.key', cert: 'keys/server.crt' } });
config
options.port
The port of the HTTP server.
options.portReturns 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.
options.port = 8000;
config
options.ip
The IP address the server listens on.
options.ipReturns String
Defaults to CONF.default_ip, then '0.0.0.0'. The values 'null', 'undefined' and 'auto' let Node.js choose.
options.ip = '127.0.0.1';
config
options.config
Configuration values that override the configuration files.
options.configReturns Object
The object is merged into CONF when the server starts.
options.config = { name: 'Shop' };
config
options.watch
More directories for the debug watcher.
options.watchReturns 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.
options.watch = ['adminer', 'lib'];
config
options.livereload
Reloads the browser when views, public files or scripts change.
options.livereloadReturns 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.
options.livereload = true;
config
options.inspector
Starts the application with the Node.js inspector.
options.inspectorReturns Number
The value is the port of --inspect (default 9229). Only for total4/debug; the watcher adds the argument to the forked process.
options.inspector = 9229;
config
options.servicemode
Starts the application without the HTTP server.
options.servicemodeReturns 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.
options.servicemode = 'config,definitions,modules,operations';
require('total4/release')(options);
config
options.watcher
Runs total4/release with a supervisor process.
options.watcherReturns Boolean
With true, the release process forks the application and starts it again when it exits. The --watcher command-line argument does the same.
options.watcher = true;
require('total4/release')(options);
config
options.bundling
Controls whether bundles are extracted on start.
options.bundlingReturns 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.
options.bundling = false;
method
LOAD([types], [directory], [callback])
Installs the application without starting the HTTP server.
LOAD([types], [directory], [callback])| Parameter | Type | Description |
|---|---|---|
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.
require('total4');
LOAD('config,definitions,models', function() {
MODEL('product').refresh();
});
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.
exports.install = function([options])| Parameter | Type | Description |
|---|---|---|
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).
// /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.
MODULE(name)| Parameter | Type | Description |
|---|---|---|
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.
MODULE('mail').send('info@example.com', 'Hello');
property
MODS
All installed modules by name.
MODSReturns Object
The same object as F.modules. MODS.mail equals MODULE('mail'), except that a missing module gives undefined.
for (var name in MODS)
console.log(name);
property
PLUGINS
All installed plugins by name.
PLUGINSReturns 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.
// /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.
MODEL(name)| Parameter | Type | Description |
|---|---|---|
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.
// /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.
INCLUDE(name)| Parameter | Type | Description |
|---|---|---|
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.
var pdf = INCLUDE('pdf');
pdf && pdf.render(data);
method
REQUIRE(path)
Requires a script relative to the application directory.
REQUIRE(path)| Parameter | Type | Description |
|---|---|---|
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.
var tools = REQUIRE('lib/tools.js');
method
IMPORT(url, [callback])
Downloads a script from a URL and requires it.
IMPORT(url, [callback])| Parameter | Type | Description |
|---|---|---|
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.
IMPORT('https://example.com/helpers.js', function(err, helpers) {
if (!err)
helpers.init();
});
property
F.version
The version of the framework as a number.
F.versionReturns Number
It is 4099. F.is4 has the same value. Use it to check a minimal version.
if (F.version < 4096)
console.warn('Update Total.js');
property
F.version_header
The major version as a string.
F.version_headerReturns 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.
F.version_nodeReturns 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.
F.version_node2Returns Number
process.version without v and dots, parsed as an integer: 'v18.17.0' gives 18170.
if (F.version_node2 >= 18000)
console.log('Node.js 18 or newer');
property
F.isBundle
true when the application runs from extracted bundles.
F.isBundleReturns Boolean
The application directory is then /.src/, not the directory of the start script.
property
F.isLoaded
true when all directories are installed.
F.isLoadedReturns Boolean
It is set before load and ready are emitted.
WAIT(() => F.isLoaded, function() {
// the application is ready
});
property
isWORKER
true when the application was started with LOAD().
isWORKERReturns Boolean
It is false otherwise. F.isWorker is similar, but it is true until HTTP() or HTTPS() starts the server.
if (!isWORKER)
SCHEDULE('03:00', '1 day', cleanup);
property
is_server
Always true in the framework.
is_serverReturns Boolean
is_client is always false. They let code that is shared with the browser detect where it runs.
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/{name}.bundleBundles 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.
/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.
/bundles.debugWhen 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.
/.bundleignoreOne 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.
/tests/
/public/img/*.psd
/views/demo.html
config
bundling
Set to shallow to keep the extracted bundles.
bundlingReturns 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.
bundling : shallow
command
total4 bundle [filename]
Creates a bundle from the current directory.
total4 bundle [filename]| Parameter | Type | Description |
|---|---|---|
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.
total4 bundle cms.bundle
total4 extract cms.bundle
method
PATH.package(name, [filename])
Returns the path to a file in an extracted package.
PATH.package(name, [filename])| Parameter | Type | Description |
|---|---|---|
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.
var html = F.Fs.readFileSync(PATH.package('invoices/template.html'), 'utf8');