0
0
Fork 0
mirror of https://github.com/denoland/deno.git synced 2024-10-31 09:14:20 -04:00
denoland-deno/docs/runtime/workers.md
Luca Casonato 45f9b32ef0
Docs for deno test + minor other changes (#5185)
* Added fs events example.
* Added docs for `deno test`.
* Renamed file server example.
* Unified markdown code types.
* Removed plugin topics from TOC.
* Fixed links.
2020-05-10 03:09:42 +02:00

1.4 KiB

Workers

Deno supports Web Worker API.

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 type: "module" option when creating new worker:

// Good
new Worker("./worker.js", { type: "module" });

// Bad
new Worker("./worker.js");
new Worker("./worker.js", { type: "classic" });

Using Deno in worker

This is an unstable Deno feature. Learn more about unstable features.

By default Deno namespace is not available in worker scope.

To add Deno namespace pass deno: true option when creating new worker:

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

// worker.js
self.onmessage = async (e) => {
  const { filename } = e.data;
  const text = await Deno.readTextFile(filename);
  console.log(text);
  self.close();
};

// log.txt
hello world
$ deno run --allow-read --unstable main.js
hello world

When Deno namespace is available in worker scope; the worker inherits parent process permissions (the ones specified using --allow-* flags).

We intend to make permissions configurable for workers.