---
title: FlowStream
project: Total.js V4
version: 0.0.99
section: guides
language: en
license: MIT
url: https://totaljs.es/docs/total-js-v4/0-0-99/guides/flowstream/
updated: 2026-11-16T15:41:20.819Z
---

# FlowStream

> Run graphs of components from .flow files in /flowstreams/, write components and work with messages and FlowStream instances.

A **FlowStream** is a graph of components connected through inputs and outputs. Data flows through it as **messages**. The Flow module is part of Total.js 4: put `.flow` files in `/flowstreams/` and the app loads them when it starts. The Flow designer edits a running FlowStream through a WebSocket. The exact list of methods is in the reference of [FlowStream](../../reference/flowstream/).

## The /flowstreams/ directory

Each `.flow` file is a JSON schema. When the app starts, the files of `/flowstreams/` (and `plugins/{name}/flowstreams/`) are passed to `Flow.load()`. Names that contain `-bk` or `_bk` are skipped, so backups can stay in the same folder. In debug mode, a changed `.flow` file restarts the app.

```json
{
	"id": "orders",
	"name": "Orders",
	"components": {
		"uppercase": "<script total>...</script>",
		"print": "<script total>...</script>"
	},
	"design": {
		"a1": { "component": "uppercase", "config": { "field": "name" }, "connections": { "output": [{ "id": "b1", "index": "input" }] } },
		"b1": { "component": "print", "config": {} }
	},
	"variables": { "currency": "EUR" }
}
```

- `components` maps a component id to the source of the component.
- `design` maps an instance id to the component it uses, its `config` and its `connections`. A connection goes from an output id to `{ id: instance, index: input }`.
- `variables` are values that components read with `instance.replace()` or `$.variables()`.
- `worker: 'worker'` runs the FlowStream in a worker thread and another truthy value (for example `'fork'`) in a child process. The worker restarts itself when it crashes.

You can also call `Flow.load(schema, callback)` from code. A schema with an `id` that is already loaded updates the running FlowStream.

## Components

A component is an HTML file. Its `<script total>` block runs on the server; the other blocks (`<readme>`, `<settings>`, `<style>`, `<script>`, `<body>`) are for the designer.

```html
<script total>

	exports.name = 'Uppercase';
	exports.icon = 'ti ti-font';
	exports.config = { field: 'name' };
	exports.inputs = [{ id: 'input', name: 'Input' }];
	exports.outputs = [{ id: 'output', name: 'Output' }];

	exports.make = function(instance, config) {
		instance.message = function($) {
			var data = $.data;
			if (data && typeof(data[config.field]) === 'string')
				data[config.field] = data[config.field].toUpperCase();
			$.send('output', data);
		};
	};

</script>

<readme>
Converts one field of the incoming object to upper case.
</readme>
```

- `exports.inputs` and `exports.outputs` declare the ports. Connections to an input that the component does not declare are removed.
- `exports.config` is the default configuration, merged with the `config` of each instance.
- `exports.make(instance, config)` runs once for each instance in the design.
- `exports.npm` lists NPM packages that are installed before the component is registered.

Inside `make` you assign handlers to the instance:

| Handler | When it runs |
| --- | --- |
| `instance.message($)` | A message arrived; `instance.message_INPUTID($)` for one input |
| `instance.configure(config)` | The configuration changed |
| `instance.trigger(data)` | `flowstream.trigger()` or the designer button |
| `instance.close(removed)` | The instance stops; clear timers here |
| `instance.init()`, `instance.refresh()` | After the design was created, and after each change |
| `instance.variables(variables)` | The variables changed |

And you call its methods: `instance.send(output, data)`, `instance.status(data, [delay])` and `instance.dashboard(data)` for the designer, `instance.throw(err)` for errors, `instance.replace(str)` for variables and `instance.save()` to store changed configuration.

## Messages

`$` is the message. `$.data` is its data. `$.send(output)` passes it to the next instances and `$.destroy()` ends it. Every message must end in one of these two ways; a message sent from an output with no connection ends by itself.

```js
exports.make = function(instance) {
	instance.message = function($) {
		console.log($.data);
		$.destroy();
	};
};
```

When a message goes to several connections, each one gets its own copy of `$.data`, objects and Buffers alike (set `cloning: false` in the schema to turn it off). `$.repo` is one object shared by all copies, useful to carry values along the chain. `$.on('end', fn)` runs when the last copy ends; `$.timeout()` and `$.totaltimeout()` end slow messages with `$.error = 408`.

A component without inputs starts messages itself:

```js
exports.outputs = [{ id: 'output', name: 'Tick' }];

exports.make = function(instance, config) {
	var timer = setInterval(() => instance.send('output', { ts: new Date() }), config.interval || 5000);
	instance.close = function() {
		clearInterval(timer);
	};
};
```

## Using a FlowStream from the app

`Flow.instances` holds the loaded FlowStreams by `id`. `send()` starts a message in one instance and calls back when the message ends:

```js
exports.install = function() {
	ROUTE('POST /api/orders/', create);
};

function create() {
	var self = this;
	Flow.instances.orders.send('a1', self.body, function(err, response) {
		if (err)
			self.invalid(err);
		else
			self.json(response.data);
	});
}
```

The target can be an instance id, `@componentid` or `#name` (the component name). The target must define `instance.message`. Other methods:

- `exec({ id, data, repo, timeout }, callback)` sends to all matching instances, with a timeout.
- `trigger(id, data)` calls `instance.trigger(data)`.
- `reconfigure(id, config)` and `variables(variables)` change settings at runtime.
- `pause([is])`, `export(callback)`, `components(callback)`, `add(id, html)` and `remove()`.
- `stats` holds the counts of messages, pending messages and errors.

## Saving changes

The framework reads `.flow` files but does not write them. When the designer or your code changes a FlowStream, `Flow` emits `save` with the whole schema about five seconds later. Store it yourself:

```js
Flow.on('save', function(schema) {
	delete schema.unixsocket;
	F.Fs.writeFile(PATH.root('flowstreams/' + schema.id + '.flow'), JSON.stringify(schema, null, '\t'), NOOP);
});
```

A schema with `readonly: true` never emits `save`. `Flow.on('load', fn)` runs when a FlowStream is ready, and `Flow.onerror` receives the errors of all FlowStreams.

## The designer

Connect a WebSocket route to a FlowStream with `Flow.socket(id, websocket, [check])`. Protect it, because the designer can change code:

```js
exports.install = function() {
	ROUTE('+SOCKET /flowstreams/{id}/', designer);
};

function designer(id) {
	var self = this;
	Flow.socket(id, self, function(client, next) {
		client.user.sa && next();
	});
}
```

## A local engine

`FLOWSTREAM(name)` returns the engine without files, workers or the designer. Register components with `add()`, create instances with `use(design)` and send data with `trigger('instanceid__inputid', data)`. Most apps use `/flowstreams/` and `Flow` instead.
