coty
coty3w ago

How to detect if executing on main thread vs worker

function main() {
// create worker from this same file
const worker = new Worker(import.meta.resolve("./mod.ts"), {
name: "hello-worker",
type: "module",
});
worker.onmessage = (e: MessageEvent<{ message: string }>) => {
console.log(e.data.message);
};
worker.postMessage({
message: "hello",
});
}

if (import.meta.main) {
if (self.window) {
main();
} else {
const worker = self as unknown as Worker & { name?: string };
worker.onmessage = (e: MessageEvent<{ message: string }>) => {
worker.postMessage({
message: `${e.data.message} from ${worker.name}`,
});
self.close();
};
}
}
function main() {
// create worker from this same file
const worker = new Worker(import.meta.resolve("./mod.ts"), {
name: "hello-worker",
type: "module",
});
worker.onmessage = (e: MessageEvent<{ message: string }>) => {
console.log(e.data.message);
};
worker.postMessage({
message: "hello",
});
}

if (import.meta.main) {
if (self.window) {
main();
} else {
const worker = self as unknown as Worker & { name?: string };
worker.onmessage = (e: MessageEvent<{ message: string }>) => {
worker.postMessage({
message: `${e.data.message} from ${worker.name}`,
});
self.close();
};
}
}
I put everything in one file to make it easier to show, but is checking for self.window the preferred way? or is there some value in Deno context? Bonus question, how can you properly type self when in a worker? That type casting is neither pretty nor accurate
3 Replies
Deno AI Helper
I wasn't able to find the answer to your question in the official Deno documentation. However, based on the code snippet you've provided, I can offer some general advice. In the context of web workers, checking for self.window is a common way to determine if the current context is the main thread or a worker thread, as window is typically only defined in the main thread. However, this is more of a web platform convention rather than something specific to Deno. Regarding your bonus question about typing self in a worker, the type casting you've used (self as unknown as Worker & { name?: string }) is indeed not the most elegant solution. A more accurate typing might involve using the Deno.Worker type or creating a more specific interface that extends the Worker interface with the properties you expect to be present on self within the worker context. Please note that this advice is not based on the Deno documentation, and I would advise you to double-check the accuracy of this advice. It's always a good idea to consult the latest Deno documentation or the community for the most current best practices.
Leokuma
Leokuma3w ago
To type check a worker, add these lines at the top:
/// <reference no-default-lib="true" />
/// <reference lib="deno.worker" />
/// <reference no-default-lib="true" />
/// <reference lib="deno.worker" />
Source: https://docs.deno.com/runtime/manual/advanced/typescript/types#type-checking-web-workers
coty
coty3w ago
Thank you, the helps a ton