Skip to content

Commit

Permalink
docs: Web Streams Example (#360)
Browse files Browse the repository at this point in the history
Co-authored-by: James M Snell <jasnell@gmail.com>
Co-authored-by: Rafael Gonzaga <rafael.nunu@hotmail.com>
  • Loading branch information
3 people authored Jun 21, 2023
1 parent a38fb29 commit 7311996
Show file tree
Hide file tree
Showing 4 changed files with 79 additions and 0 deletions.
38 changes: 38 additions & 0 deletions examples/webstreams-transform/index.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import Piscina from 'piscina';
import {
ReadableStream,
TransformStream,
WritableStream
} from 'node:stream/web';

const pool = new Piscina({
filename: new URL('./worker.mjs', import.meta.url).href
});

const readable = new ReadableStream({
start () {
this.chunks = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0];
},

pull (controller) {
const chunk = this.chunks.shift();
controller.enqueue(chunk);
if (this.chunks.length === 0) {
controller.close();
}
}
});

const writable = new WritableStream({
write (chunk) {
console.log(chunk);
}
});

const transform = new TransformStream({
async transform (chunk, controller) {
controller.enqueue(await pool.run(chunk));
}
});

readable.pipeThrough(transform).pipeTo(writable);
3 changes: 3 additions & 0 deletions examples/webstreams-transform/worker.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export default async function (num) {
return 'ABC'.repeat(num * num);
}
31 changes: 31 additions & 0 deletions examples/webstreams/index.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import Piscina from 'piscina';
import {
ReadableStream,
WritableStream
} from 'node:stream/web';

const pool = new Piscina({
filename: new URL('./worker.mjs', import.meta.url).href
});

const readable = new ReadableStream({
start () {
this.chunks = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0];
},

pull (controller) {
const chunk = this.chunks.shift();
controller.enqueue(chunk);
if (this.chunks.length === 0) {
controller.close();
}
}
});

const writable = new WritableStream({
write (chunk) {
console.log(chunk);
}
});

await pool.run({ readable, writable }, { transferList: [readable, writable] });
7 changes: 7 additions & 0 deletions examples/webstreams/worker.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
export default async function ({ readable, writable }) {
const writer = writable.getWriter();
for await (const chunk of readable) {
await writer.write(chunk);
}
writer.close();
}

0 comments on commit 7311996

Please sign in to comment.