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.
FeaturesFeatures
- 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.xVersion 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.
InstallationInstallation
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 supportPlatform support
Run on.
Webpack build setup
Webpack configWebNodeWhen using TypeScript
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.
Getting StartedGetting Started
BasicsBasics
// master.jsconst auth = awaitconst hashed = await authconsoleawait Thread
// workers/auth.js
spawn()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()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.
UsageUsage
Find the full documentation on the website:
WebpackWebpack
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.
DebugDebug
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
LicenseLicense
MIT