worker.workerData


任意的 JavaScript 值,其中包含传给该线程的 Worker 构造函数的数据的克隆。

根据 HTML 结构化克隆算法,数据如同使用 postMessage() 一样被克隆。

const { Worker, isMainThread, workerData } = require('node:worker_threads');

if (isMainThread) {
  const worker = new Worker(__filename, { workerData: 'Hello, world!' });
} else {
  console.log(workerData);  // 打印 'Hello, world!'。
}

An arbitrary JavaScript value that contains a clone of the data passed to this thread's Worker constructor.

The data is cloned as if using postMessage(), according to the HTML structured clone algorithm.

const { Worker, isMainThread, workerData } = require('node:worker_threads');

if (isMainThread) {
  const worker = new Worker(__filename, { workerData: 'Hello, world!' });
} else {
  console.log(workerData);  // Prints 'Hello, world!'.
}