npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

next-webworker-pool

v0.0.6

Published

A NPM package that enables developers to build Web Worker pools that can be used in (but not limited to) Next.js applications

Downloads

599

Readme

next-webworker-pool

.github/workflows/publish.yaml

A no-dependency package that enables developers to build Web Worker pools for Next.js applications.

Example

You can find an example Next.js project using next-webworker-pool here.

Installation

npm install next-webworker-pool

Usage

1. Create a Web Worker file

This is the file that will be run inside the Web Worker.

// my-worker.ts
import type { WebWorkerTask, WebWorkerResult } from 'next-webworker-pool';

type MyInput = number; // can be anything that the client will send
type MyOutput = number; // can be anything that the client will receive

self.onmessage = function (e: MessageEvent<WebWorkerTask<MyInput, MyOutput>>) {
    self.postMessage(runTask(e.data));
};

function runTask(
    task: WebWorkerTask<MyInput, MyOutput>,
): WebWorkerResult<MyInput> {
    const result = task.data + 1; // do something with the input

    return {
        id: task.id,
        data: result,
    };
}

2. Create a Web Worker pool by extending the WebWorkerPool class or use the factory function

This is a class that is responsible for creating Web Workers from a specific source, and running tasks on them.

This pattern is used, because Next.js scans the source code for new Worker(new URL(...)) calls, and replaces them with the Next.js custom bundling implementation.

Using the factory function

// my-worker-pool.ts
import { createWebWorkerPool } from 'next-webworker-pool';

import type { MyInput, MyOutput } from './my-worker';

export const myWorkerPool = createWebWorkerPool<MyInput, MyOutput>(
    new URL('./my-worker.ts', import.meta.url),
    { maxWorkers: 4 },
);

The worker pool can then be used directly in your Next.js application:

// pages/index.tsx

import { myWorkerPool } from '../my-worker-pool';

export default function Home() {
    const [result, setResult] = useState<number | null>(null);

    useEffect(() => {
        const task = myWorkerPool.executeTask(1); // run the task with input 1

        // wait for the task to finish and use the result
        task.promise
            .then((result) => {
                setResult(result);
            })
            .catch((error) => {
                console.error(error);
            });

        return () => {
            // terminate the Web Worker pool when the component is unmounted
            myWorkerPool.terminate();
        };
    }, []);

    return <div>{result}</div>;
}

Extending the WebWorkerPool class

// my-worker-pool.ts
import { WebWorkerPool } from 'next-webworker-pool';

import type { MyInput, MyOutput } from './my-worker';

export class MyWorkerPool extends WebWorkerPool<MyInput, MyOutput> {
    _createWorker(): Worker {
        return new Worker(new URL('./my-worker.ts', import.meta.url));
    }
}

To use the Web Worker pool, you need to create an instance of it, and call the run method with the input data.

// pages/index.tsx
import { MyWorkerPool } from '../my-worker-pool';

export default function Home() {
    const [result, setResult] = useState<number | null>(null);

    useEffect(() => {
        // create a new instance of the Web Worker pool
        const pool = new MyWorkerPool();

        const task = pool.executeTask(1); // run the task with input 1

        // wait for the task to finish and use the result
        task.promise
            .then((result) => {
                setResult(result);
            })
            .catch((error) => {
                console.error(error);
            });

        return () => {
            // terminate the Web Worker pool when the component is unmounted
            pool.terminate();
        };
    }, []);

    return <div>{result}</div>;
}

Options

maxWorkers

The maximum number of Web Workers that can be created by the pool. Defaults to navigator.hardwareConcurrency or 4 if hardwareConcurrency is not supported.

// my-worker-pool.ts

export class MyWorkerPool extends WebWorkerPool<MyInput, MyOutput> {
    constructor() {
        super({
            maxWorkers: 4,
        });
    }

    createWorker(): Worker {
        return new Worker(new URL('./my-worker.ts', import.meta.url));
    }
}