hydra-thread
v1.0.1
Published
create and control threads with worker_threads modules
Maintainers
Readme
Hydra Thread
"Cut off one head, two more shall take its place." A resilient, auto-regenerating
worker_threadsmanager for Node.js.
Hydra Thread is a robust wrapper around Node.js native worker_threads. It eliminates the fragility of raw workers by providing automatic restart strategies, persistent state management, and cross-platform path compatibility.
When a standard worker dies, your application breaks. When a Hydra Thread dies, it regenerates instantly, keeping your service alive.
✨ Key Features
- ∞ Auto-Resurrection: Automatically restarts workers upon failure (exit code
!= 0) or continuously based on your strategy. - 🛡️ Immortal References: The manager instance remains valid even after the underlying worker restarts. No need to re-bind event listeners.
- 🔌 Native API Compatible: Designed to mimic the standard Worker API (
postMessage,on,terminate) for zero learning curve. - 🌍 Cross-Platform: Built-in path normalization ensuring seamless operation on Windows, Linux, and macOS.
- 💉 Data Injection: Full support for
workerDatato preload configuration into your threads.
📦 Installation
npm install hydra-thread🚀 Quick Start
1. The Controller (Main Thread)
const Hydra = require('hydra-thread');
const path = require('path');
// Spawn a resilient thread
const thread = Hydra(path.join(__dirname, 'worker.js'), {
workerData: { mode: 'production' }, // Initial data
restart: 'fail', // Strategy: Restart only on crash
restartDelay: 1000 // Wait 1s before respawning
});
// Listen to events just like a native Worker
thread.on('message', (msg) => {
console.log('Message from Hydra:', msg);
if (msg.status === 'complete') {
thread.terminate(); // Mission accomplished
}
});
thread.on('error', (err) => {
console.error('Thread crashed (Auto-restarting...):', err.message);
});
// Send a command
thread.postMessage({ command: 'start_processing' });2. The Head (Worker Thread - worker.js)
const { parentPort, workerData } = require('node:worker_threads');
console.log('Hydra head attached. Mode:', workerData.mode);
parentPort.on('message', (msg) => {
if (msg.command === 'start_processing') {
// Perform heavy computation...
parentPort.postMessage({ status: 'running', data: [1, 2, 3] });
}
});⚙️ Configuration
Hydra(filePath, options)
| Option | Type | Default | Description |
| :--- | :--- | :--- | :--- |
| restart | 'none' \| 'always' \| 'fail' \| 'fail-count' | 'none' | Resurrection Strategy.• none: No restart.• fail: Restart only on non-zero exit code.• always: Restart on any exit.• fail-count: Restart on failure until limit is reached. |
| restartLimit | number | 0 | Max restart attempts (used with fail-count). |
| restartDelay | number | 0 | Delay in milliseconds before restarting. |
| workerData | any | undefined | Data cloned and passed to the worker on startup. |
| eval | boolean | false | If true, filePath is treated as a script string instead of a file path. |
| resourceLimits| Object | - | Native Node.js resource limits (e.g., maxOldGenerationSizeMb). |
📚 API Reference
The Hydra function returns a Manager instance extending EventEmitter.
thread.postMessage(value, [transferList])
Sends a message to the worker.
Note: Even if the worker is currently restarting, this call is safe.
thread.terminate()
Async. Forcefully kills the worker and stops the resurrection mechanism.
await thread.terminate();
console.log('Hydra destroyed.');thread.unref() / thread.ref()
Allows the Node.js process to exit even if the worker is still running (mirrors native behavior).
Events
'message': Received data from the worker.'error': Emitted when an uncaught exception occurs in the worker.'exit': Emitted when the worker process exits (includes exit code).'online': Emitted when the worker successfully starts (or restarts).'restart_limit_reached': Emitted when the max retry limit is hit (only forfail-countmode).
💡 Best Practices
- Always handle errors: Even though
hydra-threadrestarts your worker, you should listen to the'error'event to log why it crashed. - Graceful Shutdown: If your application is shutting down, remember to call
thread.terminate()to prevent configuredalwaysrestart strategies from keeping the process alive. - Paths: It is recommended to use
path.join(__dirname, 'filename.js')for the file path to ensure absolute path correctness.
📝 License
MIT
