brundolf
brundolf

Reputation: 1500

Deno: "Classic workers are not supported"?

I wanted to create a Web Worker like so:

const blob = URL.createObjectURL(new Blob([`
  ...
`], {type: 'text/javascript'}))
const worker = new Worker(blob)

But when doing so in Deno I get:

error: Uncaught NotSupported: Classic workers are not supported.
    const worker = new Worker(blob)
                   ^

I've googled this message "Classic workers are not supported" and I've found basically nothing explaining the history behind it or what specifically it means. I've found a little bit about a special Deno way of creating workers:

const worker = new Worker(new URL("worker.js", import.meta.url).href, {
  type: "module",
  deno: true,
});
worker.postMessage({ filename: "./log.txt" });

but it doesn't appear to serve my needs because I specifically need to initialize a worker dynamically from a string (or at least from an arbitrary function passed at runtime).

Is there any way to do what I need to do in Deno?

Edit: I did manage to find this page in the docs (Deno's docs have trouble turning up results in search engines, for some reason), though it doesn't bode well because it sounds like there's no way to do what I'm needing to do https://deno.land/manual/runtime/web_platform_apis#web-worker-api

Upvotes: 3

Views: 1034

Answers (2)

jsejcksn
jsejcksn

Reputation: 33796

The information provided in mfulton26's answer is right, but you don't need a data URL: you simply need to add { type: "module" } to your worker instantiation options. Deno even supports TypeScript as the source for your worker:

blob-worker.ts:

const workerModuleSource = `
const version: string = Deno.version.deno;
console.log(\`Hello from Deno v\${version}\`);
self.close();
`;

const blob = new Blob(
  [workerModuleSource],
  {type: 'application/typescript'},
);

const objUrl = URL.createObjectURL(blob);

const worker = new Worker(objUrl, {
  deno: true,
  type: 'module',
});

URL.revokeObjectURL(objUrl);
$ deno run --unstable blob-worker.ts
Hello from Deno v1.14.1

Upvotes: 1

mfulton26
mfulton26

Reputation: 31254

Deno does not currently support "classic" workers.

  1. From Worker() - Web APIs | MDN:

    type: A DOMString specifying the type of worker to create. The value can be classic or module. If not specified, the default used is classic.

  2. From Workers | Manual | Deno:

    Currently Deno supports only module type workers; thus it's essential to pass the type: "module" option when creating a new worker.

For your use case you might be able to use a data URL. e.g.:

new Worker(
  `data:text/javascript;base64,${btoa(
    `console.log("hello world"); self.close();`
  )}`,
  { type: "module" }
);

Upvotes: 5

Related Questions