---
title: Workers, threads and cluster
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/workers-and-threads/
updated: 2026-11-18T16:57:29.576Z
---

# Workers, threads and cluster

> NEWTHREAD(), NEWFORK(), NEWTHREADPOOL(), F.worker, the cluster options, SHELL(), F.python(), F.pipinstall() and PYPELINE().

Methods, properties, start options and events for worker threads, forked processes, thread pools, the cluster, `SHELL()` and `PYPELINE()`. For an introduction with examples read the guide [Workers, threads and cluster](../../guides/workers-and-threads/).

## API

### NEWTHREAD(name, [data])

Type: `method`

Starts a worker thread from the workers/ folder.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | The file name in `workers/` without `.js`, or `~` and an absolute path |
| `data` | `Object` | no |  | Data copied into the thread as `F.worker.data` |

Returns: `Worker` The Node.js worker thread

Runs `workers/{name}.js` in a new Node.js worker thread. A name that starts with `~` is an absolute path to the script. `data` is copied into the thread and is available there as `F.worker.data`. The thread receives `--worker` in its `process.argv`.

The result is the Node.js `Worker` object: use `postMessage()` to send a message and `on('message')`, `on('error')` and `on('exit')` to listen. The framework adds `kill()` and `exit()`, which call `terminate()`.

Example: Start a thread
```js
var thread = NEWTHREAD('calc', { user: 'Peter' });

thread.on('message', function(msg) {
	console.log(msg.sum);
	thread.kill();
});

thread.postMessage({ a: 1, b: 2 });
```

### NEWTHREAD()

Type: `method`

Inside a worker script: returns the worker object F.worker.

Returns: `Object` F.worker

Called without a name in a script that runs as a worker, `NEWTHREAD()` creates `F.worker` (or returns it when it exists), sets the application directory to the current working directory and starts passing the messages from the parent to `F.worker.message`. Load the framework with `require('total5')` before you call it.

Example: workers/calc.js
```js
require('total5');

var worker = NEWTHREAD();

worker.message = function(msg) {
	worker.send({ sum: msg.a + msg.b });
};
```

### F.worker

Type: `property`

The worker object of a script that runs as a worker.

Returns: `Object`

Created by `NEWTHREAD()` (or `NEWFORK()`) without a name. It holds the data from the parent and the methods to receive and send messages and to end the worker. In the main application it is `undefined`.

Example: Check the data
```js
var worker = NEWTHREAD();
console.log(F.worker === worker); // true
console.log(worker.data);
```

### F.worker.data

Type: `property`

The data passed to NEWTHREAD(name, data).

Returns: `Object`

A copy of the second argument of `NEWTHREAD()` in the main thread. It is an empty object `{}` when no data were passed, in a fork and in the threads of a pool.

Example: Read the data
```js
var worker = NEWTHREAD();
var user = worker.data.user;
```

### F.worker.is

Type: `property`

true when the script runs as a worker.

Returns: `Boolean`

`true` in a thread from `NEWTHREAD()`, in a fork from `NEWFORK()` and in the workers of `NEWTHREADPOOL()`: they all get the argument `--worker` in `process.argv`.

Example: Run as a worker or alone
```js
var worker = NEWTHREAD();
if (!worker.is)
	console.log('Started directly with node, not as a worker');
```

### F.worker.isfork

Type: `property`

true in a forked process, false in a worker thread.

Returns: `Boolean`

`true` when the worker is a process from `NEWFORK()` (messages go through `process.send()`), `false` in a worker thread.

Example: Thread or process
```js
var worker = NEWTHREAD();
console.log(worker.isfork ? 'process ' + process.pid : 'thread');
```

### F.worker.message = function(msg) {}

Type: `delegate`

Receives the messages from the parent.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `msg` | `Object` | yes |  | The message from the parent |

Assign a function. It is called with every message the parent sends with `postMessage()`. The default does nothing.

Example: Answer messages
```js
var worker = NEWTHREAD();

worker.message = function(msg) {
	if (msg.type === 'ping')
		worker.send({ type: 'pong' });
};
```

### F.worker.send(msg)

Type: `method`

Sends a message to the parent.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `msg` | `Object` | yes |  | The message; it is copied, functions are not allowed |

Sends the message to the process or thread that started the worker. `F.worker.postMessage()` is the same method. The parent receives it in `on('message')`.

Example: Send a result
```js
worker.send({ id: msg.id, result: result });
```

### F.worker.exit([code])

Type: `method`

Ends the worker.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `code` | `Number` | no | `0` | The exit code |

Calls `process.exit(code)`. Inside a thread it ends the thread; the parent gets the `exit` event with the code. `F.worker.kill()` and `F.worker.close()` are the same method.

Example: End after the job
```js
worker.message = function(msg) {
	work(msg);
	worker.exit();
};
```

### F.worker.setTimeout(timeout)

Type: `method`

Ends the worker with code 1 after a timeout.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `timeout` | `Number` | yes |  | Milliseconds |

Starts a countdown. When it runs out, the worker ends with exit code `1`. A new call clears the previous countdown and starts a new one, so call it at the start of each job.

Example: Watchdog
```js
worker.message = function(msg) {
	worker.setTimeout(10000);
	job(msg, function(response) {
		worker.send(response);
	});
};
```

### thread.kill()

Type: `method`

Stops a thread started with NEWTHREAD().

Calls `terminate()` of the Node.js `Worker`. `thread.exit()` is the same method.

Example: Stop a thread
```js
var thread = NEWTHREAD('calc');
setTimeout(() => thread.kill(), 5000);
```

### NEWFORK(name)

Type: `method` · Since: `0.0.16`

Runs a script from the workers/ folder in a new Node.js process.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | The file name in `workers/` without `.js`, or `~` and an absolute path |

Returns: `ChildProcess` The forked process

Starts `workers/{name}.js` with `child_process.fork()`. A name that starts with `~` is an absolute path. The result is the Node.js `ChildProcess`; the framework adds `postMessage()` (the same as `send()`) and `terminate()`. Messages are serialized as JSON.

The working directory of the fork is the folder of its script. The framework in the fork sends the string `total:init` to the parent after it starts, so skip string messages in the parent. Called without a name inside the fork, `NEWFORK()` returns `F.worker`, as `NEWTHREAD()` does in a thread; `F.worker.data` is then an empty object.

Example: Main application
```js
var fork = NEWFORK('report');

fork.on('message', function(msg) {
	if (typeof(msg) === 'string')
		return;
	console.log(msg);
	fork.terminate();
});

fork.postMessage({ id: 100 });
```

Example: workers/report.js
```js
require('total5');

var worker = NEWFORK();

worker.message = function(msg) {
	worker.send({ id: msg.id, done: true });
};
```

### fork.terminate()

Type: `method` · Since: `0.0.16`

Kills a process started with NEWFORK().

Sends `SIGKILL` to the process. The process ends at once, without running its exit handlers.

Example: Kill a fork
```js
var fork = NEWFORK('report');
setTimeout(() => fork.terminate(), 60000);
```

### fork.postMessage(msg)

Type: `method` · Since: `0.0.16`

Sends a message to a process started with NEWFORK().

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `msg` | `Object` | yes |  | The message; it is serialized as JSON |

The same method as `fork.send()` of Node.js, so the code for threads and forks can look the same. The fork receives the message in `F.worker.message`.

Example: Send a job
```js
fork.postMessage({ id: 100, type: 'pdf' });
```

### NEWTHREADPOOL(name, count, [isfork])

Type: `method`

Starts a pool of worker threads or forks and lends them to jobs.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | The file name in `workers/` without `.js` |
| `count` | `Number` | yes |  | The number of workers |
| `isfork` | `Boolean` | no | `false` | Start the workers with `NEWFORK()` instead of threads |

Returns: `Object` The pool

Starts `count` workers of `workers/{name}.js` at once and returns a pool: worker threads, or processes from `NEWFORK()` when `isfork` is `true`. Jobs get the workers through `pool.exec()`; a worker goes to the next job only after the current job calls `release()`. Jobs that arrive while all workers are busy wait in `pool.pending`. A worker that exits is replaced by a new one, which is given to the next waiting job. The workers get no data (`F.worker.data` is `{}`). The pool is also stored in `F.workers[name]`.

Example: Pool of four threads
```js
var pool = NEWTHREADPOOL('calc', 4);

pool.exec(function(worker, release) {
	worker.on('message', function(msg) {
		console.log(msg.sum);
		release();
	});
	worker.postMessage({ a: 5, b: 5 });
});
```

Example: Pool of forks
```js
var pool = NEWTHREADPOOL('report', 2, true);
```

### pool.exec([fn])

Type: `method`

Runs a job on the next free worker of the pool.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `fn` | `Function` | no |  | `function(worker, release)` |

Returns: `Promise` Only without `fn`: resolves with the worker

Adds the job to the queue and starts it as soon as a worker is free. The function gets `(worker, release)`; call `release()` when the job is done. Without a function the method returns a promise that resolves with the worker; release it with `worker.release()`.

Before a worker starts a job, the pool removes all its `message` listeners, so each job attaches its own.

Example: With a callback
```js
pool.exec(function(worker, release) {
	worker.on('message', function(msg) {
		release();
	});
	worker.postMessage({ a: 1, b: 2 });
});
```

Example: With a promise
```js
var worker = await pool.exec();
worker.on('message', function(msg) {
	worker.release();
});
worker.postMessage({ a: 1, b: 2 });
```

### worker.release()

Type: `method`

Returns a worker of a pool back to the pool.

Every worker of a pool has this method. It marks the worker as free and gives it to the next waiting job. It is the same function as the `release` argument of `pool.exec(fn)`.

Example: Release
```js
var worker = await pool.exec();
worker.on('message', () => worker.release());
worker.postMessage({});
```

### pool.workers

Type: `property`

The workers of the pool.

Returns: `Array`

An array of the `Worker` objects that the pool started.

Example: Send to all
```js
pool.workers.forEach(w => w.postMessage({ type: 'reload' }));
```

### pool.pending

Type: `property`

The jobs that wait for a free worker.

Returns: `Array`

An array of the functions passed to `pool.exec()` that have not started yet. Its length tells how busy the pool is.

Example: Queue length
```js
console.log('Waiting jobs:', pool.pending.length);
```

### pool.count

Type: `property`

The number of workers of the pool.

Returns: `Number`

The `count` given to `NEWTHREADPOOL()`. The pool keeps this number of workers: a worker that exits is replaced.

Example: Size
```js
var pool = NEWTHREADPOOL('calc', 4);
console.log(pool.count); // 4
```

### F.workers

Type: `property`

The thread pools of the application by name.

Returns: `Object`

`NEWTHREADPOOL(name, count)` stores the pool here under its name.

Example: Get a pool
```js
var pool = F.workers.calc;
```

### options.cluster = 4

Type: `config`

Start option: runs the application in a cluster of processes.

A number of processes, or `'auto'`. Set it in the options of `Total.run()`. The first process becomes the master: it starts the processes one after another, each of them loads the application and listens on the same port. A process that exits is started again after one second. The processes run in release mode with `options.release = true` or `options.watcher = false`; otherwise they run in debug mode and the master restarts them all when a source file changes.

With `'auto'` the master starts one process, pings all processes every 5 seconds and adds one when the average answer takes longer than 70 ms (up to `limit`). When they answer fast again, it removes the last process if it has fewer than two pending requests.

Example: Start script
```js
require('total5');

const options = {};
options.port = 8000;
options.release = true;
options.cluster = 4;

Total.run(options);
```

### options.limit = 10

Type: `config`

Start option: the maximum number of processes of an 'auto' cluster.

Used only with `cluster: 'auto'`. Without it the master can add processes without a limit.

Example: Auto cluster
```js
require('total5');

Total.run({ release: true, port: 8000, cluster: 'auto', limit: 8 });
```

### options.tz = 'utc'

Type: `config`

Start option of a cluster: the time zone of the processes.

In cluster mode the framework sets `process.env.TZ` to this value before it starts the processes. The default is `'utc'`.

Example: Time zone
```js
require('total5');

Total.run({ release: true, cluster: 4, tz: 'Europe/Madrid' });
```

### options.logs = 'isolated'

Type: `config`

Start option of a cluster: always print the cluster header.

The master prints the `CLUSTER` header (PID, versions, thread count, mode) when it runs on its own. When it runs under another Node.js process (with an IPC channel) the header is skipped, unless `logs` is `'isolated'`.

Example: Header
```js
require('total5');

Total.run({ release: true, cluster: 2, logs: 'isolated' });
```

### options.callback = function(forks) {}

Type: `delegate`

Start option of a cluster: called after all processes have started.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `forks` | `Array` | yes |  | The cluster workers |

Runs in the master once every process of the cluster has started. `forks` is the array of the `cluster.Worker` objects.

Example: After start
```js
require('total5');

Total.run({
	release: true,
	cluster: 2,
	callback: function(forks) {
		console.log('Started', forks.length, 'processes');
	}
});
```

### F.isCluster

Type: `property`

true in a process of a cluster.

Returns: `Boolean`

The framework sets it when the master sends the start options to the process. In other cases it is `undefined`.

Example: Check
```js
if (F.isCluster)
	process.send({ type: 'clearcache' });
```

### F.isWorker

Type: `property`

true when the process is a worker of the Node.js cluster.

Returns: `Boolean`

The value of `cluster.isWorker` of Node.js, so it is `true` in the processes of a Total.js cluster. It is `false` when the environment variable `PASSENGER_APP_ENV` is set. Processes with `F.isWorker` send their statistics to the master.

Example: Check
```js
console.log(F.isWorker);
```

### F.clusterid

Type: `property`

The identifier of the process in a cluster.

Returns: `String`

A string such as `'1'` or `'2'`, the same value as `F.id`. Outside a cluster it is an empty string. The framework adds it to the names of temporary files and to the statistics.

Example: Per-process file
```js
var filename = PATH.tmp('export' + F.clusterid + '.csv');
```

### F.id

Type: `property`

The identifier of the process in a cluster.

Returns: `String`

The same value as `F.clusterid`: a string with the number of the process, or an empty string outside a cluster.

Example: Log
```js
console.log('Process', F.id);
```

### ON('$message', function(msg, handle) {})

Type: `event`

Every message the process receives through its IPC channel.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `msg` | `Object` | yes |  | The message |
| `handle` | `Object` | yes |  | The handle sent with the message, if any |

Emitted for each message from the parent process. In a cluster an object that one process sends with `process.send()` is passed by the master to all ready processes, the sender included, and each of them gets it here. Do not use the `TYPE` property and strings that start with `total:` in your messages: the framework uses them.

Example: Sync caches
```js
ON('$message', function(msg) {
	if (msg && msg.type === 'clearcache')
		MAIN.products = null;
});

// in any process
process.send({ type: 'clearcache' });
```

### restart (file)

Type: `command`

A file that restarts all processes of a cluster.

The master of a cluster checks every 5 seconds whether a file named `restart` exists in the application directory. If it does, the master deletes it and restarts the processes one by one, two seconds apart. A second restart within 30 seconds is ignored.

Example: Restart from the shell
```bash
$ touch restart
```

### SHELL(cmd, [callback], [cwd])

Type: `method`

Runs a shell command.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `cmd` | `String` | yes |  | The command |
| `callback` | `Function` | no |  | `function(err, stdout)`; or the working directory as a string |
| `cwd` | `String` | no | `the application root` | The working directory |

Returns: `Promise` Only without a callback: resolves with the standard output

Runs the command with `child_process.exec()` in the system shell. With a callback it calls `callback(err, stdout)`; without one it returns a promise that resolves with the standard output or rejects with the error. A string as the second argument is the working directory. The default directory is the application root. The config key `$shell` sets the shell to use. The output can have up to 100 MB (`maxBuffer`); a larger output ends with an error.

Example: Callback
```js
SHELL('git rev-parse HEAD', function(err, stdout) {
	console.log(stdout.trim());
});
```

Example: Promise and directory
```js
var list = await SHELL('ls -1', PATH.public());
```

### $shell : /bin/bash

Type: `config`

The shell that SHELL() uses.

The path of the shell for `SHELL()`. Not set by default, which uses the default shell of Node.js (`/bin/sh`, or `cmd.exe` on Windows).

Example: config
```text
$shell : /bin/bash
```

### F.python(filename, [callback])

Type: `method`

Runs a Python script and returns its output.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `filename` | `String` | yes |  | The absolute path to the `.py` file. |
| `callback` | `Function` | no |  | `function(err, stdout, stderr)`. |

Returns: `Promise` Only without a callback: resolves with the standard output.

Runs `$python <filename>` with `child_process.exec()` in the folder of the script. With a callback it calls `callback(err, stdout, stderr)`; without one it returns a promise that resolves with the standard output. A script that ends with an exit code other than `0` gives an error (`err.code` is the exit code) and the promise rejects. `$python` is the config key with the Python command (`python3` by default).

Example: Promise
```js
var output = await F.python(PATH.root('scripts/report.py'));
```

Example: Callback
```js
F.python(PATH.root('scripts/report.py'), function(err, stdout, stderr) {
	if (err)
		console.log(stderr);
	else
		console.log(stdout);
});
```

### PYPELINE(name, [options])

Type: `method`

Starts a Python script and exchanges messages with it.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | The file name in `pypelines/` without `.py`, `~` and an absolute path, or inline code |
| `options` | `Object` | no |  | `{ autorestart, type, socket }` |

Returns: `Pypeline` An object with events and the methods below

Runs `python3` with `pypelines/{name}.py` (or an absolute path that starts with `~`) in the folder of the script. A `name` that contains a new line, `;` or a quote is inline code, run with `python3 -c` in the application root.

The framework listens on a Unix socket in `tmp/` and passes its path to the script as `sys.argv[1]`. Each message in both directions is a 4-byte big-endian length followed by the payload. The script's standard output and error go to the console of the application. When the application exits, all Python processes are killed.

The options are `autorestart` (default `true`: start the script again when it ends), `type` (`'json'` by default, `'text'` for strings, or any other value for raw buffers) and `socket` (`false` runs the script without a socket, for scripts that only run).

Example: Start a pipeline
```js
var py = PYPELINE('upper');

py.on('data', function(msg) {
	console.log(msg.text);
});

py.send({ text: 'hello' });
```

Example: Text messages
```js
var py = PYPELINE('tokenizer', { type: 'text' });
```

### F.pipinstall(name, [callback])

Type: `method`

Installs a Python package with pip.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | The package, optionally with a version (`requests==2.32.3`). |
| `callback` | `Function` | no |  | `function(err)`. |

Returns: `Promise` Only without a callback.

Runs `$python -m pip install <name>` in the application directory. With a callback it calls `callback(err)`; without one it returns a promise. When pip fails, the error is the error output of pip (a string), or the error of the process.

Example: Install before use
```js
await F.pipinstall('requests');
var output = await F.python(PATH.root('scripts/download.py'));
```

### pypeline.send(data)

Type: `method`

Sends a message to the Python script.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `data` | `Object|Buffer|String` | yes |  | The message |

Returns: `Pypeline` The pipeline (only when the script is connected)

An object is sent as JSON, a `Buffer` as it is and other values as text, each with a 4-byte length in front. Messages sent before the script connects wait and are sent when it connects.

Example: Send
```js
py.send({ text: 'hello' });
```

### pypeline.close()

Type: `method`

Stops the Python script for good.

Returns: `Pypeline`

Turns `autorestart` off, closes the socket server and kills the Python process.

Example: Stop
```js
py.close();
```

### pypeline.restart()

Type: `method`

Kills the Python process and starts it again.

Kills the current process and starts the script again. `pypeline.run()` is the same method.

Example: Reload
```js
py.restart();
```

### pypeline.on('data', function(msg) {})

Type: `event`

A message from the Python script.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `msg` | `Object|String|Buffer` | yes |  | The message |

Emitted for every complete message. With `type: 'json'` the message is parsed, with `'text'` it is a string, otherwise a `Buffer`.

Example: Read
```js
py.on('data', function(msg) {
	console.log(msg);
});
```

### pypeline.on('open', function() {})

Type: `event`

The Python script connected to the socket.

Emitted each time the script connects, after the waiting messages have been sent.

Example: Connected
```js
py.on('open', function() {
	console.log('Python is ready');
});
```

### pypeline.on('restart', function() {})

Type: `event`

The Python script ended and was started again.

Emitted with `autorestart: true` after the framework has started the script again.

Example: Log restarts
```js
py.on('restart', function() {
	console.log('Python restarted');
});
```

### pypeline.name

Type: `property`

The name of the pipeline.

Returns: `String`

The `name` passed to `PYPELINE()`, or `Inline Python Code` for inline code.

Example: Log
```js
console.log(py.name);
```
