-
-
Save kael/c443ee3338303fa49a53e32168c6fe21 to your computer and use it in GitHub Desktop.
Service worker stream transferring
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"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. | |
}; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"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. | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment