Intermediate
cliweb
Web Workers
Workers are the only ways of running javascript off of the main thread. This can be useful for a wide variety of programs, especially those where there is a lot of computation that needs to be done without blocking a thread.
Currently, Deno only supports module-type workers. To instantiate one we can use similar syntax to what is found on the web.
./main.ts
const worker = new Worker(
new URL("./worker.ts", import.meta.url).href,
{
type: "module",
},
);
We can send a message to the worker by using the `postMessage` method
./main.ts
worker.postMessage({ filename: "./log.txt" });
It is also possible to only give workers certain permissions This can be done through the deno.permissions option. By default the worker inherits the permissions of the thread it was instantiated from.
./main.ts
const worker2 = new Worker(
new URL("./worker.ts", import.meta.url).href,
{
type: "module",
deno: {
permissions: {
read: [
new URL("./file_1.txt", import.meta.url),
new URL("./file_2.txt", import.meta.url),
],
},
},
},
);
This will error since the worker does not have permission to access the file
./main.ts
worker2.postMessage({ filename: "./log.txt" });
On the web worker side, we can receive the message and do some processing
./worker.ts
self.onmessage = async (e) => {
const { filename } = e.data;
const text = await Deno.readTextFile(filename);
console.log(text);
self.close();
};
Run this example locally using the Deno CLI:
deno run https://byexample-2qr8vk52swn0.deno.dev/web-workers.ts
Additional resources: