---
title: Plugins and components
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/plugins-and-components/
updated: 2026-11-18T16:57:29.576Z
---

# Plugins and components

> The plugin definition, PLUGINS, COMPONENTATOR(), NEWCOMPONENT() with its Component, Instance and Message objects, NPMINSTALL(), REQUIRE() and IMPORT().

Properties of a plugin `index.js`, the plugin files, `PLUGINS`, `COMPONENTATOR()`, server components compiled with `NEWCOMPONENT()` (the component, its instances and messages) and the loaders `NPMINSTALL()`, `REQUIRE()` and `IMPORT()`. For an introduction with examples read the guide [Plugins and components](../../guides/plugins-and-components/).

## API

### plugins/{id}/index.js

Type: `type`

A folder in plugins/ with an index.js file, loaded at start.

Every folder in `plugins/` with an `index.js` file is a plugin; the folder name is the plugin id. A folder without `index.js` is skipped with all its subfolders, and so are folders whose name contains `-bk` or `_bk`. Total.js requires `index.js`, stores its exports in `PLUGINS[id]`, sets `exports.id` when missing and calls `exports.install()`. A `config` file in the folder is merged into `CONF`. The subfolders `controllers/`, `actions/`, `schemas/`, `models/`, `definitions/`, `extensions/` and `middleware/` are loaded like the folders of the application. An `index.flow` file is loaded as a FlowStream.

Example: A minimal plugin
```js
// plugins/contacts/index.js
exports.name = 'Contacts';
exports.icon = 'ti ti-address-book';
exports.permissions = ['contacts'];

exports.install = function() {
	ROUTE('+API    ?    contacts_list    --> Contacts/list');
};
```

### exports.install = function() {}

Type: `delegate`

Called once when the plugin is loaded.

Register routes, events and other definitions of the plugin here. It runs during the loading of the application, in the same pass as the files of `controllers/`, `definitions/` and the other folders, so use `ON('ready')` when you need everything to be loaded first.

Example: Routes and a ready handler
```js
exports.install = function() {
	ROUTE('+GET /admin/contacts/', function($) {
		$.view('#contacts/views/index');
	});
	ON('ready', function() {
		// all plugins are loaded
	});
};
```

### exports.id

Type: `property`

The id of the plugin.

Returns: `String`

When `index.js` does not define it, Total.js sets it to the name of the plugin folder. `PLUGINS` uses the folder name as the key in both cases.

### exports.name

Type: `property`

A human readable name of the plugin.

Returns: `String`

Total.js writes it, with the id and the permissions, to the source map of the application in debug mode. Your UI can read it from `PLUGINS` to build a menu.

Example: Name
```js
exports.name = 'Orders';
```

### exports.permissions

Type: `property`

The permissions the plugin defines.

Returns: `Array`

An array of strings or of objects with an `id` property (and anything else you need, such as `name`). The ids are written, joined with commas, to the source map in debug mode. Read the array from `PLUGINS` to offer the permissions in a user editor and check them with the `permissions` option of your actions (see [Authorization](../../guides/authorization/)).

Example: Permissions
```js
exports.permissions = [
	{ id: 'orders', name: 'Orders' },
	{ id: 'orders_remove', name: 'Remove orders' }
];
```

### exports.icon, exports.visible, exports.position, ...

Type: `property`

Your own properties of a plugin.

Total.js does not read any other property of `index.js`. Properties such as `icon`, `position` or `visible` are a convention for your administration UI, which reads them from `PLUGINS`.

Example: Menu data
```js
exports.icon = 'ti ti-truck';
exports.position = 5;
exports.visible = function(user) {
	return user.sa || user.permissions.includes('orders');
};
```

### PLUGINS

Type: `property`

All loaded plugins by id.

Returns: `Object` id: exports

An object whose keys are plugin ids and whose values are the exports of their `index.js`. It is filled during the loading of the application.

Example: List plugins
```js
ON('ready', function() {
	for (var id in PLUGINS)
		console.log(id, PLUGINS[id].name);
});
```

### plugins/{id}/config

Type: `config` · Since: `0.0.16`

Configuration file of a plugin.

A `config` file in the folder of a plugin is read before the scripts of the application and the plugins run, after the main `config`. It has the same format as the main file and its keys are merged into `CONF`; a key that is also in the main file is overwritten.

Example: Defaults of a plugin
```text
shop_currency    : EUR
shop_pagesize    : 20
```

### plugins/{id}/index.flow

Type: `type` · Since: `0.0.19`

A FlowStream loaded with the plugin.

An `index.flow` file (a FlowStream export in JSON) in the folder of a plugin is read and started after the files of the application and the `index.js` of the plugin, before the other files of the plugin; the instance is created asynchronously and is stored in `PLUGINS[id].flowstream` once it is ready. The FlowStream gets the plugin id as `id`, the translated plugin `name` (or the id) as `name` and the plugin folder as `directory`. The instance is stored in `PLUGINS[id].flowstream`; errors are logged as `Plugin.<id>.flowstream`. See [FlowStream](../../guides/flowstream/).

### PLUGINS[id].flowstream

Type: `property` · Since: `0.0.19`

The FlowStream instance loaded from index.flow.

Returns: `FlowStream`

Set when the `index.flow` file of the plugin has been loaded.

### PATH.plugins([path])

Type: `method`

Returns a path in the plugins folder.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `path` | `String` | no |  | A relative path such as "shop/data.json" |

Returns: `String` Absolute path

Without an argument it returns the absolute path of `plugins/`; with a path it joins it. With a path, the plugins folder is created when it does not exist.

Example: Read a file of a plugin
```js
var filename = PATH.plugins('shop/data/countries.json');
F.Fs.readFile(filename, 'utf8', function(err, data) {
	// ...
});
```

### controller.view('#{id}/path')

Type: `type`

Renders a view from a plugin folder.

A view name that starts with `#` is relative to `plugins/`: `#shop/views/index` renders `plugins/shop/views/index.html`. The same prefix works in `TEMPLATE('#shop/templates/order.html')`, which adds `.html` when the name does not contain it.

Example: A view of a plugin
```js
exports.install = function() {
	ROUTE('+GET /admin/shop/', function($) {
		$.view('#shop/views/index');
	});
};
```

### COMPONENTATOR(name, components, [removeprev], [attrs])

Type: `method`

Downloads a bundle of UI components from Componentator.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | Name of the bundle; used in the file name and as the key in REPO |
| `components` | `String` | yes |  | Comma separated component names |
| `removeprev` | `Boolean` | no | `true` | Delete older bundles with the same name |
| `attrs` | `String` | no | `''` | Extra URL-encoded fields sent with the download request |

Downloads one minified file with the listed jComponent components from `https://componentator.com/download/` into `public/ui-<name>-<hash>.min.js` (`public/ui-<hash>.min.js` with `removeprev` set to `false`). The hash is computed from `components`, and the file is downloaded only when it does not exist. With `removeprev` (default), older `ui-<name>-*` files are deleted. The URL of the bundle is stored in `REPO[name]`. Errors are logged. When `removeprev` is a string, it is taken as `attrs`.

Example: A UI bundle
```js
// definitions/ui.js
COMPONENTATOR('ui', 'exec,locale,input,box,validate,loading,notify,datagrid', true);
```

Example: In the layout
```html
<script src="@{REPO.ui}"></script>
```

### ON('componentator', function(meta) {})

Type: `event`

Emitted before COMPONENTATOR() builds the file name.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `meta` | `Object` | yes |  | { name, components } |

`meta` contains `name` and `components`. You can change both, for example to add a component to every bundle; the new values are used for the file name, `REPO` and the download.

Example: Add a component everywhere
```js
ON('componentator', function(meta) {
	meta.components += ',errorhandler';
});
```

### NEWCOMPONENT(html, [callback])

Type: `method`

Compiles a server component.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `html` | `String` | yes |  | File name, HTML or URL |
| `callback` | `Function` | no |  | function(err, component) |

Returns: `Promise<Component>` When callback is not set

`html` is the name of a file in `components/` (without `.html`), the HTML content itself (anything containing `<`), or an `https://` URL that is downloaded first. The server code must be in a `<script total>` or `<script node>` block; without it you get the error "Invalid component content". The code runs with `exports` (the component) and `require` (`REQUIRE()`). Packages in `exports.npm` are installed, schemas of inputs and outputs are compiled and `exports.install()` is called. Returns a Promise without a callback.

Example: From the components folder
```js
NEWCOMPONENT('uppercase', function(err, com) {
	if (err) {
		console.error(err);
		return;
	}
	var instance = com.create();
});
```

Example: Inline
```js
var html = '<script total>exports.make = function(instance) { instance.message = msg => msg.send(\'output\', msg.data * 2); };</script>';
var com = await NEWCOMPONENT(html);
```

### components/{name}.html

Type: `type`

The format of a server component.

An HTML file with these parts: `<script total>` or `<script node>` (server code, required), `<settings>`, `<style>`, `<script>`, `<body>`, `<readme>`, `<schema>` and `<template>`. The server code is removed from the result; the other parts are available in `component.ui` (`settings`, `css`, `js`, `html`, `readme`, `schema`, `template`).

Example: A complete file
```html
<script total>

	exports.name = 'Counter';
	exports.config = { step: 1 };
	exports.inputs = [{ id: 'input', name: 'Value' }];
	exports.outputs = [{ id: 'output', name: 'Sum' }];

	exports.make = function(instance, config) {
		var sum = 0;
		instance.message = function(msg) {
			sum += config.step;
			msg.send('output', sum);
		};
	};

</script>

<readme>
Counts incoming messages.
</readme>

<settings>
<div>Step of the counter</div>
</settings>
```

### Component

Type: `class`

A compiled server component.

The object returned by `NEWCOMPONENT()`. Its properties come from `exports` of the server code (`name`, `config`, `inputs`, `outputs`, `npm`, `make`, ...) plus `ui`, `instances`, `variables`, `secrets` and `debugger`.

### exports.make = function(instance, config, status) {}

Type: `delegate`

Sets up a new instance.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `instance` | `Instance` | yes |  | The new instance |
| `config` | `Object` | yes |  | Its configuration |
| `status` | `Object` | yes |  | The second argument of create() |

Called by `component.create()` with the instance as `this` and as the first argument. Assign `instance.message` (and other handlers such as `instance.close`, `instance.configure` or `instance.service`) here.

Example: Handlers
```js
exports.make = function(instance, config) {
	instance.message = function(msg) {
		msg.send('output', msg.data);
	};
	instance.configure = function() {
		// config has changed
	};
};
```

### exports.config

Type: `property`

Default configuration of instances.

Returns: `Object`

Each instance gets a clone of this object, extended with the options passed to `component.create()`.

### exports.inputs / exports.outputs

Type: `property`

Inputs and outputs of the component.

Returns: `Array`

Arrays of `{ id, name, schema }`. A `schema` (a schema string such as `'name:String, age:Number'`) is compiled into a JSON schema. For inputs it is applied in `instance.input()`: the cleaned data replaces `msg.data` and errors are in `msg.error`.

Example: With a schema
```js
exports.inputs = [{ id: 'user', name: 'User', schema: 'name:String, email:Email' }];
exports.outputs = [{ id: 'ok', name: 'Valid' }, { id: 'error', name: 'Invalid' }];

exports.make = function(instance) {
	instance.message = function(msg) {
		if (msg.error)
			msg.send('error', msg.error.toString());
		else
			msg.send('ok', msg.data);
	};
};
```

### exports.npm

Type: `property`

NPM packages the component needs.

Returns: `String[]`

An array of package names (optionally `name@version`). `NEWCOMPONENT()` installs them with `NPMINSTALL()` before `install()` runs; the compilation fails with the npm error when one cannot be installed.

Example: Dependencies
```js
exports.npm = ['mqtt'];

exports.make = function(instance, config) {
	var mqtt = require('mqtt');
	// ...
};
```

### exports.install = function(component) {}

Type: `delegate`

Called once after the component is compiled.

Runs with the component as `this` and as the argument, after NPM packages are installed and schemas are compiled.

### exports.onextend = function(instance) {}

Type: `delegate`

Extends each new instance before make().

Called in `component.create()` after the configuration is set and before `make()`.

### exports.oncreate = function(instance) {}

Type: `delegate`

Called after an instance is created.

Runs asynchronously (in `setImmediate`) after `make()`.

### exports.onremove = function(instance) {}

Type: `delegate`

Called when an instance is removed.

Called by `instance.remove()` after the `close` and `destroy` handlers of the instance.

### component.ui

Type: `property`

The UI parts of the component file.

Returns: `Object`

An object with `readme`, `settings`, `css`, `js`, `html`, `schema` and `template` (only the parts found in the file).

### component.instances

Type: `property`

All instances of the component.

Returns: `Instance[]`

`create()` adds an instance and `instance.remove()` removes it.

### component.debugger

Type: `property`

Prints status, debug, error and output messages to the console.

Returns: `Boolean`

`true` by default. Set it to `false` to keep the console quiet, or replace `component.output`, `component.status`, `component.debug`, `component.throw` or `component.dashboard` with your own functions.

### component.output = function(instance, msg) {}

Type: `delegate`

Receives every message sent to an output.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `instance` | `Instance` | yes |  | The sender |
| `msg` | `Message` | yes |  | msg.output and msg.data |

Called for each `msg.send()` of any instance. The default prints the output and the data when `debugger` is on. Replace it to connect instances or to process results. `component.status(instance, value)`, `component.debug(instance, value)`, `component.throw(instance, err)` and `component.dashboard(instance, value)` receive the calls of the instance methods with the same name.

Example: Collect results
```js
var com = await NEWCOMPONENT('uppercase');
com.output = function(instance, msg) {
	console.log(instance.id, msg.output, msg.data);
};
```

### component.create([options], [status])

Type: `method`

Creates an instance.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `options` | `Object` | no |  | Configuration of the instance |
| `status` | `Object` | no |  | Passed to make() as the third argument |

Returns: `Instance`

The instance gets a random `id`, a clone of `component.config` extended with `options`, and is added to `component.instances`. Then `onextend()`, `make()` and (asynchronously) `oncreate()` are called.

Example: Two instances
```js
var a = com.create({ prefix: 'A: ' });
var b = com.create({ prefix: 'B: ' });
```

### component.service(counter)

Type: `method`

Calls instance.service(counter) on all instances.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `counter` | `Number` | yes |  | Any value passed to the instances |

Total.js does not call it for you. Call it from `ON('service')` when your instances need a periodic tick.

Example: Every minute
```js
ON('service', function(counter) {
	com.service(counter);
});
```

### Instance

Type: `class`

An instance of a server component.

Returned by `component.create()`. Properties: `id`, `config`, `module` (the component) and `cache` (an empty object for your data). Handlers you can assign in `make()`: `message`, `message_<input>`, `configure`, `close`, `destroy` and `service`.

### instance.message = function(msg) {}

Type: `delegate`

Handles data that comes to an input.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `msg` | `Message` | yes |  | The incoming message |

Called by `instance.input()`. `msg.input` is the input id and `msg.data` the data. A handler named `instance.message_<input>` is called too, after `message`. Without `instance.message` the input is ignored.

Example: Per input
```js
exports.make = function(instance) {
	instance.message = NOOP;
	instance.message_reset = function(msg) {
		// only for input "reset"
	};
};
```

### instance.input(input, data, [callback])

Type: `method`

Sends data to an input of the instance.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `input` | `String` | yes |  | Input id |
| `data` | `Object` | yes |  | The data |
| `callback` | `Function` | no |  | function(msg) |

Creates a message, validates the data with the schema of the input (if any) and calls `instance.message(msg)` and `instance.message_<input>(msg)`. The `callback` is called with the message each time it is sent to an output with `msg.send()`.

Example: Call and read the result
```js
instance.input('input', 'hello', function(msg) {
	console.log(msg.output, msg.data);
});
```

### instance.send(output, data)

Type: `method` · Since: `0.0.17`

Sends new data to an output.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `output` | `String` | yes |  | Output id |
| `data` | `Object` | yes |  | The data |

Creates a new message with `data` and sends it to `output`; it ends in `instance.output(msg)` and so in `component.output()`. Use it for data the instance produces on its own (a timer, a socket).

Example: A timer
```js
exports.make = function(instance) {
	var timer = setInterval(() => instance.send('output', new Date()), 5000);
	instance.close = () => clearInterval(timer);
};
```

### instance.status(value) / debug(value) / throw(err) / dashboard(value)

Type: `method`

Reports a state of the instance.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `value` | `Object` | yes |  | Any value |

Each method calls the component method with the same name (`component.status(instance, value)` and so on). By default they print to the console when `component.debugger` is on.

Example: Report
```js
instance.status({ connected: true });
instance.throw(new Error('Connection refused'));
```

### instance.activity(key, name, value)

Type: `method` · Since: `0.0.19`

Reports an activity of the instance.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `key` | `String` | yes |  | Identifier of the activity |
| `name` | `String` | yes |  | Label |
| `value` | `Object` | yes |  | For example a progress |

Calls `component.activity(instance, { key, name, value })`, which prints `ACTIVITY` to the console when `component.debugger` is on. Replace `component.activity` to process it.

### instance.reconfigure(options)

Type: `method`

Changes the configuration of an instance.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `options` | `Object` | yes |  | New values |

Copies the keys of `options` to `instance.config` and calls `instance.configure(config)` when it is defined.

Example: Change a value
```js
instance.reconfigure({ prefix: '>> ' });
```

### instance.remove()

Type: `method`

Removes the instance.

Calls `instance.close(true)` and `instance.destroy()` when defined, then `component.onremove(instance)`, and removes the instance from `component.instances`.

Example: Remove
```js
instance.remove();
```

### instance.replace(str, [data], [encoding])

Type: `method`

Replaces {key} placeholders in a string.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `str` | `String|Object` | yes |  | Template |
| `data` | `Object` | no |  | Values |
| `encoding` | `String|Function` | no |  | Encoding of the values |

Returns: `String|Object`

Each `{key}` (or `{{key}}`) is taken from `component.variables`, then `component.secrets`, then `data` (nested keys with dots work). Without `data` the instance itself is used. `encoding` can be `'url'` (or `'urlencoded'`), `'json'`, `'querify'` or a `function(value, key)`. Dates are formatted. An object as `str` replaces its string values. `msg.replace()` works the same way.

Example: A URL
```js
com.variables.api = 'https://api.example.com';
var url = instance.replace('{api}/users/{id}/', { id: 15 });
```

### Message

Type: `class`

Data that flows through a component instance.

Created by `instance.input()` and `instance.send()`. Properties: `data`, `input`, `output`, `error` (an ErrorBuilder when the input schema failed, `null` when it passed, `undefined` for an input without a schema), `from` and `instance` (the instance), `repo` and `vars` (empty objects for your data).

### msg.send(output, [data])

Type: `method`

Sends the message to an output.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `output` | `String` | yes |  | Output id |
| `data` | `Object` | no |  | New data |

Sets `msg.output` and, when `data` is given, `msg.data`. Then it calls the callback of `instance.input()` and `instance.output(msg)`. Nothing happens after `msg.end()`.

Example: Forward
```js
instance.message = function(msg) {
	msg.send('output', { received: msg.data });
};
```

### msg.end() / msg.destroy()

Type: `method`

Releases the message.

Clears `data`, `vars`, `repo` and the instance, so later `msg.send()` calls do nothing.

### NPMINSTALL(name, [callback])

Type: `method`

Installs an NPM package.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | Package name, optionally with @version |
| `callback` | `Function` | no |  | function(err) |

Returns: `Promise` When callback is not set

Runs `npm install <name>` in `CONF.$nodemodules` (created when missing). When the package folder already contains a `package.json` (with the same version for `name@version`), nothing is installed. When the process runs as user 33 (www-data), `CONF.$npmcache` is used as the npm cache. Without a callback it returns a Promise. See [Configuration](../../guides/configuration/) for both keys.

Example: Install and load
```js
NPMINSTALL('qrcode@1.5.4', function(err) {
	if (err) {
		console.error(err);
		return;
	}
	var QR = REQUIRE('qrcode');
});
```

### REQUIRE(name)

Type: `method`

Loads a Node.js or NPM module.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | Module name |

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 `CONF.$nodemodules`, 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');
```

### IMPORT(url, [callback])

Type: `method`

Downloads and loads a remote JavaScript 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 required. Further calls with the same URL in the same process return the loaded module without downloading. 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 it a Promise resolves with the module.

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