
Security News
Attackers Are Hunting High-Impact Node.js Maintainers in a Coordinated Social Engineering Campaign
Multiple high-impact npm maintainers confirm they have been targeted in the same social engineering campaign that compromised Axios.
elastic-worker
Advanced tools
elastic-worker provides a simple and unified abstraction over Web Workers (browser) and Worker Threads (Node.js).
It enables developers to run CPU-intensive or blocking tasks in worker threads without manually handling worker setup, messaging, or lifecycle management.
This package exports:
registerWorker — register functions inside a worker contextElasticWorker — scalable worker pool for parallel executionTransfer - a class to use for passing transferable objectsnpm install elastic-worker
Organize your project with a separated worker file:
src/
worker.ts
main.ts
[!NOTE]
The examples are written in TypeScript to demonstrate type usage, but you can also use JavaScript.
Both JavaScript and TypeScript examples are provided in examples.
worker.ts)import { registerWorker } from "elastic-worker";
const add = (a: number, b: number) => a + b;
const sub = (a: number, b: number) => a - b;
const calc = { add, sub };
export type Calculator = typeof calc;
// Register functions for worker usage
registerWorker(calc);
main.ts)import { ElasticWorker } from "elastic-worker";
import type { Calculator } from "./worker.ts";
const workerUrl = new URL("./worker.ts", import.meta.url);
const elasticWorker = new ElasticWorker<Calculator>(workerUrl);
const add = elasticWorker.func("add");
const subtract = elasticWorker.func("sub");
const addResult = await add(1, 2); // runs in worker
const subResult = await subtract(5, 3); // runs in worker
main.ts → ElasticWorker → worker.ts (your functions)
Registers functions inside a worker context.
[!CAUTION]
Functions and variables defined in the worker file whereregisterWorkeris called cannot be directly imported into the main thread. If you need a function to be used directly by both threads, define it in a separate module and import it into the worker file.
registerWorker(functionsObject);
An ElasticWorker can scale horizontally by spawning multiple workers.
It is ideal for parallel, independent tasks (e.g., CPU-bound batch jobs).
new ElasticWorker(url, options);
url — URL to the worker fileoptions — configuration object (see below)Example (ESM):
import { ElasticWorker } from "elastic-worker";
const workerUrl = new URL("./worker.ts", import.meta.url);
const elasticWorker = new ElasticWorker(workerUrl, {
minWorkers: 2,
maxWorkers: 4,
maxTasks: 1000,
idleTimeout: 1000,
});
Example (CJS):
const { ElasticWorker } = require("elastic-worker");
const { pathToFileURL } = require("url");
const path = require("path");
const workerUrl = pathToFileURL(path.resolve("./worker.js"));
const elasticWorker = new ElasticWorker(workerUrl);
1) — Minimum idle workers to keep alive, prevents cold starts.2) — Maximum worker instances allowed.Infinity) — Maximum tasks allow for waiting while workers are busy.500 ms) — Time in milliseconds before an idle worker is terminated.Queue) — Custom task store constructor used to store pending tasks.TaskStore lets you plug in your own task store implementation. Provide a class that implement the interface TaskStore and pass it in ElasticWorker options.
Example
import { ElasticWorker } from "elastic-worker";
import type { TaskStore, Task } from "elastic-worker";
class PriorityQueue implements TaskStore {
readonly maxSize: number;
private readonly items: Task[] = [];
constructor(maxSize: number = Infinity) {
this.maxSize = maxSize;
}
get count() {
return this.items.length;
}
push(item: Task) {
this.items.push(item);
this.items.sort((a, b) => a.timeout - b.timeout);
}
pull() {
return this.items.shift();
}
all() {
return this.items.values();
}
clear() {
this.items.length = 0;
}
}
const workerUrl = new URL("./worker.ts", import.meta.url);
const elasticWorker = new ElasticWorker(workerUrl, {
TaskStore: PriorityQueue,
});
funcCreates a callable wrapper around a worker function.
const controller = new AbortController();
const add = elasticWorker.func("add", {
timeoutMs: 10000,
signal: controller.signal,
});
Parameters:
funcName — Registered worker function nameoptions:
timeoutMs (default: 5000) — Call timeoutsignal — AbortSignal for cancellationterminateGracefully terminates all workers and clears the task store.
Use this if you’re finished with the worker pool.
await elasticWorker.terminate();
The Transfer class provides a clean way to send Transferable Objects between threads. Instead of passing a separate transfer list as a second parameter (like in postMessage), Transfer wraps both your data and its transferable references in a single object—keeping worker function signatures simple and consistent.
[!NOTE] You don't need to use
Transferunless you are trying to transfer large data to worker thread.
Transferable Object back from the worker, return a Transfer object with Transferable Object inside.value property of the Transfer instance.Transfer object.Transfer instance.const processLargeData = elasticWorker.func("processLargeData");
const largeData = new ArrayBuffer(8);
const t = new Transfer(largeData, [largeData]);
const result = await processLargeData(t);
console.log("result", result.value);
const processLargeData = (t: Transfer) => {
const largeData = t.value;
return new Transfer(largeData, [largeData]);
};
registerWorker({ processLargeData });
The Transfer constructor takes two parameters:
Transferable objects).Transferable objects that should be transferred, similar to the second argument in postMessage.const buffer1 = new ArrayBuffer(8);
const buffer2 = new ArrayBuffer(16);
const transfer = new Transfer(
{ buffer1, buffer2, num: 1, str: "hello world" },
[buffer1, buffer2]
);
value — The data being transferred between the main and worker threads.maxTasks limit reached
Main thread: 596.17 ms
Elastic worker(4 worker): 156.19 ms (~3.82 x faster)
The benchmark results can vary significantly based on the number of worker threads (maxWorker) and the computational intensity of the task.
maxWorker generally provides near-linear performance gains — e.g., maxWorker: 2 ≈ 2× faster, maxWorker: 4 ≈ 4× faster.maxWorker: 8, the speedup might be closer to ~5× depending on how much real computation is involved.See examples/js/benchmark.js try it yourself.
Here are javascript and typescript examples.
MIT
FAQs
Use worker as simple asynchronous function
The npm package elastic-worker receives a total of 21 weekly downloads. As such, elastic-worker popularity was classified as not popular.
We found that elastic-worker demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Security News
Multiple high-impact npm maintainers confirm they have been targeted in the same social engineering campaign that compromised Axios.

Security News
Axios compromise traced to social engineering, showing how attacks on maintainers can bypass controls and expose the broader software supply chain.

Security News
Node.js has paused its bug bounty program after funding ended, removing payouts for vulnerability reports but keeping its security process unchanged.