Spanish Total.js
English
Documentation For AI agents
Contents

Installation and first app

Install the total5 package, write the start script, add a first route and action, and run the app in debug and release mode.

.md GitHub
On this page

This guide installs the total5 package, writes the start script, adds a first route and a first action, and runs the application in debug and in release mode.

Requirements

Total.js 5 runs on Node.js. Install the current LTS version, which also installs npm. Then open a terminal and check that both commands answer with a version number:

$ node --version
$ npm --version

Install the package

Create a directory for the application and install the package from npm:

$ mkdir myapp
$ cd myapp
$ npm init -y
$ npm install total5@beta

The package has no dependencies of its own, so this installs only the framework. It also installs the total5 and flow5 command-line tools (see Command line).

The start script

Create index.js in the application root. This is the official start script of Total.js 5:

require('total5');

const options = {};

// options.ip = '127.0.0.1';
// options.port = parseInt(process.argv[2]);
// options.unixsocket = PATH.join(F.tmpdir, 'app_name.socket');
// options.unixsocket777 = true;
// options.config = { name: 'Total.js' };
// options.inspector = 9229;
// options.watch = ['private'];
// options.livereload = 'https://yourhostname';
// options.watcher = false; // disables watcher
// options.edit = 'wss://www.yourcodeinstance.com/?id=projectname'

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

// Service mode:
options.servicemode = process.argv.includes('--service') || process.argv.includes('--servicemode');
// options.servicemode = 'definitions,modules,config';

// Cluster:
// options.tz = 'utc';
// options.cluster = 'auto';
// options.limit = 10;

Total.run(options);

Start it with node index.js in debug mode, with node index.js --release in release mode, or with node index.js --service to load the application without the HTTP server.

Total.run() (the same function as F.run()) starts the debug watcher: the application runs in a child process that restarts when a file changes. options.release only switches DEBUG to false, so with --release the watcher still restarts the application on changes. With options.watcher = false the application runs in release mode in the current process, without the watcher.

The commented lines are the other start options:

OptionDescription
ipIP address to listen on. Default 0.0.0.0 (CONF.$ip).
portPort number. When it is not set, the port comes from the $port configuration key. When that is auto (the default), the port comes from the PORT environment variable, then from the first command-line argument of 3 to 5 digits, and falls back to 8000.
unixsocketListen on a Unix socket instead of an IP and port.
unixsocket777Gives the Unix socket the permissions 777.
configAn object with configuration keys applied before the app loads, for example { name: 'My app' }.
inspectorWith the watcher: starts the app with the Node.js inspector on this port (--inspect=9229).
watchWith the watcher: an array of extra directories the watcher observes.
livereloadWith the watcher: true starts a live reload WebSocket server on port 35729 and also watches public and views, a number sets the port, and a hostname sends the changed files to the Total.js live reload service.
watcherfalse runs the application in release mode in the current process, without the watcher.
editConnects the application to the Total.js Code Editor.
releasetrue runs the application with DEBUG = false.
servicemodetrue loads the application without the HTTP server. A comma-separated string (for example 'config,modules,definitions') loads only those parts.
clusterA number of processes, or 'auto' (see Workers and threads).
limitWith cluster: 'auto': the maximum number of processes.
tzWith cluster: the time zone of the processes (process.env.TZ), 'utc' by default.

Every option is described in the reference.

The framework switches the working directory to the directory of the start script. With the watcher the application runs in a child process, so the application root is the directory that contains index.js even when you start it from another place (node /www/myapp/index.js). With options.watcher = false the application root is the directory you start the script from, so start it from the application directory.

Folder structure

The framework loads these files and directories from the application root when it starts. All of them are optional: create only the ones you use.

myapp/
├── index.js          start script
├── config            configuration (key : value per line)
├── .env              environment variables
├── version           application version (first line)
├── controllers/      routes: *.js files with exports.install
├── actions/          NEWACTION() definitions
├── schemas/          NEWSCHEMA() definitions
├── models/           business logic
├── definitions/      startup code: delegates, helpers, globals
├── modules/          modules with exports.install
├── extensions/       extensions of the framework
├── middleware/       NEWMIDDLEWARE() definitions
├── plugins/          plugins: plugins/<name>/index.js
├── jsonschemas/      JSON schemas (*.json or *.txt)
├── resources/        localization (*.resource)
├── views/            HTML views
├── public/           static files (CSS, JS, images)
├── flowstreams/      FlowStream schemas
├── databases/        NoSQL databases and file storages
├── logs/             log files
└── tmp/              temporary files

Every .js file in controllers, actions, schemas, models, definitions, modules, extensions and middleware is required, and when it exports an install() function the framework calls it. Subdirectories are read too. A file or directory whose name contains -bk or _bk is skipped. The full description of each directory is in Application structure.

First route

Create controllers/default.js:

exports.install = function() {
    ROUTE('GET /', index);
    ROUTE('GET /api/hello/ --> hello');
    ROUTE('POST /api/greet/ --> greet');
};

function index($) {
    $.plain('Hello world');
}

ROUTE('GET /', index) sends a plain text response from a function. The other two routes have no function: the --> operator runs the named action and sends its result as JSON. Routing is explained in Routing and the $ object in Controller.

First action

Create actions/hello.js:

NEWACTION('hello', {
    name: 'Say hello',
    action: function($) {
        $.success('Hello from an action');
    }
});

NEWACTION('greet', {
    input: '*name:String',
    action: function($, model) {
        $.callback({ message: 'Hello ' + model.name });
    }
});

The hello action answers with $.success(), which sends {"success":true,"value":"Hello from an action"}. The greet action declares an inline input schema: *name:String means a required string field. The framework validates the request body before the action runs, and model is the validated data. A request without name gets an error response:

$ curl -X POST -H 'Content-Type: application/json' -d '{"name":"Peter"}' http://127.0.0.1:8000/api/greet/
{"message":"Hello Peter"}

$ curl -X POST -H 'Content-Type: application/json' -d '{}' http://127.0.0.1:8000/api/greet/
[{"name":"name","error":"The field \"name\" is invalid","path":"name"}]

Actions and inline schemas are covered in Actions and JSON schemas.

Configuration

Create a config file with one key : value pair per line:

name          : My first app

The value is available as CONF.name and is printed when the app starts. See Configuration.

Run in debug mode

$ node index.js

The debug module starts a watcher process (Total.js watcher PID: ...), which starts the application in a child process and prints the start information:

====================================================
PID           : 75692
...
Name          : My first app
Version       : 1.0.0
Mode          : debug
Compiled      : 2 files (4ms)
====================================================

http://0.0.0.0:8000/

Open http://127.0.0.1:8000/ in the browser: the page shows Hello world. Press Ctrl+C in the terminal to stop the application.

In debug mode:

  • DEBUG is true.
  • The watcher checks the application directories (controllers, actions, schemas, models, definitions, modules, plugins and the others) and the config and version files in the root. When a file changes, it prints a line such as --- UPD --- [ ... ] --------> /actions/hello.js and restarts the application.
  • The watcher writes an index.pid file with its process ID. Deleting the file stops the watcher and the application.
  • The framework writes index.js.map, a JSON list of the registered routes and actions.

Pass a port as an argument when the start script does not set one:

$ node index.js 8001

Run in release mode

$ node index.js --release

With the start script above, --release switches DEBUG to false, but the watcher keeps running and restarts the application when a file changes.

For production, uncomment the line options.watcher = false in the start script and start the application with node index.js. The application then runs in release mode in the current process, without the watcher, and changes to source files have no effect until you start it again.

Next steps

Made in Europe