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:

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

    worker.ts

    1. console.log("hello world");
    2. self.close();

    For workers using remote modules; permission is required:

    main.ts

    1. new Worker("https://example.com/worker.ts", { type: "module" });

    worker.ts (at https://example.com/worker.ts)

    1. self.close();

    Using Deno in worker

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

    main.js

    1. const worker = new Worker(new URL("worker.js", import.meta.url).href, {
    2. type: "module",
    3. deno: true,
    4. });

    worker.js

    1. const { filename } = e.data;
    2. const text = await Deno.readTextFile(filename);
    3. console.log(text);
    4. self.close();
    5. };

    log.txt

    1. $ 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).