Skip to main content
Deno 2 is finally here 🎉️
Learn more

workerio

deno land deno doc Test codecov

Deno module to translate Worker’s system of messages into ReadableStream<Uint8Array> and WritableStream<Uint8Array> or Deno.Reader and Deno.Writer.

Example

ReadableStream/WritableStream

Server

import {
  readableStreamFromWorker,
  writableStreamFromWorker,
} from "https://deno.land/x/workerio@v3.1.1/mod.ts";

const decoder = new TextDecoder();
const encoder = new TextEncoder();

const worker = new Worker(new URL("./worker.ts", import.meta.url).href, {
  type: "module",
});

const reader = readableStreamFromWorker(worker);
const writer = writableStreamFromWorker(worker);
const w = writer.getWriter();

await w.write(encoder.encode("Hello"));
await w.write(encoder.encode("World"));
w.releaseLock();

for await (const data of reader) {
  const text = decoder.decode(data);
  console.log(text);
}

Worker

import {
  readableStreamFromWorker,
  writableStreamFromWorker,
} from "https://deno.land/x/workerio@v3.1.1/mod.ts";

const decoder = new TextDecoder();
const encoder = new TextEncoder();

async function main(): Promise<void> {
  const worker = self as unknown as Worker;
  const reader = readableStreamFromWorker(worker);
  const writer = writableStreamFromWorker(worker);
  const w = writer.getWriter();

  for await (const data of reader) {
    const text = decoder.decode(data);
    await w.write(encoder.encode(`!!! ${text} !!!`));
  }
  w.releaseLock();
}

main().catch((e) => console.error(e));

Deno.Reader/Deno.Writer

Server

import {
  WorkerReader,
  WorkerWriter,
} from "https://deno.land/x/workerio@v3.1.1/mod.ts";

const decoder = new TextDecoder();
const encoder = new TextEncoder();

const worker = new Worker(new URL("./worker.ts", import.meta.url).href, {
  type: "module",
});

const reader = new WorkerReader(worker);
const writer = new WorkerWriter(worker);

await writer.write(encoder.encode("Hello"));
await writer.write(encoder.encode("World"));

for await (const data of Deno.iter(reader)) {
  const text = decoder.decode(data);
  console.log(text);
}

Worker

import {
  WorkerReader,
  WorkerWriter,
} from "https://deno.land/x/workerio@v3.1.1/mod.ts";

const decoder = new TextDecoder();
const encoder = new TextEncoder();

async function main(): Promise<void> {
  const worker = self as unknown as Worker;
  const reader = new WorkerReader(worker);
  const writer = new WorkerWriter(worker);

  for await (const data of Deno.iter(reader)) {
    const text = decoder.decode(data);
    await writer.write(encoder.encode(`!!! ${text} !!!`));
  }
}

main().catch((e) => console.error(e));

License

The code follows MIT license written in LICENSE. Contributors need to agree that any modifications sent in this repository follow the license.