Skip to content

Instantly share code, notes, and snippets.

@domenic
Last active October 20, 2022 11:10
Show Gist options
  • Save domenic/ea5ebedffcee27f552e103963cf8585c to your computer and use it in GitHub Desktop.
Save domenic/ea5ebedffcee27f552e103963cf8585c to your computer and use it in GitHub Desktop.
Service worker stream transferring
"use strict";
const worker = new Worker("worker.js");
self.onfetch = e => {
const transform = new TransformStream(); // creates an identity transform
e.respondWith(new Response(transform.readable));
// Give the worker the writable end. An identity transform stream will just shuffle
// bytes written there into transform.readable.
worker.postMessage(transform.writable, [transform.writable]);
// transform.writable has now been transferred/neutered/detached.
// This means that transform.writable.getWriter() will never work anymore in this thread.
// However, the *creator* of transform.writable (i.e., the logic inside
// new TransformStream()) can still see data that is written to it. That logic
// will then shuffle it over to transform.readable.
};
"use strict";
self.onmessage = ({ data: writableStream }) => {
const writer = writableStream.getWriter();
writer.write(new Uint8Array([1, 2, 3, 4]));
writer.close();
// You can, of course, do the writing/closing asynchronously.
};
@kettanaito
Copy link

@guest271314, yes, that was the root cause! 🎉 I've come to discover it as well. You should transfer encoded data over ReadableStream.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment