A Node.js module providing tools to create high-performance, multithreaded applications.
Enhances communication between the main thread and workers using events and promises, utilizes shared memory for real-time updates, and much more.
Install using the following command
npm install multithreaded-node- No dependencies
- Event-based communication between the main thread and the worker
- Asynchronous request between the main thread and the worker
- Shared memory between the main thread and the worker
- Progress updates for heavy tasks
- Worker state management
Below is a minimal structure to get you started with a main thread and a worker.
Set up a listener on the worker thread and emit events from the main thread.
import {startWorker} from "multithreaded-node"
const worker = await startWorker("./worker.ts")
// you can emit events
worker.emit("print", "Hello from the main thread!")import {initializeWorker} from "multithreaded-node"
const thread = initializeWorker()
// listen for events
thread.on('print', (msg) => {
console.log(msg);
});Send a request to the worker and receive a response using promises.
import {startWorker} from "multithreaded-node"
const worker = await startWorker("./worker.ts")
// request something async
worker.request("add", [1, 2]).then((result) => {
console.log(result)
}).catch((err) => {
console.error(err)
})import {initializeWorker} from "multithreaded-node"
const thread = initializeWorker()
// respond to requests
thread.respondTo('add', (array) => {
return array.reduce((a, b) => a + b, 0);
});Get the current CPU and memory usage of the worker.
import {startWorker} from "multithreaded-node"
const worker = await startWorker("./worker.ts")
console.log(worker.cpuUsage, "%")
console.log(worker.memorySnapshot)import {initializeWorker} from "multithreaded-node"
const thread = initializeWorker()
thread.trackMemory = true
thread.trackCpuUsage = trueHere’s a list of the examples included in this repository:
| Example | Description |
|---|---|
| 🔄 Main ↔ Worker Event Communication | Emit and capture events between the main thread and the worker |
| 🔄 Main ↔ Worker Request/Response Communication | Send asynchronous request to the worker and receive a response using promises |
| 🧪 Extend The Shared Memory | An example on how to use the SharedMemory and how to extend it |
| 🧠 Heavy Task Handling with Worker | Handle heavy tasks with a busy state and progress updates |
You can run the test suite with:
npm testThis project is licensed under the MIT License.
Pull requests and improvements are welcome! If you have additional worker-thread examples, feel free to submit a PR and expand the collection.
- No external libraries are required — only Node.js built-in worker_threads is required.
- Great for building advanced worker-based systems.
- Works seamlessly with modern async/await syntax