+ Native cross-platform Web Workers. Works in published npm modules. +
++ +
+ +**In Node**, it's a web-compatible Worker implementation atop Node's [worker_threads](https://nodejs.org/api/worker_threads.html). + +**In the browser** (and when bundled for the browser), it's simply an alias of `Worker`. + +### Features + +_Here's how this is different from worker_threads:_ + +- makes Worker code compatible across browser and Node +- supports Module Workers (`{type:'module'}`) natively in Node 12.8+ +- uses DOM-style events (`Event.data`, `Event.type`, etc) +- supports event handler properties (`worker.onmessage=..`) +- `Worker()` accepts a module URL, Blob URL or Data URL +- emulates browser-style [WorkerGlobalScope] within the worker + +### Usage Example + +In its simplest form: + +```js +import Worker from 'web-worker'; + +const worker = new Worker('data:,postMessage("hello")'); +worker.onmessage = e => console.log(e.data); // "hello" +``` + +main.js | worker.js |
---|---|
+ +```js +import Worker from 'web-worker'; + +const url = new URL('./worker.js', import.meta.url); +const worker = new Worker(url); + +worker.addEventListener('message', e => { + console.log(e.data) // "hiya!" +}); + +worker.postMessage('hello'); +``` + + | + +```js +addEventListener('message', e => { + if (e.data === 'hello') { + postMessage('hiya!'); + } +}); +``` + + |
main.mjs | worker.mjs |
---|---|
+ +```js +import Worker from 'web-worker'; + +const worker = new Worker( + new URL('./worker.mjs', import.meta.url), + { type: 'module' } +); +worker.addEventListener('message', e => { + console.log(e.data) // "200 OK" +}); +worker.postMessage('https://httpstat.us/200'); +``` + + | + +```js +import fetch from 'isomorphic-fetch'; + +addEventListener('message', async e => { + const url = e.data; + const res = await fetch(url) + const text = await res.text(); + postMessage(text); +}); +``` + + |