1 Matching Annotations
- Dec 2021
-
github.com github.com
-
// main.js const { RemoteReadableStream, RemoteWritableStream } = RemoteWebStreams; (async () => { const worker = new Worker('./worker.js'); // create a stream to send the input to the worker const { writable, readablePort } = new RemoteWritableStream(); // create a stream to receive the output from the worker const { readable, writablePort } = new RemoteReadableStream(); // transfer the other ends to the worker worker.postMessage({ readablePort, writablePort }, [readablePort, writablePort]); const response = await fetch('./some-data.txt'); await response.body // send the downloaded data to the worker // and receive the results back .pipeThrough({ readable, writable }) // show the results as they come in .pipeTo(new WritableStream({ write(chunk) { const results = document.getElementById('results'); results.appendChild(document.createTextNode(chunk)); // tadaa! } })); })();
// worker.js const { fromReadablePort, fromWritablePort } = RemoteWebStreams; self.onmessage = async (event) => { // create the input and output streams from the transferred ports const { readablePort, writablePort } = event.data; const readable = fromReadablePort(readablePort); const writable = fromWritablePort(writablePort); // process data await readable .pipeThrough(new TransformStream({ transform(chunk, controller) { controller.enqueue(process(chunk)); // do the actual work } })) .pipeTo(writable); // send the results back to main thread };
-