### Install Total.js Framework Locally
Source: https://docs.totaljs.com/total4/40cdd001wp51c
Installs the Total.js framework as a local dependency in your current project directory. This is the recommended approach for most projects.
```Shell
npm install total4
```
--------------------------------
### Shell: Install Total.js and Run Application
Source: https://docs.totaljs.com/total4/40cfc001mn51c
Commands to install the Total.js framework using npm, install project dependencies, and run the application using Node.js. The watcher automatically restarts the app on file changes.
```Shell
$ npm install total4
```
```Shell
$ cd emptyproject-restservice
$ npm install
```
```Shell
$ node index.js
```
--------------------------------
### Run Total.js Help Command
Source: https://docs.totaljs.com/total4/40cdd001wp51c
After a global installation of Total.js, this command displays the available command-line options and usage instructions for the 'total4' tool.
```Shell
total4 --help
```
--------------------------------
### Run Total.js Application
Source: https://docs.totaljs.com/total4/40cdd001wp51c
Starts a Total.js application by executing its main script, typically 'index.js'. This command is used after setting up a project and installing dependencies.
```Shell
node index.js
```
--------------------------------
### Install Total.js Framework Globally
Source: https://docs.totaljs.com/total4/40cdd001wp51c
Installs the Total.js framework globally on your system, making the 'total4' command-line tool available. This allows you to manage Total.js projects and use helper tools from anywhere.
```Shell
npm install -g total4
```
--------------------------------
### JavaScript: Initialize Total.js and Define Routes
Source: https://docs.totaljs.com/total4/40cfc001mn51c
Initializes the Total.js framework and registers a GET route for the root path, returning a JSON response. It also sets up a WebSocket route that sends a message on connection and logs received messages.
```JavaScript
// Initializes Total.js framework 4
require('total4');
// Registers a route
ROUTE('GET /', function({
// this === Controller
this.json({ message: 'Hello world' });
});
// Registers a WebSocket route
ROUTE('SOCKET /', function({
// this === controller
this.on('open', function(client) {
client.send({ message: 'Hello' });
});
this.on('message', function(client, message) {
console.log(message);
});
});
// Launches a web server in "debug" mode
HTTP('debug');
```
--------------------------------
### Total.js API Call Example
Source: https://docs.totaljs.com/total4/5aed2001pj51c
Illustrates how to make API calls using the Total.js framework. This snippet shows a basic example of initiating an API request.
```JavaScript
GET /api/users
POST /api/users
PUT /api/users/{id}
DELETE /api/users/{id}
```
--------------------------------
### Bundle Content Example
Source: https://docs.totaljs.com/total4/4083a001yg51c
Shows a simplified example of the content within a .bundle file, listing the files and directories it contains.
```plaintext
/controllers/default.js
/definitions/helpers.js
/config
```
--------------------------------
### Total.js AppMonitor Installation
Source: https://docs.totaljs.com/total4/6e2c0001li51c
Instructions for installing and registering Total.js applications with the AppMonitor service. Requires downloading the 'monitor.js' module and ensuring the app is accessible via a domain name.
```JavaScript
Download the `monitor.js` module
Register your app in the AppMonitor
```
--------------------------------
### Total.js Theme Initialization
Source: https://docs.totaljs.com/total4/4083e001yi51c
Demonstrates the structure of a theme initialization file (`index.js`) for Total.js. This file is optional and is loaded automatically when the framework starts. It allows for custom setup and configuration for a specific theme.
```javascript
exports.install = function({
// ...
// ...
// space for your code
// ...
// ...
};
```
--------------------------------
### Install Total.js v3
Source: https://docs.totaljs.com/total4/index
Installs the Total.js framework version 3 using npm. This command is used for users who need to work with or maintain older projects using Total.js v3.
```bash
npm install total.js
```
--------------------------------
### Total.js CLI Bundle Command
Source: https://docs.totaljs.com/total4/4083a001yg51c
Provides an example of using the Total.js CLI tool to create a bundle for an application.
```bash
cd yourapp
total4 -bundle myapp
```
--------------------------------
### Install Total.js v4
Source: https://docs.totaljs.com/total4/3dcf5002ti50c
This snippet shows the command to install the Total.js framework version 4, which is available under the 'total4' package name on npm. This is the recommended version for new projects.
```bash
npm install total4
```
--------------------------------
### Install Total.js v4
Source: https://docs.totaljs.com/total4/index
Installs the Total.js framework version 4 using npm. This command is used for new projects or upgrades to the latest version of the Total.js framework, available under the 'total4' package name.
```bash
npm install total4
```
--------------------------------
### Resource File Example
Source: https://docs.totaljs.com/total4/4083b001sd51c
Demonstrates the structure of a resource file, which is a plain-text key-value dictionary used for localization. It shows how keys, values, and comments are formatted.
```plaintext
key1 : value1
// comment
key2 : value2
key3 : with the tag
```
--------------------------------
### Install Total.js v3
Source: https://docs.totaljs.com/total4/3dcf5002ti50c
This snippet shows the command to install the Total.js framework version 3 using npm. It's provided for users who might still be working with or need to maintain older versions.
```bash
npm install total.js
```
--------------------------------
### Total.js Theme Routing Examples
Source: https://docs.totaljs.com/total4/4083e001yi51c
Provides examples of how to configure routes in Total.js to point to theme-specific views. It shows how to route to a view within the current theme using `=THEME_NAME/index` and to a view in the default theme using `=?/products`.
```javascript
ROUTE('GET /', '=THEME_NAME/index');
// Will be routed to "/themes/THEME_NAME/views/index.html"
ROUTE('GET /products/', '=?/products');
// Will be routed to "/themes/DEFAULT_THEME/views/products.html"
```
--------------------------------
### Total.js File Routing
Source: https://docs.totaljs.com/total4/40d57002oi50c
Explains file routing for static files in Total.js, optimized for performance. It covers routing all files or specific file types using the GET method and includes an example for image resizing.
```javascript
ROUTE('FILE /relative/url/*.jpg', action_fn, [flags]);
RESIZE('/pictures/*.jpg', convertor_fn, [flags]);
```
```javascript
// Example
// File: /controllers/example.js
exports.install = function({
ROUTE('FILE /documents/*.*', handle_documents);
ROUTE('FILE /images/*.jpg', handle_images);
};
function handle_documents(req, res) {
// "req" -> read more in "Request.prototype"
// "res" -> read more in "Response.prototype"
// your code
res.file('/path/to/file.pdf');
}
function handle_images(req, res) {
// "req" -> read more in "Request.prototype"
// "res" -> read more in "Response.prototype"
// your code
}
```
```javascript
// Example
// File: /controllers/example.js
exports.install = function({
RESIZE('/gallery/*.jpg', resize);
};
function resize(image) {
image.resize(120, 120);
image.quality(90);
image.minify();
}
```
--------------------------------
### Initialize TextDB Instance
Source: https://docs.totaljs.com/total4/62ba4001tf51c
Demonstrates how to get an instance of the TextDB database, either in NoSQL or Table mode, using the `NOSQL()` or `TABLE()` constructor respectively. This is the primary way to interact with the database.
```javascript
var database = NOSQL('database');
// or var database = TABLE('database');
```
--------------------------------
### Total.js FileStorage Example
Source: https://docs.totaljs.com/total4/5aed2001pj51c
Demonstrates the usage of FileStorage in Total.js for managing file operations. This includes uploading, downloading, and storing files efficiently.
```JavaScript
const storage = new FileStorage('files/');
storage.save('my_file.txt', 'content');
```
--------------------------------
### Total.js Service Script Example
Source: https://docs.totaljs.com/total4/6b8ac001nf51c
This JavaScript code demonstrates how to set up a Total.js application to run as a service. It loads the Total.js framework and executes custom logic within the `LOAD` callback.
```javascript
require('total4');
LOAD('definitions, schemas', function({
// now you can do everything
console.log('Framework is loaded');
});
```
--------------------------------
### Initialize FileStorage Instance
Source: https://docs.totaljs.com/total4/40d59001ti51c
Demonstrates how to get an instance of the FileStorage module. The FILESTORAGE global method is used to create or retrieve a File Storage instance, identified by a given name.
```javascript
var fs = FILESTORAGE('files');
```
--------------------------------
### Bundle Structure Example
Source: https://docs.totaljs.com/total4/4083a001yg51c
Illustrates the internal structure of a Total.js bundle file, showing how directories and gzipped, Base64 encoded files are represented.
```plaintext
/relative/path/to/directory/ : #
/relative/path/to/file/1/ : Gzipped binary file encoded via Base64
/relative/path/to/file/2/ : Gzipped binary file encoded via Base64
```
--------------------------------
### Example Translated Resource File (Slovak)
Source: https://docs.totaljs.com/total4/4083e003yi51c
An example of a translated Total.js resource file, specifically for Slovak ('sk'). This file takes the generated keys and provides the corresponding translated text for each string, enabling the website to display content in multiple languages.
```properties
// Total.js translation file
// Created: 2020-12-04 10:32
// index.html
T1c4854 : Titulok
T1y5ksfx : Ahoj svet!
Tpfol3 : Total.js je webový framework pre Node.js
// IMPORTANT: This line was created manually
message : Priame čítanie
```
--------------------------------
### Total.js Start Script (with Endpoint Prefix)
Source: https://docs.totaljs.com/total4/40840001xi51c
A Total.js start script that configures threads to use a specific prefix for all their endpoints. This allows for cleaner API organization.
```javascript
var options = {};
// Before name of all threads will be added a prefix:
options.threads = '/api/';
options.cluster = 'auto';
options.max = 5;
options.timeout = 5000;
require('total4/debug')(options);
```
--------------------------------
### Total.js: Execute a 'compress' Operation
Source: https://docs.totaljs.com/total4/40d13002eh50c
Demonstrates how to execute a previously defined Total.js operation, specifically the 'compress' operation. This example shows how to call the operation with parameters for the source path and the desired output filename. It also includes a callback function to handle the response, logging any errors or the successful result.
```javascript
// Compress a directory:
OPERATION('compress', { path: '/home/documents/', filename: '/home/documents.zip' }, function(err, response) {
// response.value will be "filename"
console.log(err, response.value);
});
```
--------------------------------
### Total.js Start Script (Basic)
Source: https://docs.totaljs.com/total4/40840001xi51c
A basic start script for a Total.js application configured to use Threads. It enables threading, sets the cluster mode to 'auto' for scaling, defines a maximum number of threads, and sets a proxy timeout.
```javascript
var options = {};
options.threads = true;
// Auto-scale or you can define fixed threads as {Number} for this thread
options.cluster = 'auto';
// Max. allowed threads
options.max = 5;
// A proxy timeout
options.timeout = 5000;
require('total4/debug')(options);
```
--------------------------------
### Example Resource File Content (Generated)
Source: https://docs.totaljs.com/total4/4083e003yi51c
An example of a generated Total.js translation resource file. It lists the original text found in the views and assigns a unique hash key (e.g., `T1c4854`) to each for efficient lookup. This file serves as the base for creating language-specific translations.
```properties
// Total.js translation file
// Created: 2020-12-04 10:32
// index.html
T1c4854 : Title
T1y5ksfx : Hello world!
Tpfol3 : Total.js is web application framework for Node.js
// IMPORTANT: This line was created manually
message : Direct reading
```
--------------------------------
### Total.js Macros: Basic Example
Source: https://docs.totaljs.com/total4/pahk001pr41d
Demonstrates a basic Total.js Macro that increments a value. It shows how to define a macro using NEWMACRO and execute it with an input object.
```javascript
var fn = NEWMACRO(`
VALUE = VALUE + 10
RETURN VALUE
`);
console.log(fn({ value: 10 }));
// Output: 20
```
--------------------------------
### Total.js Threads Routing Example
Source: https://docs.totaljs.com/total4/40840001xi51c
Demonstrates how incoming HTTP requests are routed to specific threads based on their URL path. Each thread is associated with a particular endpoint prefix.
```plaintext
http://127.0.0.1:8000/orders/* ---> is routed to "orders" thread
http://127.0.0.1:8000/products/* ---> is routed to "products" thread
http://127.0.0.1:8000/users/* ---> is routed to "users" thread
```
--------------------------------
### Make API Call with Data
Source: https://docs.totaljs.com/total4/rsps001cs41d
Demonstrates how to initiate an API call to a specific service ('Payments') and operation ('payments_insert') with associated data. The example shows the basic structure for sending parameters.
```JavaScript
var api = API('Payments', 'payments_insert', { amount: 100 });
```
--------------------------------
### Routing Static Files in HTML
Source: https://docs.totaljs.com/total4/4083e004yi50c
Demonstrates how to use the `@` syntax in HTML to route static files like images and scripts. It shows examples of routing to the default theme, a specific theme ('redtheme'), and merging CSS files.
```html
@{import('ui.js')}
@{import('ui.css')}
@{import('default.css + ui.css')}
```
--------------------------------
### Total.js Module Example
Source: https://docs.totaljs.com/total4/r5ad001cs41d
Demonstrates how to create a Total.js module that increments a counter for each incoming request and provides an endpoint to retrieve the counter's value. It also shows how to register and unregister event listeners.
```javascript
var counter = 0;
function increment({
counter++;
}
exports.version = '1.0';
exports.install = function(options) {
// Register event listener for every received request
ON('request', increment);
// Register route that return current "counter" value
ROUTE('/stats/', function({
this.json({ requests: counter });
});
};
// Remove event listener after module is no longer in use
exports.uninstall = function(options) {
OFF('request', increment);
};
```
--------------------------------
### API Call with Callback and Error Handling
Source: https://docs.totaljs.com/total4/rsps001cs41d
Provides a one-line example of making an API call, including a callback function to handle the response and a string for error reporting. This illustrates chaining methods for immediate feedback.
```JavaScript
API('Payments', 'payments_insert', { amount: 100 }).callback(console.log).error('A trouble with API');
```
--------------------------------
### Total.js Unit Testing Basics
Source: https://docs.totaljs.com/total4/40842001ok51c
Demonstrates the fundamental structure for writing unit tests in Total.js. It shows how to include the 'total4' package, use the TESTER function to define test groups and individual tests, and make API calls using RESTBuilder.
```javascript
// Example
// File: {app}/tests/users.js
require('total4');
TESTER(function(group, start) {
group('Users', function(test, cleanup) {
test('Create', function(next) {
RESTBuilder.POST('/users/', { email: 'abc@def.ijk' }).exec(function(err, res) {
err ? next(err) : next();
});
// Shorthand
RESTBuilder.POST('/users/', { email: 'abc@def.ijk' }).exec(next);
});
});
start();
});
```
--------------------------------
### Running Total.js Application (CLI)
Source: https://docs.totaljs.com/total4/4083e003yi51c
This command starts a Total.js application using Node.js. When accessed via a web browser, the application will render content based on the default language or a language specified in the URL query parameters.
```bash
$ node index.js
```
--------------------------------
### Total.js Task Example: Download
Source: https://docs.totaljs.com/total4/40d13003eh51c
Demonstrates how to create a custom task in Total.js for downloading data from multiple URLs. The task initializes an output array, delays execution, and then iteratively downloads content using RESTBuilder, handling errors and passing results to a callback.
```javascript
NEWTASK('Download', function(push) {
push('init', function($) {
// you can extend "$" by your needs:
$.output = [];
$.next('delay');
});
push('delay', function($) {
setTimeout($.next2('download'), 1000);
});
push('download', function($, value) {
// value is alias for "$.value"
var url = value.shift();
if (url == null) {
// End of TaskBuilder and send the value to the callback
$.end($.output);
return;
}
RESTBuilder.GET(url).callback(function(err, response, output) {
if (err) {
// Unhandled error
// Go back
$.value.push(url);
} else
$.output.push(output.response);
$.next('delay');
});
});
});
// Run task
TASK('Download/init', function(err, response) {
console.log(err, response);
}, null, ['https://www.totaljs.com', 'https://www.google.com', 'https://nodejs.org']);
```
--------------------------------
### Run Total.js as a Service
Source: https://docs.totaljs.com/total4/6b8ac001nf51c
This command starts a Total.js application in service mode, suitable for background operations without a web server. The `--release` flag indicates a production-ready deployment.
```bash
node index.js --servicemode --release
```
--------------------------------
### Total.js View Engine: Layout Structure
Source: https://docs.totaljs.com/total4/4083e004yi50c
Provides an example of a Total.js layout file (`layout.html`). It includes standard HTML structure, meta tags, and Total.js View Engine directives like `@{meta}`, `@{import}`, `@{section}`, `@{body}`, and `@{view}` to render dynamic content and include other views.
```HTML