Web Workers 和 node:worker_threads


🌐 Web Workers and node:worker_threads

每个 Web Worker 都由一个 node:worker_threads <Worker> 支持,因此这两个 API 共享它们的线程、结构化克隆和传输语义。在 worker 内部,[worker_threads.parentPort][] 是 self.postMessage() 和 worker 的 message 事件背后的端口,isMainThread 是 false,而 workerData 是 undefined。

🌐 Every Web Worker is backed by a node:worker_threads <Worker>, so the two APIs share their threading, structured clone, and transfer semantics. Inside a worker, [worker_threads.parentPort][] is the port behind self.postMessage() and the worker's message events, isMainThread is false, and workerData is undefined.

Web Workers,就像 node:worker_threads workers 一样,默认情况下会保持事件循环活跃。在 Node.js 中,Web Workers 实现了 可引用协议,并且可以使用 process.ref(worker) 和 process.unref(worker) 来引用或取消引用。

🌐 Web Workers, like node:worker_threads workers, keep the event loop alive by default. In Node.js, Web Workers implement the Refable protocol, and can be ref'd and unref'd using process.ref(worker) and process.unref(worker).

一般来说,当程序需要 workerData、自定义的 env 或 execArgv、资源限制、stdio 重定向、'online' 和 'exit' 事件,或者 worker.threadId 时,直接使用 node:worker_threads;Worker 仅接受 name、type 和 credentials 选项,并且根据规范,它的 terminate() 返回 undefined,而不是 promise。通过 node:worker_threads 启动的线程是普通的 Node.js 线程,不会获得 worker 全局作用域的 API。

🌐 As a rule of thumb, use node:worker_threads directly when a program needs workerData, a custom env or execArgv, resource limits, stdio redirection, the 'online' and 'exit' events, or worker.threadId; Worker accepts only the name, type, and credentials options and, per the specification, its terminate() returns undefined, rather than a promise. Threads started through node:worker_threads are ordinary Node.js threads and do not get the worker global scope APIs.