• Stars
    star
    2,942
  • Rank 15,244 (Top 0.4 %)
  • Language
    TypeScript
  • License
    MIT License
  • Created about 9 years ago
  • Updated 11 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

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

threads.js

Build status npm (tag) Chat room


Offload CPU-intensive tasks to worker threads in node.js, web browsers and electron using one uniform API.

Uses web workers in the browser, worker_threads in node 12+ and tiny-worker in node 8 to 11.

Features

  • First-class support for async functions & observables
  • Write code once, run it on all platforms
  • Manage bulk task executions with thread pools
  • Use require() and import/export in workers
  • Works great with webpack

Version 0.x

You can find the old version 0.12 of threads.js on the v0 branch. All the content on this page refers to version 1.0 which is a rewrite of the library with a whole new API.

Installation

npm install threads tiny-worker

You only need to install the tiny-worker package to support node.js < 12. It's an optional dependency and used as a fallback if worker_threads are not available.

Platform support

Run on node.js

Running code using threads.js in node works out of the box.

Note that we wrap the native Worker, so new Worker("./foo/bar") will resolve the path relative to the module that calls it, not relative to the current working directory.

That aligns it with the behavior when bundling the code with webpack or parcel.

Webpack build setup

Webpack config

Use with the threads-plugin. It will transparently detect all new Worker("./unbundled-path") expressions, bundles the worker code and replaces the new Worker(...) path with the worker bundle path, so you don't need to explicitly use the worker-loader or define extra entry points.

  npm install -D threads-plugin

Then add it to your webpack.config.js:

+ const ThreadsPlugin = require('threads-plugin');

  module.exports = {
    // ...
    plugins: [
+     new ThreadsPlugin()
    ]
    // ...
  }

Node.js bundles

If you are using webpack to create a bundle that will be run in node (webpack config target: "node"), you also need to specify that the tiny-worker package used for node < 12 should not be bundled:

  module.exports = {
    // ...
+   externals: {
+     "tiny-worker": "tiny-worker"
+   }
    // ...
}

Make sure that tiny-worker is listed in your package.json dependencies in that case.

When using TypeScript

Note: You'll need to be using Typescript version 4+, as the types generated by threads.js are not supported in Typescript 3.

Make sure the TypeScript compiler keeps the import / export statements intact, so webpack resolves them. Otherwise the threads-plugin won't be able to do its job.

  module.exports = {
    // ...
    module: {
      rules: [
        {
          test: /\.ts$/,
          loader: "ts-loader",
+         options: {
+           compilerOptions: {
+             module: "esnext"
+           }
+         }
        }
      ]
    },
    // ...
  }
Parcel bundler setup

You need to import threads/register once at the beginning of your application code (in the master code, not in the workers):

  import { spawn } from "threads"
+ import "threads/register"

  // ...

  const work = await spawn(new Worker("./worker"))

This registers the library's Worker implementation for your platform as the global Worker. This is necessary, since you cannot import { Worker } from "threads" or Parcel won't recognize new Worker() as a web worker anymore.

Be aware that this might affect any code that tries to instantiate a normal web worker Worker and now instead instantiates a threads.js Worker. The threads.js Worker is just a web worker with some sugar on top, but that sugar might have unexpected side effects on third-party libraries.

Everything else should work out of the box.

Getting Started

Basics

// 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)
  }
})

spawn()

The hashPassword() function of the auth object in the master code proxies the call to the hashPassword() function in the worker:

If the worker's function returns a promise or an observable then you can just use the return value as such in the master code. If the function returns a primitive value, expect the master function to return a promise resolving to that value.

expose()

Use expose() to make a function or an object containing methods callable from the master thread.

In case of exposing an object, spawn() will asynchronously return an object exposing all the object's functions. If you expose() a function, spawn will also return a callable function, not an object.

Usage

Find the full documentation on the website:

Webpack

Threads.js works with webpack. Usually all you need to do is adding the threads-plugin.

See Build with webpack on the website for details.

Debug

We are using the debug package to provide opt-in debug logging. All the package's debug messages have a scope starting with threads:, with different sub-scopes:

  • threads:master:messages
  • threads:master:spawn
  • threads:master:thread-utils
  • threads:pool:${poolName || poolID}

Set it to DEBUG=threads:* to enable all the library's debug logging. To run its tests with full debug logging, for instance:

DEBUG=threads:* npm test

License

MIT

More Repositories

1

webpack-blocks

πŸ“¦ Configure webpack using functional feature blocks.
JavaScript
2,974
star
2

leakage

πŸ› Memory leak testing for node.
JavaScript
1,583
star
3

pg-listen

πŸ“‘ PostgreSQL LISTEN & NOTIFY for node.js that finally works.
TypeScript
540
star
4

typed-emitter

πŸ”© Type-safe event emitter interface for TypeScript
JavaScript
250
star
5

use-inline-memo

βš›οΈ React hook for memoizing values inline anywhere in a component
TypeScript
163
star
6

postguard

πŸ› Statically validate Postgres SQL queries in JS / TS code and derive schemas.
TypeScript
161
star
7

laravel-js-localization

Simple, ease-to-use and flexible package for the Laravel web framework. Allows you to use localized messages of the Laravel webapp (see `resources/lang` directory) in your Javascript code.
PHP
143
star
8

squid

πŸ¦‘ Provides SQL tagged template strings and schema definition functions.
TypeScript
124
star
9

ava-ts

πŸš€ Fork of the AVA test runner with native typescript support
JavaScript
116
star
10

postcss-debug

Debug your postcss workflow with ease! Creates snapshots of your CSS files before/after each postcss plugin is run.
JavaScript
94
star
11

react-usestyles

πŸ– Style components using React hooks. Abstracts the styling library away.
JavaScript
87
star
12

postcss-theme

PostCSS plugin to enable versatile theming.
JavaScript
87
star
13

react-stateful-fn

βš› Stateful functional components for React.
JavaScript
57
star
14

puppet-run

πŸ€– Run anything JavaScript in a headless Chrome from your command line
TypeScript
53
star
15

threadpool-js

Javascript thread pool implementation using web workers.
JavaScript
47
star
16

jquery-dim-background

jQuery plugin to dim the current page except for some user-defined top elements.
JavaScript
43
star
17

observable-fns

πŸ•΅οΈβ€β™€οΈ Light-weight observable implementation and functional utilities in TypeScript
TypeScript
41
star
18

npm-launch

πŸš€ Minimalistic task runner on steroids!
JavaScript
39
star
19

drag-mock

Trigger HTML5 drag & drop events for testing
JavaScript
35
star
20

gear

πŸ›  Experimental tool to bootstrap typed JavaScript code.
JavaScript
33
star
21

proposal-double-colon-types

πŸ€“ JS / Flow syntax proposal. Types Γ  la Hindley-Milner.
20
star
22

http-event-stream

πŸ“‘ Modern spec-compliant Server Sent Events stream implementation.
TypeScript
19
star
23

ts

βš™οΈ The CLI that TypeScript deserves.
TypeScript
18
star
24

key-store

πŸ” Isomorphic encrypted key store written in TypeScript.
TypeScript
17
star
25

plow

πŸ‘¨β€πŸŒΎ Postgres migrations and seeding made easy
TypeScript
14
star
26

isomorphic-crypto

πŸ”’ Isomorphic crypto package for node and the browser.
JavaScript
12
star
27

type-reflect

☝️ TypeScript plugin providing access to type information at runtime
TypeScript
11
star
28

srv

πŸ“‘ Functional node server. Composable routing. Take a request, return a response.
TypeScript
9
star
29

rungpt

GPT client with local plugin framework, built by GPT-4
TypeScript
9
star
30

php-easygit

Manage Git repositories from within your PHP webapp. Commit, branch, clone, checkout, ...
PHP
7
star
31

zaster

πŸ’Έ Headless multi-blockchain wallet and SDK.
TypeScript
7
star
32

react-commandments

πŸ“– Thou shalt honor thy reactive code and keep it holy.
6
star
33

koa-router-index

Koa v2 middleware to create an index page for API servers.
JavaScript
5
star
34

gulp-elixir-modules

Elixir extension for handling frontend modules easily.
JavaScript
5
star
35

json-sql-import

Small PHP tool to import JSON data into database tables using transformation rules.
PHP
4
star
36

puppet-run-plugins

🧩 Plugins for puppet-run.
TypeScript
4
star
37

shutter-legacy

πŸ“Έ Visual snapshot testing with no effort.
TypeScript
3
star
38

deep-assert

πŸ” Better deep-equals comparison, supporting custom property assertions and pretty diffs.
TypeScript
3
star
39

ideabox

Place to collect techy ideas and get feedback.
1
star
40

bundle-decomposition-research

JavaScript
1
star
41

stellar-wallet

With the new Stellar wallet to the moon πŸš€
JavaScript
1
star