threads.js

Make web workers & worker threads as simple as a function call.

npm install threads

Getting started Documentation


Transparent API

Write code once, run it everywhere – in web workers and node worker threads.

Call workers transparently, await results. It's never been easier.

// master.js
import { spawn, Thread, Worker } from "threads"

const auth = await spawn(new Worker("./workers/auth"))
const hashed = await auth.hashPassword("Super secret password", "1234")

console.log("Hashed password:", hashed)

await Thread.terminate(auth)
// workers/auth.js
import sha256 from "js-sha256"
import { expose } from "threads/worker"

expose({
  hashPassword(password, salt) {
    return sha256(password + salt)
  }
})

Modern features

Designed for modern day JavaScript and TypeScript code.

  • Async functions & observables

    Built on functional paradigms and with modern APIs in mind, threads.js makes it easy to write clear, declarative code.

  • Statically typed using TypeScript

    Completely written in TypeScript – providing a robust code base and always shipping up-to-date types out of the box.

  • Webpack & other bundlers

    Works great with webpack – just need to add one extra plugin!
    Works with other bundlers, too.


Use cases

Web workers and worker threads turn out to be pretty versatile.

  • Speed-up CPU-bound code

    Outsourcing calculation-intensive code to one or multiple workers can improve performance drastically.

  • Thread pools

    Manage bulk tasks by using a thread pool. The pool will dispatch the tasks to workers in a controlled and predictable way.

  • Smooth UI transitions

    Offload business logic from the main thread, since this is where the rendering happens. Enjoy smooth 60 FPS.

  • Shield sensitive functionality

    Security-relevant code should be shielded from other application code. Use worker to sandbox code and create secure enclaves.


Supported platforms

Serves as an abstraction layer for different worker implementations.

Node.js 12+

Using native worker threads

Node.js 8 to 11

Using tiny-worker

Web browsers

Using web workers

Tested on all major desktop operating systems