---
title: Workers, threads and cluster
project: Total.js V4
version: 0.0.99
section: reference
language: en
license: MIT
url: https://totaljs.es/docs/total-js-v4/0-0-99/reference/workers-and-threads/
updated: 2026-11-16T15:41:05.817Z
---

# Workers, threads and cluster

> NEWTHREAD(), NEWFORK(), NEWTHREADPOOL(), WORKER(), SHELL(), LOAD() and the cluster API.

Every function, property and start option for background workers, threads, shell commands and the cluster. The guide [Workers, threads and cluster](../../guides/workers-and-threads/) shows how they fit together.

## API

### NEWTHREAD(name, [data])

Type: `method`

Runs a script from /workers/ as a worker_threads thread.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | no |  | The file name in `/workers/` without `.js`, `@package` or `~/absolute/path.js`; leave it out inside a worker to get the helper |
| `data` | `Object` | no |  | Data for the thread (`workerData`) |

Returns: `Worker` The thread, or the worker helper when `name` is empty

Starts `/workers/{name}.js` with `new Worker()` of the Node.js `worker_threads` module and returns the `Worker`. `data` reaches the thread as `workerData` (the helper's `worker.data`). The returned object gets `kill()` and `exit()`, which call `terminate()`.

A `name` that starts with `@` points to a package file, one that starts with `~` is an absolute path. Without `name`, the function returns the worker-side helper (see `worker.data`, `worker.message`, `worker.send()`).

Example: Start a thread
```js
var worker = NEWTHREAD('hash', { rounds: 10 });
worker.on('message', function(msg) {
	console.log(msg);
	worker.kill();
});
worker.postMessage('secret');
```

### NEWFORK(name)

Type: `method`

Runs a script from /workers/ as a child process.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | no |  | The file name in `/workers/` without `.js`, `@package` or `~/absolute/path.js`; leave it out inside a worker to get the helper |

Returns: `ChildProcess` The child process, or the worker helper when `name` is empty

Starts `/workers/{name}.js` with `child_process.fork()` in the app directory and returns the `ChildProcess`. The object gets `postMessage()` (alias of `send()`) and `terminate()` (sends `SIGTERM`), so it has the same methods as a thread from `NEWTHREAD()`.

The name rules are the same as in `NEWTHREAD()`. Without `name`, the function returns the worker-side helper.

Example: Start a fork
```js
var fork = NEWFORK('import');
fork.on('message', function(msg) {
	console.log('Imported', msg.count);
	fork.terminate();
});
fork.postMessage({ filename: PATH.databases('import.csv') });
```

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

Type: `method`

Starts a fixed number of workers and lends them to jobs.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | The file name in `/workers/` without `.js` |
| `count` | `Number` | yes |  | How many workers to start |
| `isfork` | `Boolean` | no | `false` | Use child processes instead of threads |

Returns: `Object` The pool with `exec()`, `workers` and `pending`

Starts `count` workers of `/workers/{name}.js` with `NEWTHREAD()`, or with `NEWFORK()` when `isfork` is `true`, and returns a pool. Jobs run with `pool.exec()`. The pool is also stored in `F.workerspool[name]`.

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

Example: A pool of child processes
```js
var pool = NEWTHREADPOOL('pdf', 2, true);
```

### pool.exec([fn])

Type: `method`

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

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

Returns: `Promise` Only when `fn` is not given; resolves with the worker

When a worker is free, the pool removes its `message` listeners and calls `fn(worker, release)`; inside `fn`, `this` is the worker too. Call `release()` when the job is done so the worker can take the next job. Jobs wait in `pool.pending` while all workers are busy.

Without `fn` the method returns a promise that resolves with the free worker. Call `worker.release()` when you are done.

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

Example: With await
```js
var worker = await pool.exec();
worker.on('message', function(msg) {
	worker.release();
	console.log(msg);
});
worker.postMessage({ id: 2 });
```

### pool.workers

Type: `property`

The workers of a pool.

Returns: `Array`

An array of the `Worker` or `ChildProcess` objects that the pool started. `pool.pending` is the array of jobs that wait for a free worker.

### F.workerspool

Type: `property`

The pools created by NEWTHREADPOOL(), by name.

Returns: `Object`

An object where each key is the `name` given to `NEWTHREADPOOL()` and each value is the pool. Use it to get a pool in another file.

Example: Use a pool from another file
```js
F.workerspool.resize.exec(function(worker, release) {
	// ...
	release();
});
```

### worker.data

Type: `property`

The data that the parent passed to NEWTHREAD().

Returns: `Object`

Inside a worker file, `NEWTHREAD()` or `NEWFORK()` without arguments returns the worker helper. `worker.data` is the `data` argument of `NEWTHREAD(name, data)`. In a child process it is an empty object; send data with a message instead.

Example: In /workers/hash.js
```js
require('total4');
var worker = NEWTHREAD();
console.log(worker.data.rounds);
```

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

Type: `delegate`

Receives the messages that the parent sends to the worker.

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

Assign a function to the helper returned by `NEWTHREAD()` or `NEWFORK()` without arguments. It is called for each message from the parent, in a thread and in a child process.

Example: Answer each message
```js
require('total4');
var worker = NEWFORK();
worker.message = function(msg) {
	worker.send({ id: msg.id, length: msg.text.length });
};
```

### worker.send(message)

Type: `method`

Sends a message from the worker to the parent.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `message` | `Object` | yes |  | A serialisable value |

Uses `parentPort.postMessage()` in a thread and `process.send()` in a child process. `worker.postMessage()` is the same method. The parent receives the message in `on('message')` of the object that `NEWTHREAD()` or `NEWFORK()` returned.

Example: Report progress
```js
worker.send({ progress: 50 });
```

### worker.exit([code])

Type: `method`

Ends the worker.

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

Calls `process.exit(code)`. `worker.kill()` and `worker.close()` are the same method.

Example: Finish after the answer
```js
worker.message = function(msg) {
	worker.send(msg);
	worker.exit();
};
```

### worker.setTimeout(timeout)

Type: `method`

Ends the worker after a time limit.

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

Starts a timer that ends the worker with exit code `1` after `timeout` milliseconds. A new call replaces the previous timer, so you can call it again to extend the limit while the worker is busy.

Example: Limit the worker to one minute
```js
var worker = NEWTHREAD();
worker.setTimeout(60000);
```

### WORKER(name, [timeout], [args])

Type: `method`

Forks a script from /workers/ (the older API).

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | The file name in `/workers/`, without `.js` |
| `timeout` | `Number` | no |  | Kills the process after this many milliseconds |
| `args` | `Array` | no |  | Command-line arguments for the script |

Returns: `ChildProcess`

Runs `/workers/{name}.js` with `child_process.fork()` in the app directory and returns the `ChildProcess`. The arguments `args` and `--worker` are passed to the script. The process is stored in `F.workers` until it exits. When `timeout` (more than 10 ms) passes, the process is killed with `SIGKILL`.

`timeout` can be left out: `WORKER(name, args)`. A name that starts with `@` points to a package file; a name that starts with `#` returns a running worker from `F.workers` by its id. `NEWFORK()` is the newer alternative.

Example: Run a worker for at most 10 seconds
```js
var worker = WORKER('stats', 10000);
worker.on('message', function(msg) {
	console.log(msg);
});
worker.send({ year: 2024 });
```

Example: /workers/stats.js
```js
require('total4');
process.on('message', function(msg) {
	process.send({ year: msg.year, count: 0 });
	process.exit(0);
});
```

### WORKER2(name, [args], callback, [timeout])

Type: `method`

Runs a script from /workers/ and returns its standard output.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | The file name in `/workers/`, without `.js` |
| `args` | `Array` | no |  | Command-line arguments; the script reads them from `process.argv` |
| `callback` | `Function` | yes |  | `function(err, buffer)` |
| `timeout` | `Number` | no |  | Kills the process after this many milliseconds |

Returns: `ChildProcess`

Forks `/workers/{name}.js` silently (like `WORKER()`), collects everything it writes to the standard output and calls `callback(err, buffer)` when the process exits or fails. `args` can be an array or one value. The order of `callback` and `timeout` can be swapped.

Example: Read the output of a script
```js
WORKER2('report', ['2024'], function(err, buffer) {
	var report = buffer.toString('utf8').parseJSON();
	console.log(report);
}, 30000);
```

Example: /workers/report.js
```js
var year = process.argv[2];
console.log(JSON.stringify({ year: year, total: 100 }));
```

### F.workers

Type: `property`

The running processes started by WORKER().

Returns: `Object`

An object of the child processes that `WORKER()` and `WORKER2()` started, by their id (`{name}_{number}`). A process is removed when it exits. When the app stops, all of them are killed.

### PATH.workers([filename])

Type: `method`

Returns the path to a file in the /workers/ directory.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `filename` | `String` | no |  | A file name |

Returns: `String`

Joins `directory_workers` (default `/workers/`) with `filename` and returns the full path.

Example: Check a worker file
```js
var exists = require('fs').existsSync(PATH.workers('resize.js'));
```

### isWORKER

Type: `property`

true when the framework runs through LOAD() without the HTTP server.

Returns: `Boolean`

The global is `false` by default. `LOAD()` sets it to `true`, and `HTTP()` sets it back to `false`. Use it in shared code that must not do things that need a web server (for example start schedulers) when it runs in a worker.

Example: Skip a timer in workers
```js
if (!isWORKER)
	setInterval(cleanup, 60000);
```

### LOAD([types], [cwd], [callback])

Type: `method`

Loads parts of the app without starting the HTTP server.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `types` | `String|Array` | no |  | The parts to load or to skip |
| `cwd` | `String` | no |  | The app directory |
| `callback` | `Function` | no |  | Called when the app is loaded |

Returns: `Promise` Only when `callback` is not given

Use it in worker files and scripts. It reads the config and `.env`, loads the parts named in `types` and calls `callback` (or resolves the returned promise) when they are ready. It sets `isWORKER` to `true` and emits `load` and `ready`.

`types` is an array or a string separated by commas or spaces, for example `'config,modules,schemas'`. Names with the `no` prefix (`'nobundles'`) exclude a part and load the rest. The default is `['nobundles', 'nopackages', 'nocomponents', 'nothemes']`. Add `'debug'` to run in debug mode and `'service'` to run the `ON('service')` timer. Parts: `actions`, `builds`, `bundles`, `components`, `controllers`, `definitions`, `extensions`, `flowstreams`, `jsonschemas`, `middleware`, `models`, `modules`, `operations`, `packages`, `plugins`, `preferences`, `schemas`, `sitemap`, `tasks`, `themes`, `versions`.

Example: A worker with schemas
```js
require('total4');
LOAD('config,schemas,modules', function() {
	console.log(isWORKER); // true
});
```

Example: With await
```js
require('total4');
(async function() {
	await LOAD('nobundles,nopackages');
	console.log(CONF.name);
})();
```

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

Type: `method`

Runs a shell command.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `command` | `String` | yes |  | The command line |
| `callback` | `Function` | no |  | `function(err, stdout, stderr)` |
| `cwd` | `String` | no | `the app directory` | The working directory |

Returns: `Promise` Only when `callback` is not given; resolves with stdout

Runs `command` with `child_process.exec()`. The working directory is `cwd` or the app directory; the shell is `default_shell` when it is set. The callback receives `(err, stdout, stderr)`. Without a callback the function returns a promise that resolves with the standard output. You can pass `cwd` as the second argument when you use the promise.

Never put user input into `command` without escaping it.

Example: With a callback
```js
SHELL('df -h', function(err, stdout) {
	console.log(stdout);
});
```

Example: With await and a directory
```js
var commit = await SHELL('git rev-parse HEAD', '/www/app/');
```

### default_shell : <value>

Type: `config`

The shell that SHELL() uses.

Returns: `String`

The path of the shell for `SHELL()` (the `shell` option of `child_process.exec()`). When it is not set, Node.js uses `/bin/sh` on Unix and `cmd.exe` on Windows.

Example: In the config file
```text
default_shell : /bin/bash
```

### options.cluster = 4

Type: `config`

Runs the app as a cluster of several instances.

Returns: `Number|String`

A start-script option of `total4/release` and `total4/debug`. A number starts that many instances of the app; `'auto'` starts one and adds or removes instances by their response time (see `options.cluster_limit`). The master process restarts an instance that exits after one second. In debug mode the master restarts all instances when a file changes.

When `options.threads` is set, the value applies to each thread instead of the main app.

Example: index.js
```js
const options = {};
options.cluster = 4;
require('total4/release')(options);
```

### options.cluster_limit = 10

Type: `config`

The maximum number of instances in the auto cluster.

Returns: `Number`

With `options.cluster = 'auto'`, the master pings the instances every five seconds. It adds an instance when the average response is over 70 ms, until the count reaches `cluster_limit`. Without it there is no limit. When an instance answers fast, the master removes the last instance (at most every 25 seconds) if it has fewer than two pending requests.

Example: index.js
```js
const options = {};
options.cluster = 'auto';
options.cluster_limit = 8;
require('total4/release')(options);
```

### options.tz = 'utc'

Type: `config`

The time zone of a cluster.

Returns: `String`

In cluster mode the master sets `process.env.TZ` for all instances to this value. When you do not set it, the cluster runs in `'utc'`, whatever the time zone of the server is.

Example: index.js
```js
const options = {};
options.cluster = 2;
options.tz = 'Europe/Bratislava';
require('total4/release')(options);
```

### options.threads = '/api/'

Type: `config`

Runs every subdirectory of /threads/ as a separate app.

Returns: `String|Boolean`

For each directory in `/threads/` the main app writes a start script `{script}_{name}.js` into the root and forks it. Requests under `{threads}/{name}/` are forwarded to that thread over a Unix socket, without the prefix. `true` means no prefix (`/{name}/`).

Each thread loads the `.js` files of its directory with `exports.install`, its own config and `.env` files, `views/` and `public/`. It skips the root `/controllers/` and `/middleware/`.

Example: index.js
```js
const options = {};
options.threads = '/api/';
require('total4/release')(options);
```

Example: /threads/users/index.js
```js
exports.install = function() {
	// Serves GET /api/users/
	ROUTE('GET /', function() {
		this.json({ thread: THREAD });
	});
};
```

### options.thread = 'name'

Type: `config`

The thread name of the process.

Returns: `String`

Sets the global `THREAD` and loads the app as the thread `/threads/{name}/`. The scripts that `options.threads` writes set it for you. In cluster mode, the restart file is `restart_{name}`.

### options.logs = 'isolated'

Type: `config`

Writes the output of each thread into its own log file.

Returns: `String`

With `'isolated'`, the output of a thread goes to `/threads/{name}/logs/debug.log` instead of the console of the main app. The file is cleared when the thread starts (in debug mode only on the first start).

### THREAD

Type: `property`

The name of the current thread.

Returns: `String`

An empty string in a normal app. Inside a thread of `/threads/{name}/` it is the name of the thread. The framework adds it to the console banner and to audit logs.

Example: Use the thread name
```js
var key = THREAD ? ('cache_' + THREAD) : 'cache';
```

### F.threads

Type: `property`

The child processes of the threads, by name.

Returns: `Object`

In the main app with `options.threads`, an object where each key is a thread name and each value is its `ChildProcess`. Otherwise `undefined`.

### F.isCluster

Type: `property`

true in an instance of a cluster.

Returns: `Boolean`

`true` when the process is an instance started by the cluster master.

Example: Run a job in one instance only
```js
if (!F.isCluster || F.id === '0')
	SCHEDULE('03:00', '1 day', cleanup);
```

### F.id

Type: `property`

The id of the instance in a cluster.

Returns: `String`

The index of the instance as a string (`'0'`, `'1'`, ...), or `null` outside a cluster. Temporary files of an instance get the prefix `cluster_{id}_`.

### F.cluster.emit(name, [a], [b], [c], [d], [e])

Type: `method`

Raises an event in every instance of the cluster.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | The event name |
| `a` | `Object` | no |  | Up to five arguments |

Returns: `Framework`

Sends the event through the master to all instances, the sender included. Each instance calls its `ON(name)` listeners with up to five arguments. The arguments travel as IPC messages, so they must be serialisable. Outside a cluster it does nothing.

Example: Clear a cache everywhere
```js
ON('settings_changed', function() {
	CACHE('settings', null);
});

F.cluster.emit('settings_changed');
```

### F.cluster.master(name, [a], [b], [c], [d], [e])

Type: `method`

Sends an event from an instance to the master process.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | The event name |
| `a` | `Object` | no |  | Up to five arguments |

Returns: `Framework`

The master calls the listeners registered with `F.cluster.on(name)`. Outside a cluster it does nothing.

Example: Report to the master
```js
F.cluster.master('visit', F.id);
```

### F.cluster.on(name, callback)

Type: `method`

Listens in the master process to events from F.cluster.master().

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | The event name |
| `callback` | `Function` | yes |  | `function(a, b, c, d, e)` |

Returns: `Framework`

Register it in the start script: the master runs that script, and so does every instance. The callback receives the arguments of `F.cluster.master()`. Register only one listener per name.

Example: index.js
```js
const options = {};
options.cluster = 4;
require('total4/release')(options);

var visits = 0;
F.cluster.on('visit', function(id) {
	visits++;
});
```

### F.cluster.restart([index])

Type: `method`

Restarts instances of the cluster from the master process.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `index` | `Number` | no |  | The index of the instance |

Restarts the instance with `index`, or all instances two seconds apart when `index` is not given. It works only in the master process. From outside, create the `restart` file instead.

Example: Restart all instances from the start script
```js
// index.js
const options = {};
options.cluster = 4;
require('total4/release')(options);

// The start script also runs in every instance, so check the master
if (require('cluster').isMaster)
	setInterval(() => F.cluster.restart(), 24 * 60 * 60 * 1000);
```

### F.cluster.http(count, mode, [options], [callback])

Type: `method`

Starts a cluster with an HTTP server.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `count` | `Number|String` | yes |  | Number of instances or `'auto'` |
| `mode` | `String` | yes |  | `'debug'` or `'release'` |
| `options` | `Object` | no |  | Start options |
| `callback` | `Function` | no |  | `function(forks)` |

This is what `options.cluster` calls in the start script. `count` is a number, `'auto'` or `null` (one instance per CPU core). `mode` is `'debug'` or `'release'`. `options` are the start options that the instances receive. In the master, `callback` is called with the array of instances when all of them have started. `F.cluster.https()` takes the same arguments and starts HTTPS servers.

Example: Start a cluster directly
```js
require('total4').cluster.http(4, 'release', { port: 8000 });
```

### restart

Type: `command`

A file that restarts all instances of a running cluster.

The master checks every five seconds for a file named `restart` in the app directory (`restart_{thread}` when `options.thread` is set). When it finds it, it deletes the file and restarts all instances two seconds apart, at most once in 30 seconds. Use it after a deploy to load new code without stopping the app.

The master also writes its state (PID, versions, instance count, memory and statistics of every instance) into the start script name plus `.json`, for example `index.js.json`, about every 50 seconds.

Example: Restart after a deploy
```bash
touch /www/app/restart
```

### allow_cache_cluster : false

Type: `config`

Synchronizes the framework cache between cluster instances.

Returns: `Boolean`

When `true`, every `CACHE()` / `F.cache.set()`, `remove()`, `removeAll()` and `clear()` in an instance is repeated in the other instances. Sessions are synchronized in a cluster without this option.

Example: In the config file
```text
allow_cache_cluster : true
```
