Workers can be used to run code on multiple threads. Each instance of Worker
is run on a separate thread, dedicated only to that worker.
Currently Deno supports only module
type workers; thus it’s essential to pass the type: "module"
option when creating a new worker.
Relative module specifiers are at the moment. You can instead use the URL
contructor and import.meta.url
to easily create a specifier for some nearby script.
Creating a new Worker
instance is similar to a dynamic import; therefore Deno requires appropriate permission for this action.
For workers using local modules; --allow-read
permission is required:
new Worker(new URL("worker.ts", import.meta.url).href, { type: "module" });
worker.ts
console.log("hello world");
self.close();
For workers using remote modules; permission is required:
main.ts
new Worker("https://example.com/worker.ts", { type: "module" });
worker.ts (at https://example.com/worker.ts)
self.close();
Using Deno in worker
To add the Deno
namespace pass deno: true
option when creating new worker:
main.js
const worker = new Worker(new URL("worker.js", import.meta.url).href, {
type: "module",
deno: true,
});
worker.js
const { filename } = e.data;
const text = await Deno.readTextFile(filename);
console.log(text);
self.close();
};
log.txt
$ deno run --allow-read --unstable main.js
When the Deno
namespace is available in worker scope, the worker inherits its parent process’ permissions (the ones specified using --allow-*
flags).