Bunadvanced
export const countPrimesOnWorker = (from: number, to: number) => {
const workerCode = `
self.onmessage = ({ data: [from, to] }) => {
let count = 0;
for (let n = from; n < to; n++) {
Bun's Worker API uses real OS threads, so CPU-bound work can be split across workers created from an in-memory blob: URL, with no separate worker file needed.
Node.jsadvanced
import { fork } from "node:child_process";
import { cpus } from "node:os";
import { once } from "node:events";
import { fileURLToPath } from "node:url";
Fork one child process per CPU core, split a CPU-bound range across them, and aggregate results over IPC — using one self-contained file.
Web Platformadvanced
export const getFreshAuthToken = () =>
navigator.locks.request("auth-token-refresh", async () => {
const expiresAt = Number(localStorage.getItem("auth-token-expires-at") ?? 0);
if (Date.now() < expiresAt) return localStorage.getItem("auth-token")!;
Stop every open tab from refreshing the same auth token at once — let one tab do the network call while the rest wait and reuse its result.
Node.jsadvanced
import { Worker, isMainThread, parentPort, workerData } from "node:worker_threads";
const fibonacci = (n: number): number => (n < 2 ? n : fibonacci(n - 1) + fibonacci(n - 2));
if (isMainThread) {
Offload a genuinely CPU-heavy computation to a worker_threads Worker so it stops blocking the event loop, using one self-contained file.