npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2025 – Pkg Stats / Ryan Hefner

hydra-thread

v1.0.1

Published

create and control threads with worker_threads modules

Readme

||| Hydra Thread

"Cut off one head, two more shall take its place." A resilient, auto-regenerating worker_threads manager for Node.js.

npm version Node.js License

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 workerData to 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 for fail-count mode).

💡 Best Practices

  1. Always handle errors: Even though hydra-thread restarts your worker, you should listen to the 'error' event to log why it crashed.
  2. Graceful Shutdown: If your application is shutting down, remember to call thread.terminate() to prevent configured always restart strategies from keeping the process alive.
  3. Paths: It is recommended to use path.join(__dirname, 'filename.js') for the file path to ensure absolute path correctness.

📝 License

MIT