### Install Dependencies and Serve Locally Source: https://github.com/andywer/threads.js/blob/master/docs/README.md Installs project dependencies using Bundler and then serves the Jekyll site locally. Ensure you have Ruby and Bundler installed. ```sh bundle install --path vendor/bundle bundle exec jekyll serve --baseurl '' ``` -------------------------------- ### Install threads.js Source: https://github.com/andywer/threads.js/blob/master/docs/index.md Install the threads.js library using npm. ```bash npm install threads ``` -------------------------------- ### Install threads.js and tiny-worker Source: https://github.com/andywer/threads.js/blob/master/README.md Install the threads.js package. Include tiny-worker for Node.js versions older than 12. ```bash npm install threads tiny-worker ``` -------------------------------- ### Handling Task Results and Pool Lifecycle Source: https://github.com/andywer/threads.js/blob/master/docs/usage-pool.md Illustrates a complete example of setting up a thread pool, queuing a task, handling its result using .then(), and managing the pool's lifecycle by awaiting completion and termination. ```javascript import { spawn, Pool, Worker } from "threads" const pool = Pool(() => spawn(new Worker("./workers/crytpo"))) const task = pool.queue(crypto => crypto.encrypt("some-password")) task.then(result => { // do something with the result }) await pool.completed() await pool.terminate() ``` -------------------------------- ### Install threads-plugin for Webpack Source: https://github.com/andywer/threads.js/blob/master/README.md Install the threads-plugin using npm. This plugin helps bundle worker code automatically. ```sh npm install -D threads-plugin ``` -------------------------------- ### Scheduling a Task with Pool Source: https://github.com/andywer/threads.js/blob/master/docs/usage-pool.md Demonstrates how to queue a task to a thread pool and handle its result asynchronously. It shows the basic setup for spawning workers and queuing tasks. ```typescript let pool: Pool type TaskFunction = (thread: ThreadType) => Promise | T pool.queue(task: TaskFunction): Promise ``` -------------------------------- ### Cancel a Queued Task Source: https://github.com/andywer/threads.js/blob/master/docs/usage-pool.md Cancel a task that has been queued but not yet started. If the task is already executing, cancellation will fail. ```javascript const task = pool.queue(multiplierWorker => multiplierWorker(2, 3)) task.cancel() ``` -------------------------------- ### Type-Safe Workers with TypeScript Source: https://github.com/andywer/threads.js/blob/master/docs/usage.md Declare worker types when spawning to enable type-safe interactions. This example uses a HashFunction type. ```typescript // master.ts import { spawn, Thread, Worker } from "threads" type HashFunction = (input: string) => Promise const sha512 = await spawn(new Worker("./workers/sha512")) const hashed = await sha512("abcdef") ``` -------------------------------- ### Type-Safe Workers with Exported Types Source: https://github.com/andywer/threads.js/blob/master/docs/usage.md Export worker types from the worker module and use them when spawning for enhanced type safety. This example uses a Counter type. ```typescript // master.ts import { spawn, Thread, Worker } from "threads" import { Counter } from "./workers/counter" const counter = await spawn(new Worker("./workers/counter")) console.log(`Initial counter: ${await counter.getCount()}`) await counter.increment() console.log(`Updated counter: ${await counter.getCount()}`) await Thread.terminate(counter) ``` ```typescript // counter.ts import { expose } from "threads/worker" let currentCount = 0 const counter = { getCount() { return currentCount }, increment() { return ++currentCount }, decrement() { return --currentCount } } export type Counter = typeof counter expose(counter) ``` -------------------------------- ### Spawn and Expose a GitHub Profile Fetcher Source: https://github.com/andywer/threads.js/blob/master/docs/usage.md Shows how to spawn a worker that fetches a GitHub user profile asynchronously and returns the JSON data. The master thread then logs the user's signup date. ```javascript // master.js import { spawn, Thread, Worker } from "threads" const fetchGithubProfile = await spawn(new Worker("./workers/fetch-github-profile")) const andywer = await fetchGithubProfile("andywer") console.log(`User "andywer" has signed up on ${new Date(andywer.created_at).toLocaleString()}`) await Thread.terminate(fetchGithubProfile) ``` ```javascript // workers/fetch-github-profile.js import fetch from "isomorphic-fetch" import { expose } from "threads/worker" expose(async function fetchGithubProfile(username) { const response = await fetch(`https://api.github.com/users/${username}`) return response.json() }) ``` -------------------------------- ### Spawn and Expose a Simple Add Worker Source: https://github.com/andywer/threads.js/blob/master/docs/usage.md Demonstrates spawning a worker that exposes a single function for addition and calling it from the main thread. Ensure the worker file path is correct. ```javascript // 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) ``` ```javascript // workers/add.js import { expose } from "threads/worker" expose(function add(a, b) { return a + b }) ``` -------------------------------- ### Master script to spawn and communicate with a worker Source: https://github.com/andywer/threads.js/blob/master/docs/index.md This script demonstrates how to spawn a worker, call a method on it, and terminate the worker. It uses async/await for handling results. ```javascript // 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) ``` -------------------------------- ### Create and Use a Thread Pool Source: https://github.com/andywer/threads.js/blob/master/docs/usage-pool.md Instantiate a pool with a worker factory and an optional size. Queue tasks to be executed by available workers. Ensure to terminate the pool when done. ```javascript import { spawn, Pool, Worker } from "threads" const pool = Pool(() => spawn(new Worker("./workers/multiplier")), 8 /* optional size */) pool.queue(async multiplier => { const multiplied = await multiplier(2, 3) console.log(`2 * 3 = ${multiplied}`) }) await pool.completed() await pool.terminate() ``` -------------------------------- ### Spawn a worker and call a method Source: https://github.com/andywer/threads.js/blob/master/docs/getting-started.md This snippet shows how to spawn a worker using `spawn` and invoke a method (`hashPassword`) on it. It also demonstrates terminating the worker using `Thread.terminate`. ```javascript // master.js import { spawn, Thread, Worker } from "threads" async function main() { 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) } main().catch(console.error) ``` -------------------------------- ### Observable Subject Basics Source: https://github.com/andywer/threads.js/blob/master/docs/usage-observables.md Demonstrates the basic usage of Observable and Subject. Subjects allow triggering observable updates from outside the observer context. ```javascript const observable = new Observable(observer => { // We can call `.next()`, `.error()`, `.complete()` only here // as they are only exposed on the `observer` observer.complete() }) const subject = new Subject() subject.complete() // We are free to call `.next()`, `.error()`, `.complete()` from anywhere now // Beware: With great power comes great responsibility! Don't write spaghetti code. ``` ```javascript const subscriptionOne = observable.subscribe(/* ... */) subscriptionOne.unsubscribe() const subscriptionTwo = subject.subscribe(/* ... */) subscriptionTwo.unsubscribe() ``` -------------------------------- ### Spawn and Expose a Module Worker for Counter Operations Source: https://github.com/andywer/threads.js/blob/master/docs/usage.md Demonstrates using a module worker to expose multiple functions (increment, decrement, getCount) for managing a counter. The master thread calls these functions and logs the final count. ```javascript // master.js import { spawn, Thread, Worker } from "threads" const counter = await spawn(new Worker("./workers/counter")) await counter.increment() await counter.increment() await counter.decrement() console.log(`Counter is now at ${await counter.getCount()}`) await Thread.terminate(counter) ``` ```javascript // workers/counter.js import { expose } from "threads/worker" let currentCount = 0 const counter = { getCount() { return currentCount }, increment() { return ++currentCount }, decrement() { return --currentCount } } expose(counter) ``` -------------------------------- ### Configure Electron-Webpack for Threads Source: https://github.com/andywer/threads.js/blob/master/docs/getting-started.md Add 'threads' to 'whiteListedModules' in your webpackElectron configuration for Electron-webpack projects. ```diff "electronWebpack": { "whiteListedModules": [ + "threads" ] } ``` -------------------------------- ### Configure Webpack for Node.js Bundles Source: https://github.com/andywer/threads.js/blob/master/docs/getting-started.md Prevent bundling of 'tiny-worker' when creating Node.js bundles by adding it to externals. ```diff module.exports = { // ... + externals: { + "tiny-worker": "tiny-worker" + } // ... } ``` -------------------------------- ### Configure Webpack for Node.js bundles Source: https://github.com/andywer/threads.js/blob/master/README.md When creating Node.js bundles with Webpack, externalize 'tiny-worker' to prevent it from being bundled. Ensure 'tiny-worker' is in your package.json dependencies. ```javascript module.exports = { // ... externals: { "tiny-worker": "tiny-worker" } // ... } ``` -------------------------------- ### Subscribe to Thread Events Source: https://github.com/andywer/threads.js/blob/master/docs/usage-advanced.md Listen for various events emitted by a spawned thread for debugging or monitoring purposes. Ensure the thread is spawned before subscribing. ```typescript import { spawn, Thread, Worker } from "threads" const myThread = await spawn(new Worker("./mythread")) Thread.events(myThread).subscribe(event => console.log("Thread event:", event)) ``` -------------------------------- ### Enable All Threads.js Debug Logging Source: https://github.com/andywer/threads.js/blob/master/docs/usage-advanced.md Set the DEBUG environment variable to 'threads:*' to enable all debug logs from the threads.js library. This is useful for comprehensive troubleshooting. ```bash DEBUG=threads:* npm test ``` -------------------------------- ### Configure Electron ASAR Unpack for Workers Source: https://github.com/andywer/threads.js/blob/master/docs/getting-started.md Specify worker files in 'asarUnpack' within your package.json to ensure they are accessible when packaged in an ASAR archive. ```diff + "asarUnpack": { + "dist/main/0.bundle.worker.js", + "dist/main/0.bundle.worker.js.map" + } ``` -------------------------------- ### Implement Custom Class Serializer Source: https://github.com/andywer/threads.js/blob/master/docs/usage-advanced.md Define a custom serializer for a class to enable passing instances between threads. This involves implementing `serialize` and `deserialize` methods and defining a serialized representation. ```typescript import { SerializerImplementation } from "threads" interface SerializedMyClass { __type: "$$MyClass" state: string } class MyClass { state: string constructor(initialState: string) { this.state = initialState } doStuff() { // Do fancy things } serialize(): SerializedMyClass { return { __type: "$$MyClass", state: this.state } } static deserialize(message: SerializedMyClass) { return new MyClass(message.state) } } const MySerializer: SerializerImplementation = { deserialize(message, defaultHandler) { if (message && message.__type === "$$MyClass") { return MyClass.deserialize(message as any) } else { return defaultHandler(message) } }, serialize(thing, defaultHandler) { if (thing instanceof MyClass) { return thing.serialize() } else { return defaultHandler(thing) } } } ``` -------------------------------- ### Pool Creation Options Source: https://github.com/andywer/threads.js/blob/master/docs/usage-pool.md Defines the interface for PoolOptions, specifying concurrency, max queued jobs, a custom name, and the number of workers (size). ```typescript interface PoolOptions { concurrency?: number maxQueuedJobs?: number name?: string size?: number } function Pool(threadFactory: () => Thread, size?: number): Pool function Pool(threadFactory: () => Thread, options?: PoolOptions): Pool ``` -------------------------------- ### Register Threads Worker Implementation with Parcel Source: https://github.com/andywer/threads.js/blob/master/docs/getting-started.md Import 'threads/register' once in your main application code when using Parcel to enable threads.js worker handling. ```diff import { spawn } from "threads" + import "threads/register" // ... const work = await spawn(new Worker("./worker")) ``` -------------------------------- ### Configure TypeScript for Webpack Source: https://github.com/andywer/threads.js/blob/master/docs/getting-started.md Ensure TypeScript compiler options preserve 'esnext' module format for webpack to resolve imports correctly. ```diff module.exports = { // ... module: { rules: [ { test: /\.ts$/, loader: "ts-loader", + options: { + compilerOptions: { + module: "esnext" + } + } } ] }, // ... } ``` -------------------------------- ### Master: Stream Min/Max Values Source: https://github.com/andywer/threads.js/blob/master/docs/usage-observables.md Master code to spawn a worker that streams min/max values. Subscribe to the values() observable to receive updates as they are computed. ```javascript import { spawn, Thread, Worker } from "threads" const minmax = await spawn(new Worker("./workers/minmax")) minmax.values().subscribe(({ min, max }) => { console.log(`Min: ${min} | Max: ${max}`) }) await minmax.add(2) await minmax.add(3) await minmax.add(4) await minmax.add(1) await minmax.add(5) await minmax.finish() await Thread.terminate(minmax) ``` -------------------------------- ### Error Handling in Worker Threads Source: https://github.com/andywer/threads.js/blob/master/docs/usage.md Illustrates transparent error handling by wrapping worker calls in a try-catch block. Errors thrown in the worker will reject the promise in the master thread, including the worker's stack trace. ```javascript // master.js import { spawn, Thread, Worker } from "threads" const counter = await spawn(new Worker("./workers/counter")) try { await counter.increment() await counter.increment() await counter.decrement() console.log(`Counter is now at ${await counter.getCount()}`) } catch (error) { console.error("Counter thread errored:", error) } finally { await Thread.terminate(counter) } ``` -------------------------------- ### Await Completion of Specific Tasks Source: https://github.com/andywer/threads.js/blob/master/docs/usage-pool.md Use `Promise.all` to wait for a specific set of queued tasks to complete. This is useful when you need to ensure a subset of operations finishes before proceeding, while other pool tasks might still be running. ```typescript // (Created a pool and queued other pool tasks before…) const myTasks: QueuedTask[] = [] for (let input = 0; input < 5; input++) { const task = pool.queue(worker => worker.work(input)) myTasks.push(task) } await Promise.all(myTasks) console.log("All worker.work() tasks have completed. Other pool tasks might still be running.") ``` -------------------------------- ### Register Custom Serializer Source: https://github.com/andywer/threads.js/blob/master/docs/usage-advanced.md Register a custom serializer in both the main thread and worker threads. This must be done early, before spawning or exposing threads. ```typescript import { registerSerializer } from "threads" // also exported from the worker sub-module: // import { registerSerializer } from "threads/worker" registerSerializer(MySerializer) ``` -------------------------------- ### Inline Worker Code with BlobWorker Source: https://github.com/andywer/threads.js/blob/master/docs/usage.md Use BlobWorker.fromText to inline worker source code, useful for self-contained libraries. Requires raw-loader for webpack. ```javascript import { spawn, BlobWorker } from "threads" import MyWorkerNode from "raw-loader!../dist/worker.node/worker.js" import MyWorkerWeb from "raw-loader!../dist/worker.web/worker.js" const MyWorker = process.browser ? MyWorkerWeb : MyWorkerNode const worker = await spawn(BlobWorker.fromText(MyWorker)) // Now use this worker as always ``` -------------------------------- ### Google Analytics Tracking Code Source: https://github.com/andywer/threads.js/blob/master/docs/_includes/analytics-providers/google.html This snippet initializes Google Analytics tracking. It configures anonymize_ip and storage settings based on site configuration. ```html {%- if site.analytics.google.tracking_id -%} window.dataLayer = window.dataLayer || []; function gtag() { dataLayer.push(arguments); } gtag('js', new Date()); {% if site.analytics.google.anonymize_ip == true %} gtag('config', '{{ site.analytics.google.tracking_id }}', { 'anonymize_ip': true, 'storage': 'none' }); {% else %} gtag('config', '{{ site.analytics.google.tracking_id }}'); {% endif %} {%- endif -%} ``` -------------------------------- ### Expose worker functionality Source: https://github.com/andywer/threads.js/blob/master/docs/getting-started.md This snippet defines the functionality exposed by a worker thread. It uses `expose` to make the `hashPassword` function available to the main thread. ```javascript // workers/auth.js - will be run in worker thread import sha256 from "js-sha256" import { expose } from "threads/worker" expose({ hashPassword(password, salt) { return sha256(password + salt) } }) ``` -------------------------------- ### Worker script to expose a function Source: https://github.com/andywer/threads.js/blob/master/docs/index.md This worker script exposes a 'hashPassword' function that can be called by the master script. It uses 'js-sha256' for hashing. ```javascript // workers/auth.js import sha256 from "js-sha256" import { expose } from "threads/worker" expose({ hashPassword(password, salt) { return sha256(password + salt) } }) ``` -------------------------------- ### Configure TypeScript for Webpack with threads-plugin Source: https://github.com/andywer/threads.js/blob/master/README.md Ensure your TypeScript configuration for Webpack uses 'esnext' module format to preserve import/export statements. This is required for threads-plugin to correctly resolve worker bundles. ```javascript module.exports = { // ... module: { rules: [ { test: /\.ts$/, loader: "ts-loader", options: { compilerOptions: { module: "esnext" } } } ] }, // ... } ``` -------------------------------- ### Observable from Subject Source: https://github.com/andywer/threads.js/blob/master/docs/usage-observables.md Create a read-only observable that proxies values from a subject using Observable.from(). This prevents external code from triggering subject updates. ```javascript // The returned observable will be read-only return Observable.from(subject) ``` -------------------------------- ### Register Multiple Custom Serializers Source: https://github.com/andywer/threads.js/blob/master/docs/usage-advanced.md Chain multiple custom serializers by calling `registerSerializer` multiple times. The last registered serializer is invoked first, with fallbacks to previously registered ones. ```typescript import { registerSerializer } from "threads" registerSerializer(SomeSerializer) registerSerializer(AnotherSerializer) // threads.js will first try to use AnotherSerializer, will fall back to SomeSerializer, // eventually falls back to passing the data as is if no serializer can handle it ``` -------------------------------- ### Return Transferred ArrayBuffer from Worker Source: https://github.com/andywer/threads.js/blob/master/docs/usage-advanced.md Use `Transfer()` when returning an ArrayBuffer from a worker to transfer its ownership. This avoids copying the buffer back to the calling thread. ```javascript import { expose, Transfer } from "threads/worker" expose(function xorBuffer(buffer, value) { const view = new Uint8Array(buffer) view.forEach((byte, offset) => view.set([byte ^ value], offset)) return Transfer(buffer) }) ``` -------------------------------- ### Worker: Return an Observable Source: https://github.com/andywer/threads.js/blob/master/docs/usage-observables.md In the worker code, return an Observable that emits values. Ensure the Observable implementation is compatible (e.g., zen-observable). ```javascript import { Observable } from "observable-fns" import { expose } from "threads/worker" function startCounting() { return new Observable(observer => { for (let currentCount = 1; currentCount <= 10; currentCount++) { observer.next(currentCount) } observer.complete() }) } expose(startCounting) ``` -------------------------------- ### Transfer ArrayBuffer to Worker Source: https://github.com/andywer/threads.js/blob/master/docs/usage-advanced.md Use `Transfer()` to mark an ArrayBuffer to be transferred to the receiving thread. This is useful for large binary data to avoid copying. ```javascript import { spawn, Transfer, Worker } from "threads" const xorBuffer = await spawn(new Worker("./workers/arraybuffer-xor")) const resultBuffer = await xorBuffer(Transfer(testData), 127) ``` -------------------------------- ### Register threads.js Worker for Parcel Source: https://github.com/andywer/threads.js/blob/master/README.md Import 'threads/register' once in your main application code when using Parcel. This globally registers threads.js's Worker implementation, allowing 'new Worker()' to work correctly. ```javascript import { spawn } from "threads" import "threads/register" // ... const work = await spawn(new Worker("./worker")) ``` -------------------------------- ### Subscribe to Thread Errors Source: https://github.com/andywer/threads.js/blob/master/docs/usage-advanced.md Specifically listen for error events from a thread. This is useful for isolating and handling thread-specific exceptions. ```typescript Thread.errors(myThread).subscribe(error => console.log("Thread error:", error)) ``` -------------------------------- ### Master: Subscribe to Worker Observable Source: https://github.com/andywer/threads.js/blob/master/docs/usage-observables.md In the master code, subscribe to the observable returned by the worker to receive streamed results. ```javascript import { spawn, Thread, Worker } from "threads" const counter = await spawn(new Worker("./workers/counter")) counter().subscribe(newCount => console.log(`Counter incremented to:`, newCount)) ``` -------------------------------- ### Worker: Compute and Stream Min/Max Source: https://github.com/andywer/threads.js/blob/master/docs/usage-observables.md Worker code that computes minimum and maximum values and streams updates using an Observable Subject. The values() method returns a read-only observable. ```javascript import { Observable, Subject } from "threads/observable" import { expose } from "threads/worker" let max = -Infinity let min = Infinity let subject = new Subject() const minmax = { finish() { subject.complete() subject = new Subject() }, add(value) { max = Math.max(max, value) min = Math.min(min, value) subject.next({ max, min }) }, values() { return Observable.from(subject) } } expose(minmax) ``` -------------------------------- ### Add Threads Plugin to Webpack Config Source: https://github.com/andywer/threads.js/blob/master/docs/getting-started.md Integrate the threads-plugin into your webpack.config.js to automatically bundle worker files. ```diff + const ThreadsPlugin = require('threads-plugin') module.exports = { // ... plugins: [ + new ThreadsPlugin() ] // ... } ``` -------------------------------- ### Terminate Pool Gracefully Source: https://github.com/andywer/threads.js/blob/master/docs/usage-pool.md Terminate the pool, waiting for all scheduled tasks to complete before shutting down workers. ```javascript // Terminate gracefully pool.terminate() ``` -------------------------------- ### Transfer ArrayBuffer in Observable Stream from Worker Source: https://github.com/andywer/threads.js/blob/master/docs/usage-advanced.md Use `Transfer()` within an Observable stream to transfer ArrayBuffers as they are emitted. This maintains efficiency when streaming large binary data. ```javascript import { expose, Observable, Transfer } from "threads/worker" import { DataSource } from "./my-data-source" expose(function streamBuffers() { return new Observable(observer => { const datasource = new DataSource() datasource.on("data", arrayBuffer => observer.next(Transfer(arrayBuffer))) return () => datasource.close() }) }) ``` -------------------------------- ### Add threads-plugin to Webpack config Source: https://github.com/andywer/threads.js/blob/master/README.md Integrate the threads-plugin into your webpack.config.js file by adding it to the plugins array. This enables automatic detection and bundling of worker expressions. ```javascript const ThreadsPlugin = require('threads-plugin'); module.exports = { // ... plugins: [ new ThreadsPlugin() ] // ... } ``` -------------------------------- ### Force-Terminate Pool Workers Source: https://github.com/andywer/threads.js/blob/master/docs/usage-pool.md Forcefully terminate the pool immediately, without waiting for ongoing tasks to complete. ```javascript // Force-terminate pool workers pool.terminate(true) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.