
Security News
Vite+ Joins the Push to Consolidate JavaScript Tooling
Evan You announces Vite+, a commercial, Rust-powered toolchain built on the Vite ecosystem to unify JavaScript development and fund open source.
Easy to use, yet powerful multi-threading library for node.js, web browsers and Electron
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.
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.
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.
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.
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()
]
// ...
}
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.
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"
+ }
+ }
}
]
},
// ...
}
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.
// master.js
import { spawn, Thread, Worker } from "threads"
async function main() {
const add = await spawn(new Worker("./workers/add"))
const sum = await add(2, 3)
console.log(`2 + 3 = ${sum}`)
await Thread.terminate(add)
}
main().catch(console.error)
// workers/add.js
import { expose } from "threads/worker"
expose(function add(a, b) {
return a + b
})
The return value of add()
in the master code depends on the add()
return value in the worker:
If the 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.
Use expose()
to make either a function or an object callable from the master thread.
In case of exposing an object, spawn()
will asynchronously return an object exposing all the object's functions, following the same rules as functions directly expose()
-ed.
Find the full documentation on the website:
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
MIT
'jest-worker' is a package developed by Facebook for parallelizing tasks in Node.js. It is commonly used in the Jest testing framework to run tests in parallel. While it provides similar functionality to 'threads', it is more specialized for use cases involving task parallelization in testing environments.
'piscina' is a fast, efficient worker thread pool implementation for Node.js. It allows you to manage a pool of worker threads to handle multiple tasks concurrently. 'piscina' is designed for high performance and scalability, making it a good alternative to 'threads' for more complex parallel processing needs.
FAQs
Web workers & worker threads as simple as a function call
The npm package threads receives a total of 228,041 weekly downloads. As such, threads popularity was classified as popular.
We found that threads demonstrated a not healthy version release cadence and project activity because the last version was released 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
Evan You announces Vite+, a commercial, Rust-powered toolchain built on the Vite ecosystem to unify JavaScript development and fund open source.
Security News
Ruby Central’s incident report on the RubyGems.org access dispute sparks backlash from former maintainers and renewed debate over project governance.
Research
/Security News
Socket researchers uncover how threat actors weaponize Discord across the npm, PyPI, and RubyGems ecosystems to exfiltrate sensitive data.