{"$schema":"https://doc-kit.nodejs.org/schemas/api-doc/1.0.0.json","id":"worker_threads","path":"/worker_threads","type":"module","module":"worker_threads","title":"Worker threads","introducedIn":"v10.5.0","sourceLink":{"path":"lib/worker_threads.js","url":"https://github.com/nodejs/node/blob/HEAD/lib/worker_threads.js"},"stability":{"index":"2","description":"Stable"},"added":["v10.5.0"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[{"versions":["v12.11.0"],"prUrl":"https://github.com/nodejs/node/pull/29512","commit":null,"description":"This API is no longer experimental."},{"versions":["v11.7.0"],"prUrl":"https://github.com/nodejs/node/pull/25361","commit":null,"description":"This API is no longer behind the `--experimental-worker` CLI flag."}],"description":"The `node:worker_threads` module enables the use of threads that execute\nJavaScript in parallel. To access it:\n\n```mjs\nimport worker_threads from 'node:worker_threads';\n```\n\n```cjs\nconst worker_threads = require('node:worker_threads');\n```\n\nWorkers (threads) are useful for performing CPU-intensive JavaScript operations.\nThey do not help much with I/O-intensive work. The Node.js built-in\nasynchronous I/O operations are more efficient than Workers can be.\n\nUnlike `child_process` or `cluster`, `worker_threads` can share memory. They do\nso by transferring `ArrayBuffer` instances or sharing `SharedArrayBuffer`\ninstances.\n\n```mjs\nimport {\n  Worker,\n  isMainThread,\n  parentPort,\n  workerData,\n} from 'node:worker_threads';\n\nif (!isMainThread) {\n  const { parse } = await import('some-js-parsing-library');\n  const script = workerData;\n  parentPort.postMessage(parse(script));\n}\n\nexport default function parseJSAsync(script) {\n  return new Promise((resolve, reject) => {\n    const worker = new Worker(new URL(import.meta.url), {\n      workerData: script,\n    });\n    worker.on('message', resolve);\n    worker.once('error', reject);\n    worker.once('exit', (code) => {\n      if (code !== 0)\n        reject(new Error(`Worker stopped with exit code ${code}`));\n    });\n  });\n};\n```\n\n```cjs\nconst {\n  Worker,\n  isMainThread,\n  parentPort,\n  workerData,\n} = require('node:worker_threads');\n\nif (isMainThread) {\n  module.exports = function parseJSAsync(script) {\n    return new Promise((resolve, reject) => {\n      const worker = new Worker(__filename, {\n        workerData: script,\n      });\n      worker.on('message', resolve);\n      worker.once('error', reject);\n      worker.once('exit', (code) => {\n        if (code !== 0)\n          reject(new Error(`Worker stopped with exit code ${code}`));\n      });\n    });\n  };\n} else {\n  const { parse } = require('some-js-parsing-library');\n  const script = workerData;\n  parentPort.postMessage(parse(script));\n}\n```\n\nThe above example spawns a Worker thread for each `parseJSAsync()` call. In\npractice, use a pool of Workers for these kinds of tasks. Otherwise, the\noverhead of creating Workers would likely exceed their benefit.\n\nWhen implementing a worker pool, use the [`AsyncResource`](async_hooks.html#class-asyncresource) API to inform\ndiagnostic tools (e.g. to provide asynchronous stack traces) about the\ncorrelation between tasks and their outcomes. See\n[\"Using `AsyncResource` for a `Worker` thread pool\"](async_context.html#using-asyncresource-for-a-worker-thread-pool)\nin the `async_hooks` documentation for an example implementation.\n\nWorker threads inherit non-process-specific options by default. Refer to\n[`Worker constructor options`](#new-workerfilename-options) to know how to customize worker thread options,\nspecifically `argv` and `execArgv` options.","summary":"The `node:worker_threads` module enables the use of threads that execute JavaScript in parallel. To access it:","examples":[{"language":"mjs","displayName":null,"code":"import worker_threads from 'node:worker_threads';"},{"language":"cjs","displayName":null,"code":"const worker_threads = require('node:worker_threads');"},{"language":"mjs","displayName":null,"code":"import {\n  Worker,\n  isMainThread,\n  parentPort,\n  workerData,\n} from 'node:worker_threads';\n\nif (!isMainThread) {\n  const { parse } = await import('some-js-parsing-library');\n  const script = workerData;\n  parentPort.postMessage(parse(script));\n}\n\nexport default function parseJSAsync(script) {\n  return new Promise((resolve, reject) => {\n    const worker = new Worker(new URL(import.meta.url), {\n      workerData: script,\n    });\n    worker.on('message', resolve);\n    worker.once('error', reject);\n    worker.once('exit', (code) => {\n      if (code !== 0)\n        reject(new Error(`Worker stopped with exit code ${code}`));\n    });\n  });\n};"},{"language":"cjs","displayName":null,"code":"const {\n  Worker,\n  isMainThread,\n  parentPort,\n  workerData,\n} = require('node:worker_threads');\n\nif (isMainThread) {\n  module.exports = function parseJSAsync(script) {\n    return new Promise((resolve, reject) => {\n      const worker = new Worker(__filename, {\n        workerData: script,\n      });\n      worker.on('message', resolve);\n      worker.once('error', reject);\n      worker.once('exit', (code) => {\n        if (code !== 0)\n          reject(new Error(`Worker stopped with exit code ${code}`));\n      });\n    });\n  };\n} else {\n  const { parse } = require('some-js-parsing-library');\n  const script = workerData;\n  parentPort.postMessage(parse(script));\n}"}],"children":[{"kind":"method","id":"worker_threadsgetenvironmentdatakey","name":"getEnvironmentData","title":"`worker_threads.getEnvironmentData(key)`","scope":"module","overloadOf":null,"stability":null,"added":["v15.12.0","v14.18.0"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[{"versions":["v17.5.0","v16.15.0"],"prUrl":"https://github.com/nodejs/node/pull/41272","commit":null,"description":"No longer experimental."}],"signature":{"parameters":[{"name":"key","type":{"text":"any","links":[{"name":"any","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types","start":0,"end":3}]},"description":"Any arbitrary, cloneable JavaScript value that can be used as a\n{Map} key.","default":null,"optional":false,"rest":false,"properties":[]}],"returns":{"type":{"text":"any","links":[{"name":"any","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types","start":0,"end":3}]},"description":""}},"description":"Within a worker thread, `worker.getEnvironmentData()` returns a clone\nof data passed to the spawning thread's `worker.setEnvironmentData()`.\nEvery new `Worker` receives its own copy of the environment data\nautomatically.\n\n```mjs\nimport {\n  Worker,\n  isMainThread,\n  setEnvironmentData,\n  getEnvironmentData,\n} from 'node:worker_threads';\n\nif (isMainThread) {\n  setEnvironmentData('Hello', 'World!');\n  const worker = new Worker(new URL(import.meta.url));\n} else {\n  console.log(getEnvironmentData('Hello'));  // Prints 'World!'.\n}\n```\n\n```cjs\nconst {\n  Worker,\n  isMainThread,\n  setEnvironmentData,\n  getEnvironmentData,\n} = require('node:worker_threads');\n\nif (isMainThread) {\n  setEnvironmentData('Hello', 'World!');\n  const worker = new Worker(__filename);\n} else {\n  console.log(getEnvironmentData('Hello'));  // Prints 'World!'.\n}\n```","summary":"Within a worker thread, `worker.getEnvironmentData()` returns a clone of data passed to the spawning thread's `worker.setEnvironmentData()`. Every new `Worker` receives its own copy of the environment data automatically.","examples":[{"language":"mjs","displayName":null,"code":"import {\n  Worker,\n  isMainThread,\n  setEnvironmentData,\n  getEnvironmentData,\n} from 'node:worker_threads';\n\nif (isMainThread) {\n  setEnvironmentData('Hello', 'World!');\n  const worker = new Worker(new URL(import.meta.url));\n} else {\n  console.log(getEnvironmentData('Hello'));  // Prints 'World!'.\n}"},{"language":"cjs","displayName":null,"code":"const {\n  Worker,\n  isMainThread,\n  setEnvironmentData,\n  getEnvironmentData,\n} = require('node:worker_threads');\n\nif (isMainThread) {\n  setEnvironmentData('Hello', 'World!');\n  const worker = new Worker(__filename);\n} else {\n  console.log(getEnvironmentData('Hello'));  // Prints 'World!'.\n}"}],"children":[]},{"kind":"property","id":"worker_threadsisinternalthread","name":"isInternalThread","title":"`worker_threads.isInternalThread`","scope":"module","overloadOf":null,"stability":null,"added":["v23.7.0","v22.14.0"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"type":{"text":"boolean","links":[{"name":"boolean","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#boolean_type","start":0,"end":7}]},"default":null,"description":"Is `true` if this code is running inside of an internal [`Worker`](#class-worker) thread (e.g the loader thread).\n\n```bash\nnode --experimental-loader ./loader.js main.js\n```\n\n```mjs\n// loader.js\nimport { isInternalThread } from 'node:worker_threads';\nconsole.log(isInternalThread);  // true\n```\n\n```cjs\n// loader.js\nconst { isInternalThread } = require('node:worker_threads');\nconsole.log(isInternalThread);  // true\n```\n\n```mjs\n// main.js\nimport { isInternalThread } from 'node:worker_threads';\nconsole.log(isInternalThread);  // false\n```\n\n```cjs\n// main.js\nconst { isInternalThread } = require('node:worker_threads');\nconsole.log(isInternalThread);  // false\n```","summary":"Is `true` if this code is running inside of an internal `Worker` thread (e.g the loader thread).","examples":[{"language":"bash","displayName":null,"code":"node --experimental-loader ./loader.js main.js"},{"language":"mjs","displayName":null,"code":"// loader.js\nimport { isInternalThread } from 'node:worker_threads';\nconsole.log(isInternalThread);  // true"},{"language":"cjs","displayName":null,"code":"// loader.js\nconst { isInternalThread } = require('node:worker_threads');\nconsole.log(isInternalThread);  // true"},{"language":"mjs","displayName":null,"code":"// main.js\nimport { isInternalThread } from 'node:worker_threads';\nconsole.log(isInternalThread);  // false"},{"language":"cjs","displayName":null,"code":"// main.js\nconst { isInternalThread } = require('node:worker_threads');\nconsole.log(isInternalThread);  // false"}],"children":[]},{"kind":"property","id":"worker_threadsismainthread","name":"isMainThread","title":"`worker_threads.isMainThread`","scope":"module","overloadOf":null,"stability":null,"added":["v10.5.0"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"type":{"text":"boolean","links":[{"name":"boolean","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#boolean_type","start":0,"end":7}]},"default":null,"description":"Is `true` if this code is not running inside of a [`Worker`](#class-worker) thread.\n\n```mjs\nimport { Worker, isMainThread } from 'node:worker_threads';\n\nif (isMainThread) {\n  // This re-loads the current file inside a Worker instance.\n  new Worker(new URL(import.meta.url));\n} else {\n  console.log('Inside Worker!');\n  console.log(isMainThread);  // Prints 'false'.\n}\n```\n\n```cjs\nconst { Worker, isMainThread } = require('node:worker_threads');\n\nif (isMainThread) {\n  // This re-loads the current file inside a Worker instance.\n  new Worker(__filename);\n} else {\n  console.log('Inside Worker!');\n  console.log(isMainThread);  // Prints 'false'.\n}\n```","summary":"Is `true` if this code is not running inside of a `Worker` thread.","examples":[{"language":"mjs","displayName":null,"code":"import { Worker, isMainThread } from 'node:worker_threads';\n\nif (isMainThread) {\n  // This re-loads the current file inside a Worker instance.\n  new Worker(new URL(import.meta.url));\n} else {\n  console.log('Inside Worker!');\n  console.log(isMainThread);  // Prints 'false'.\n}"},{"language":"cjs","displayName":null,"code":"const { Worker, isMainThread } = require('node:worker_threads');\n\nif (isMainThread) {\n  // This re-loads the current file inside a Worker instance.\n  new Worker(__filename);\n} else {\n  console.log('Inside Worker!');\n  console.log(isMainThread);  // Prints 'false'.\n}"}],"children":[]},{"kind":"method","id":"worker_threadsmarkasuntransferableobject","name":"markAsUntransferable","title":"`worker_threads.markAsUntransferable(object)`","scope":"module","overloadOf":null,"stability":null,"added":["v14.5.0","v12.19.0"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"signature":{"parameters":[{"name":"object","type":{"text":"any","links":[{"name":"any","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types","start":0,"end":3}]},"description":"Any arbitrary JavaScript value.","default":null,"optional":false,"rest":false,"properties":[]}],"returns":null},"description":"Mark an object as not transferable. If `object` occurs in the transfer list of\na [`port.postMessage()`](#portpostmessagevalue-transferlist) call, an error is thrown. This is a no-op if\n`object` is a primitive value.\n\nIn particular, this makes sense for objects that can be cloned, rather than\ntransferred, and which are used by other objects on the sending side.\nFor example, Node.js marks the `ArrayBuffer`s it uses for its\n[`Buffer` pool](buffer.html#static-method-bufferallocunsafesize-alignment) with this.\n`ArrayBuffer.prototype.transfer()` is disallowed on such array buffer\ninstances.\n\nThis operation cannot be undone.\n\n```mjs\nimport { MessageChannel, markAsUntransferable } from 'node:worker_threads';\n\nconst pooledBuffer = new ArrayBuffer(8);\nconst typedArray1 = new Uint8Array(pooledBuffer);\nconst typedArray2 = new Float64Array(pooledBuffer);\n\nmarkAsUntransferable(pooledBuffer);\n\nconst { port1 } = new MessageChannel();\ntry {\n  // This will throw an error, because pooledBuffer is not transferable.\n  port1.postMessage(typedArray1, [ typedArray1.buffer ]);\n} catch (error) {\n  // error.name === 'DataCloneError'\n}\n\n// The following line prints the contents of typedArray1 -- it still owns\n// its memory and has not been transferred. Without\n// `markAsUntransferable()`, this would print an empty Uint8Array and the\n// postMessage call would have succeeded.\n// typedArray2 is intact as well.\nconsole.log(typedArray1);\nconsole.log(typedArray2);\n```\n\n```cjs\nconst { MessageChannel, markAsUntransferable } = require('node:worker_threads');\n\nconst pooledBuffer = new ArrayBuffer(8);\nconst typedArray1 = new Uint8Array(pooledBuffer);\nconst typedArray2 = new Float64Array(pooledBuffer);\n\nmarkAsUntransferable(pooledBuffer);\n\nconst { port1 } = new MessageChannel();\ntry {\n  // This will throw an error, because pooledBuffer is not transferable.\n  port1.postMessage(typedArray1, [ typedArray1.buffer ]);\n} catch (error) {\n  // error.name === 'DataCloneError'\n}\n\n// The following line prints the contents of typedArray1 -- it still owns\n// its memory and has not been transferred. Without\n// `markAsUntransferable()`, this would print an empty Uint8Array and the\n// postMessage call would have succeeded.\n// typedArray2 is intact as well.\nconsole.log(typedArray1);\nconsole.log(typedArray2);\n```\n\nThere is no equivalent to this API in browsers.","summary":"Mark an object as not transferable. If `object` occurs in the transfer list of a `port.postMessage()` call, an error is thrown. This is a no-op if `object` is a primitive value.","examples":[{"language":"mjs","displayName":null,"code":"import { MessageChannel, markAsUntransferable } from 'node:worker_threads';\n\nconst pooledBuffer = new ArrayBuffer(8);\nconst typedArray1 = new Uint8Array(pooledBuffer);\nconst typedArray2 = new Float64Array(pooledBuffer);\n\nmarkAsUntransferable(pooledBuffer);\n\nconst { port1 } = new MessageChannel();\ntry {\n  // This will throw an error, because pooledBuffer is not transferable.\n  port1.postMessage(typedArray1, [ typedArray1.buffer ]);\n} catch (error) {\n  // error.name === 'DataCloneError'\n}\n\n// The following line prints the contents of typedArray1 -- it still owns\n// its memory and has not been transferred. Without\n// `markAsUntransferable()`, this would print an empty Uint8Array and the\n// postMessage call would have succeeded.\n// typedArray2 is intact as well.\nconsole.log(typedArray1);\nconsole.log(typedArray2);"},{"language":"cjs","displayName":null,"code":"const { MessageChannel, markAsUntransferable } = require('node:worker_threads');\n\nconst pooledBuffer = new ArrayBuffer(8);\nconst typedArray1 = new Uint8Array(pooledBuffer);\nconst typedArray2 = new Float64Array(pooledBuffer);\n\nmarkAsUntransferable(pooledBuffer);\n\nconst { port1 } = new MessageChannel();\ntry {\n  // This will throw an error, because pooledBuffer is not transferable.\n  port1.postMessage(typedArray1, [ typedArray1.buffer ]);\n} catch (error) {\n  // error.name === 'DataCloneError'\n}\n\n// The following line prints the contents of typedArray1 -- it still owns\n// its memory and has not been transferred. Without\n// `markAsUntransferable()`, this would print an empty Uint8Array and the\n// postMessage call would have succeeded.\n// typedArray2 is intact as well.\nconsole.log(typedArray1);\nconsole.log(typedArray2);"}],"children":[]},{"kind":"method","id":"worker_threadsismarkedasuntransferableobject","name":"isMarkedAsUntransferable","title":"`worker_threads.isMarkedAsUntransferable(object)`","scope":"module","overloadOf":null,"stability":null,"added":["v21.0.0"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"signature":{"parameters":[{"name":"object","type":{"text":"any","links":[{"name":"any","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types","start":0,"end":3}]},"description":"Any JavaScript value.","default":null,"optional":false,"rest":false,"properties":[]}],"returns":{"type":{"text":"boolean","links":[{"name":"boolean","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#boolean_type","start":0,"end":7}]},"description":""}},"description":"Check if an object is marked as not transferable with\n[`markAsUntransferable()`](#worker_threadsmarkasuntransferableobject).\n\n```mjs\nimport { markAsUntransferable, isMarkedAsUntransferable } from 'node:worker_threads';\n\nconst pooledBuffer = new ArrayBuffer(8);\nmarkAsUntransferable(pooledBuffer);\n\nisMarkedAsUntransferable(pooledBuffer);  // Returns true.\n```\n\n```cjs\nconst { markAsUntransferable, isMarkedAsUntransferable } = require('node:worker_threads');\n\nconst pooledBuffer = new ArrayBuffer(8);\nmarkAsUntransferable(pooledBuffer);\n\nisMarkedAsUntransferable(pooledBuffer);  // Returns true.\n```\n\nThere is no equivalent to this API in browsers.","summary":"Check if an object is marked as not transferable with `markAsUntransferable()`.","examples":[{"language":"mjs","displayName":null,"code":"import { markAsUntransferable, isMarkedAsUntransferable } from 'node:worker_threads';\n\nconst pooledBuffer = new ArrayBuffer(8);\nmarkAsUntransferable(pooledBuffer);\n\nisMarkedAsUntransferable(pooledBuffer);  // Returns true."},{"language":"cjs","displayName":null,"code":"const { markAsUntransferable, isMarkedAsUntransferable } = require('node:worker_threads');\n\nconst pooledBuffer = new ArrayBuffer(8);\nmarkAsUntransferable(pooledBuffer);\n\nisMarkedAsUntransferable(pooledBuffer);  // Returns true."}],"children":[]},{"kind":"method","id":"worker_threadsmarkasuncloneableobject","name":"markAsUncloneable","title":"`worker_threads.markAsUncloneable(object)`","scope":"module","overloadOf":null,"stability":null,"added":["v23.0.0","v22.10.0"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"signature":{"parameters":[{"name":"object","type":{"text":"any","links":[{"name":"any","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types","start":0,"end":3}]},"description":"Any arbitrary JavaScript value.","default":null,"optional":false,"rest":false,"properties":[]}],"returns":null},"description":"Mark an object as not cloneable. If `object` is used as [`message`](#event-message) in\na [`port.postMessage()`](#portpostmessagevalue-transferlist) call, an error is thrown. This is a no-op if `object` is a\nprimitive value.\n\nThis has no effect on `ArrayBuffer`, or any `Buffer` like objects.\n\nThis operation cannot be undone.\n\n```mjs\nimport { markAsUncloneable } from 'node:worker_threads';\n\nconst anyObject = { foo: 'bar' };\nmarkAsUncloneable(anyObject);\nconst { port1 } = new MessageChannel();\ntry {\n  // This will throw an error, because anyObject is not cloneable.\n  port1.postMessage(anyObject);\n} catch (error) {\n  // error.name === 'DataCloneError'\n}\n```\n\n```cjs\nconst { markAsUncloneable } = require('node:worker_threads');\n\nconst anyObject = { foo: 'bar' };\nmarkAsUncloneable(anyObject);\nconst { port1 } = new MessageChannel();\ntry {\n  // This will throw an error, because anyObject is not cloneable.\n  port1.postMessage(anyObject);\n} catch (error) {\n  // error.name === 'DataCloneError'\n}\n```\n\nThere is no equivalent to this API in browsers.","summary":"Mark an object as not cloneable. If `object` is used as `message` in a `port.postMessage()` call, an error is thrown. This is a no-op if `object` is a primitive value.","examples":[{"language":"mjs","displayName":null,"code":"import { markAsUncloneable } from 'node:worker_threads';\n\nconst anyObject = { foo: 'bar' };\nmarkAsUncloneable(anyObject);\nconst { port1 } = new MessageChannel();\ntry {\n  // This will throw an error, because anyObject is not cloneable.\n  port1.postMessage(anyObject);\n} catch (error) {\n  // error.name === 'DataCloneError'\n}"},{"language":"cjs","displayName":null,"code":"const { markAsUncloneable } = require('node:worker_threads');\n\nconst anyObject = { foo: 'bar' };\nmarkAsUncloneable(anyObject);\nconst { port1 } = new MessageChannel();\ntry {\n  // This will throw an error, because anyObject is not cloneable.\n  port1.postMessage(anyObject);\n} catch (error) {\n  // error.name === 'DataCloneError'\n}"}],"children":[]},{"kind":"method","id":"worker_threadsmovemessageporttocontextport-contextifiedsandbox","name":"moveMessagePortToContext","title":"`worker_threads.moveMessagePortToContext(port, contextifiedSandbox)`","scope":"module","overloadOf":null,"stability":null,"added":["v11.13.0"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"signature":{"parameters":[{"name":"port","type":{"text":"MessagePort","links":[{"name":"MessagePort","href":"worker_threads.html#class-messageport","start":0,"end":11}]},"description":"The message port to transfer.","default":null,"optional":false,"rest":false,"properties":[]},{"name":"contextifiedSandbox","type":{"text":"Object","links":[{"name":"Object","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object","start":0,"end":6}]},"description":"A [contextified](vm.html#what-does-it-mean-to-contextify-an-object) object as returned by the\n`vm.createContext()` method.","default":null,"optional":false,"rest":false,"properties":[]}],"returns":{"type":{"text":"MessagePort","links":[{"name":"MessagePort","href":"worker_threads.html#class-messageport","start":0,"end":11}]},"description":""}},"description":"Transfer a `MessagePort` to a different [`vm`](vm.html) Context. The original `port`\nobject is rendered unusable, and the returned `MessagePort` instance\ntakes its place.\n\nThe returned `MessagePort` is an object in the target context and\ninherits from its global `Object` class. Objects passed to the\n[`port.onmessage()`](https://developer.mozilla.org/en-US/docs/Web/API/MessagePort/message_event) listener are also created in the target context\nand inherit from its global `Object` class.\n\nHowever, the created `MessagePort` no longer inherits from\n{EventTarget}, and only [`port.onmessage()`](https://developer.mozilla.org/en-US/docs/Web/API/MessagePort/message_event) can be used to receive\nevents using it.","summary":"Transfer a `MessagePort` to a different `vm` Context. The original `port` object is rendered unusable, and the returned `MessagePort` instance takes its place.","examples":[],"children":[]},{"kind":"property","id":"worker_threadsparentport","name":"parentPort","title":"`worker_threads.parentPort`","scope":"module","overloadOf":null,"stability":null,"added":["v10.5.0"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"type":{"text":"null | MessagePort","links":[{"name":"null","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#null_type","start":0,"end":4},{"name":"MessagePort","href":"worker_threads.html#class-messageport","start":7,"end":18}]},"default":null,"description":"If this thread is a [`Worker`](#class-worker), this is a [`MessagePort`](#class-messageport)\nallowing communication with the parent thread. Messages sent using\n`parentPort.postMessage()` are available in the parent thread\nusing `worker.on('message')`, and messages sent from the parent thread\nusing `worker.postMessage()` are available in this thread using\n`parentPort.on('message')`.\n\n```mjs\nimport { Worker, isMainThread, parentPort } from 'node:worker_threads';\n\nif (isMainThread) {\n  const worker = new Worker(new URL(import.meta.url));\n  worker.once('message', (message) => {\n    console.log(message);  // Prints 'Hello, world!'.\n  });\n  worker.postMessage('Hello, world!');\n} else {\n  // When a message from the parent thread is received, send it back:\n  parentPort.once('message', (message) => {\n    parentPort.postMessage(message);\n  });\n}\n```\n\n```cjs\nconst { Worker, isMainThread, parentPort } = require('node:worker_threads');\n\nif (isMainThread) {\n  const worker = new Worker(__filename);\n  worker.once('message', (message) => {\n    console.log(message);  // Prints 'Hello, world!'.\n  });\n  worker.postMessage('Hello, world!');\n} else {\n  // When a message from the parent thread is received, send it back:\n  parentPort.once('message', (message) => {\n    parentPort.postMessage(message);\n  });\n}\n```","summary":"If this thread is a `Worker`, this is a `MessagePort` allowing communication with the parent thread. Messages sent using `parentPort.postMessage()` are available in the parent thread using `worker.on('message')`, and messages sent from the parent thread using `worker.postMessage()` are available in this thread using `parentPort.on('message')`.","examples":[{"language":"mjs","displayName":null,"code":"import { Worker, isMainThread, parentPort } from 'node:worker_threads';\n\nif (isMainThread) {\n  const worker = new Worker(new URL(import.meta.url));\n  worker.once('message', (message) => {\n    console.log(message);  // Prints 'Hello, world!'.\n  });\n  worker.postMessage('Hello, world!');\n} else {\n  // When a message from the parent thread is received, send it back:\n  parentPort.once('message', (message) => {\n    parentPort.postMessage(message);\n  });\n}"},{"language":"cjs","displayName":null,"code":"const { Worker, isMainThread, parentPort } = require('node:worker_threads');\n\nif (isMainThread) {\n  const worker = new Worker(__filename);\n  worker.once('message', (message) => {\n    console.log(message);  // Prints 'Hello, world!'.\n  });\n  worker.postMessage('Hello, world!');\n} else {\n  // When a message from the parent thread is received, send it back:\n  parentPort.once('message', (message) => {\n    parentPort.postMessage(message);\n  });\n}"}],"children":[]},{"kind":"method","id":"worker_threadspostmessagetothreadthreadid-value-transferlist-timeout","name":"postMessageToThread","title":"`worker_threads.postMessageToThread(threadId, value[, transferList][, timeout])`","scope":"module","overloadOf":null,"stability":{"index":"1.1","description":"Active development"},"added":["v22.5.0","v20.19.0"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"signature":{"parameters":[{"name":"threadId","type":{"text":"number","links":[{"name":"number","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#number_type","start":0,"end":6}]},"description":"The target thread ID. If the thread ID is invalid, a\n[`ERR_WORKER_MESSAGING_FAILED`](errors.html#err_worker_messaging_failed) error will be thrown. If the target thread ID is the current thread ID,\na [`ERR_WORKER_MESSAGING_SAME_THREAD`](errors.html#err_worker_messaging_same_thread) error will be thrown.","default":null,"optional":false,"rest":false,"properties":[]},{"name":"value","type":{"text":"any","links":[{"name":"any","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types","start":0,"end":3}]},"description":"The value to send.","default":null,"optional":false,"rest":false,"properties":[]},{"name":"transferList","type":{"text":"Object[]","links":[{"name":"Object","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object","start":0,"end":6}]},"description":"If one or more `MessagePort`-like objects are passed in `value`,\na `transferList` is required for those items or [`ERR_MISSING_MESSAGE_PORT_IN_TRANSFER_LIST`](errors.html#err_missing_message_port_in_transfer_list) is thrown.\nSee [`port.postMessage()`](#portpostmessagevalue-transferlist) for more information.","default":null,"optional":true,"rest":false,"properties":[]},{"name":"timeout","type":{"text":"number","links":[{"name":"number","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#number_type","start":0,"end":6}]},"description":"Time to wait for the message to be delivered in milliseconds.\nBy default it's `undefined`, which means wait forever. If the operation times out,\na [`ERR_WORKER_MESSAGING_TIMEOUT`](errors.html#err_worker_messaging_timeout) error is thrown.","default":null,"optional":true,"rest":false,"properties":[]}],"returns":{"type":{"text":"Promise","links":[{"name":"Promise","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise","start":0,"end":7}]},"description":"A promise which is fulfilled if the message was successfully processed by destination thread."}},"description":"Sends a value to another worker, identified by its thread ID.\n\nIf the target thread has no listener for the `workerMessage` event, then the operation will throw\na [`ERR_WORKER_MESSAGING_FAILED`](errors.html#err_worker_messaging_failed) error.\n\nIf the target thread threw an error while processing the `workerMessage` event, then the operation will throw\na [`ERR_WORKER_MESSAGING_ERRORED`](errors.html#err_worker_messaging_errored) error.\n\nThis method should be used when the target thread is not the direct\nparent or child of the current thread.\nIf the two threads are parent-children, use the [`require('node:worker_threads').parentPort.postMessage()`](#workerpostmessagevalue-transferlist)\nand the [`worker.postMessage()`](#workerpostmessagevalue-transferlist) to let the threads communicate.\n\nThe example below shows the use of `postMessageToThread`: it creates 10 nested threads,\nthe last one will try to communicate with the main thread.\n\n```mjs\nimport process from 'node:process';\nimport {\n  postMessageToThread,\n  threadId,\n  workerData,\n  Worker,\n} from 'node:worker_threads';\n\nconst channel = new BroadcastChannel('sync');\nconst level = workerData?.level ?? 0;\n\nif (level < 10) {\n  const worker = new Worker(new URL(import.meta.url), {\n    workerData: { level: level + 1 },\n  });\n}\n\nif (level === 0) {\n  process.on('workerMessage', (value, source) => {\n    console.log(`${source} -> ${threadId}:`, value);\n    postMessageToThread(source, { message: 'pong' });\n  });\n} else if (level === 10) {\n  process.on('workerMessage', (value, source) => {\n    console.log(`${source} -> ${threadId}:`, value);\n    channel.postMessage('done');\n    channel.close();\n  });\n\n  await postMessageToThread(0, { message: 'ping' });\n}\n\nchannel.onmessage = channel.close;\n```\n\n```cjs\nconst {\n  postMessageToThread,\n  threadId,\n  workerData,\n  Worker,\n} = require('node:worker_threads');\n\nconst channel = new BroadcastChannel('sync');\nconst level = workerData?.level ?? 0;\n\nif (level < 10) {\n  const worker = new Worker(__filename, {\n    workerData: { level: level + 1 },\n  });\n}\n\nif (level === 0) {\n  process.on('workerMessage', (value, source) => {\n    console.log(`${source} -> ${threadId}:`, value);\n    postMessageToThread(source, { message: 'pong' });\n  });\n} else if (level === 10) {\n  process.on('workerMessage', (value, source) => {\n    console.log(`${source} -> ${threadId}:`, value);\n    channel.postMessage('done');\n    channel.close();\n  });\n\n  postMessageToThread(0, { message: 'ping' });\n}\n\nchannel.onmessage = channel.close;\n```","summary":"Sends a value to another worker, identified by its thread ID.","examples":[{"language":"mjs","displayName":null,"code":"import process from 'node:process';\nimport {\n  postMessageToThread,\n  threadId,\n  workerData,\n  Worker,\n} from 'node:worker_threads';\n\nconst channel = new BroadcastChannel('sync');\nconst level = workerData?.level ?? 0;\n\nif (level < 10) {\n  const worker = new Worker(new URL(import.meta.url), {\n    workerData: { level: level + 1 },\n  });\n}\n\nif (level === 0) {\n  process.on('workerMessage', (value, source) => {\n    console.log(`${source} -> ${threadId}:`, value);\n    postMessageToThread(source, { message: 'pong' });\n  });\n} else if (level === 10) {\n  process.on('workerMessage', (value, source) => {\n    console.log(`${source} -> ${threadId}:`, value);\n    channel.postMessage('done');\n    channel.close();\n  });\n\n  await postMessageToThread(0, { message: 'ping' });\n}\n\nchannel.onmessage = channel.close;"},{"language":"cjs","displayName":null,"code":"const {\n  postMessageToThread,\n  threadId,\n  workerData,\n  Worker,\n} = require('node:worker_threads');\n\nconst channel = new BroadcastChannel('sync');\nconst level = workerData?.level ?? 0;\n\nif (level < 10) {\n  const worker = new Worker(__filename, {\n    workerData: { level: level + 1 },\n  });\n}\n\nif (level === 0) {\n  process.on('workerMessage', (value, source) => {\n    console.log(`${source} -> ${threadId}:`, value);\n    postMessageToThread(source, { message: 'pong' });\n  });\n} else if (level === 10) {\n  process.on('workerMessage', (value, source) => {\n    console.log(`${source} -> ${threadId}:`, value);\n    channel.postMessage('done');\n    channel.close();\n  });\n\n  postMessageToThread(0, { message: 'ping' });\n}\n\nchannel.onmessage = channel.close;"}],"children":[]},{"kind":"method","id":"worker_threadsreceivemessageonportport","name":"receiveMessageOnPort","title":"`worker_threads.receiveMessageOnPort(port)`","scope":"module","overloadOf":null,"stability":null,"added":["v12.3.0"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[{"versions":["v15.12.0"],"prUrl":"https://github.com/nodejs/node/pull/37535","commit":null,"description":"The port argument can also refer to a `BroadcastChannel` now."}],"signature":{"parameters":[{"name":"port","type":{"text":"MessagePort | BroadcastChannel","links":[{"name":"MessagePort","href":"worker_threads.html#class-messageport","start":0,"end":11},{"name":"BroadcastChannel","href":"worker_threads.html#class-broadcastchannel-extends-eventtarget","start":14,"end":30}]},"description":"","default":null,"optional":false,"rest":false,"properties":[]}],"returns":{"type":{"text":"Object | undefined","links":[{"name":"Object","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object","start":0,"end":6},{"name":"undefined","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#undefined_type","start":9,"end":18}]},"description":""}},"description":"Receive a single message from a given `MessagePort`. If no message is available,\n`undefined` is returned, otherwise an object with a single `message` property\nthat contains the message payload, corresponding to the oldest message in the\n`MessagePort`'s queue.\n\n```mjs\nimport { MessageChannel, receiveMessageOnPort } from 'node:worker_threads';\nconst { port1, port2 } = new MessageChannel();\nport1.postMessage({ hello: 'world' });\n\nconsole.log(receiveMessageOnPort(port2));\n// Prints: { message: { hello: 'world' } }\nconsole.log(receiveMessageOnPort(port2));\n// Prints: undefined\n```\n\n```cjs\nconst { MessageChannel, receiveMessageOnPort } = require('node:worker_threads');\nconst { port1, port2 } = new MessageChannel();\nport1.postMessage({ hello: 'world' });\n\nconsole.log(receiveMessageOnPort(port2));\n// Prints: { message: { hello: 'world' } }\nconsole.log(receiveMessageOnPort(port2));\n// Prints: undefined\n```\n\nWhen this function is used, no `'message'` event is emitted and the\n`onmessage` listener is not invoked.","summary":"Receive a single message from a given `MessagePort`. If no message is available, `undefined` is returned, otherwise an object with a single `message` property that contains the message payload, corresponding to the oldest message in the `MessagePort`'s queue.","examples":[{"language":"mjs","displayName":null,"code":"import { MessageChannel, receiveMessageOnPort } from 'node:worker_threads';\nconst { port1, port2 } = new MessageChannel();\nport1.postMessage({ hello: 'world' });\n\nconsole.log(receiveMessageOnPort(port2));\n// Prints: { message: { hello: 'world' } }\nconsole.log(receiveMessageOnPort(port2));\n// Prints: undefined"},{"language":"cjs","displayName":null,"code":"const { MessageChannel, receiveMessageOnPort } = require('node:worker_threads');\nconst { port1, port2 } = new MessageChannel();\nport1.postMessage({ hello: 'world' });\n\nconsole.log(receiveMessageOnPort(port2));\n// Prints: { message: { hello: 'world' } }\nconsole.log(receiveMessageOnPort(port2));\n// Prints: undefined"}],"children":[]},{"kind":"property","id":"worker_threadsresourcelimits","name":"resourceLimits","title":"`worker_threads.resourceLimits`","scope":"module","overloadOf":null,"stability":null,"added":["v13.2.0","v12.16.0"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"type":{"text":"Object","links":[{"name":"Object","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object","start":0,"end":6}]},"default":null,"description":"Provides the set of JS engine resource constraints inside this Worker thread.\nIf the `resourceLimits` option was passed to the [`Worker`](#class-worker) constructor,\nthis matches its values.\n\nIf this is used in the main thread, its value is an empty object.","summary":"Provides the set of JS engine resource constraints inside this Worker thread. If the `resourceLimits` option was passed to the `Worker` constructor, this matches its values.","examples":[],"children":[]},{"kind":"property","id":"worker_threadsshare_env","name":"SHARE_ENV","title":"`worker_threads.SHARE_ENV`","scope":"module","overloadOf":null,"stability":null,"added":["v11.14.0"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"type":{"text":"symbol","links":[{"name":"symbol","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#symbol_type","start":0,"end":6}]},"default":null,"description":"A special value that can be passed as the `env` option of the [`Worker`](#class-worker)\nconstructor, to indicate that the current thread and the Worker thread should\nshare read and write access to the same set of environment variables.\n\n```mjs\nimport process from 'node:process';\nimport { Worker, SHARE_ENV } from 'node:worker_threads';\nnew Worker('process.env.SET_IN_WORKER = \"foo\"', { eval: true, env: SHARE_ENV })\n  .once('exit', () => {\n    console.log(process.env.SET_IN_WORKER);  // Prints 'foo'.\n  });\n```\n\n```cjs\nconst { Worker, SHARE_ENV } = require('node:worker_threads');\nnew Worker('process.env.SET_IN_WORKER = \"foo\"', { eval: true, env: SHARE_ENV })\n  .once('exit', () => {\n    console.log(process.env.SET_IN_WORKER);  // Prints 'foo'.\n  });\n```","summary":"A special value that can be passed as the `env` option of the `Worker` constructor, to indicate that the current thread and the Worker thread should share read and write access to the same set of environment variables.","examples":[{"language":"mjs","displayName":null,"code":"import process from 'node:process';\nimport { Worker, SHARE_ENV } from 'node:worker_threads';\nnew Worker('process.env.SET_IN_WORKER = \"foo\"', { eval: true, env: SHARE_ENV })\n  .once('exit', () => {\n    console.log(process.env.SET_IN_WORKER);  // Prints 'foo'.\n  });"},{"language":"cjs","displayName":null,"code":"const { Worker, SHARE_ENV } = require('node:worker_threads');\nnew Worker('process.env.SET_IN_WORKER = \"foo\"', { eval: true, env: SHARE_ENV })\n  .once('exit', () => {\n    console.log(process.env.SET_IN_WORKER);  // Prints 'foo'.\n  });"}],"children":[]},{"kind":"method","id":"worker_threadssetenvironmentdatakey-value","name":"setEnvironmentData","title":"`worker_threads.setEnvironmentData(key[, value])`","scope":"module","overloadOf":null,"stability":null,"added":["v15.12.0","v14.18.0"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[{"versions":["v17.5.0","v16.15.0"],"prUrl":"https://github.com/nodejs/node/pull/41272","commit":null,"description":"No longer experimental."}],"signature":{"parameters":[{"name":"key","type":{"text":"any","links":[{"name":"any","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types","start":0,"end":3}]},"description":"Any arbitrary, cloneable JavaScript value that can be used as a\n{Map} key.","default":null,"optional":false,"rest":false,"properties":[]},{"name":"value","type":{"text":"any","links":[{"name":"any","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types","start":0,"end":3}]},"description":"Any arbitrary, cloneable JavaScript value that will be cloned\nand passed automatically to all new `Worker` instances. If `value` is passed\nas `undefined`, any previously set value for the `key` will be deleted.","default":null,"optional":true,"rest":false,"properties":[]}],"returns":null},"description":"The `worker.setEnvironmentData()` API sets the content of\n`worker.getEnvironmentData()` in the current thread and all new `Worker`\ninstances spawned from the current context.","summary":"The `worker.setEnvironmentData()` API sets the content of `worker.getEnvironmentData()` in the current thread and all new `Worker` instances spawned from the current context.","examples":[],"children":[]},{"kind":"property","id":"worker_threadsthreadid","name":"threadId","title":"`worker_threads.threadId`","scope":"module","overloadOf":null,"stability":null,"added":["v10.5.0"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"type":{"text":"integer","links":[{"name":"integer","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#number_type","start":0,"end":7}]},"default":null,"description":"An integer identifier for the current thread. On the corresponding worker object\n(if there is any), it is available as [`worker.threadId`](#workerthreadid).\nThis value is unique for each [`Worker`](#class-worker) instance inside a single process.","summary":"An integer identifier for the current thread. On the corresponding worker object (if there is any), it is available as `worker.threadId`. This value is unique for each `Worker` instance inside a single process.","examples":[],"children":[]},{"kind":"property","id":"worker_threadsthreadname","name":"threadName","title":"`worker_threads.threadName`","scope":"module","overloadOf":null,"stability":null,"added":["v24.6.0","v22.20.0"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"type":{"text":"string | null","links":[{"name":"string","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#string_type","start":0,"end":6},{"name":"null","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#null_type","start":9,"end":13}]},"default":null,"description":"A string identifier for the current thread or null if the thread is not running.\nOn the corresponding worker object (if there is any), it is available as [`worker.threadName`](#workerthreadname).","summary":"A string identifier for the current thread or null if the thread is not running. On the corresponding worker object (if there is any), it is available as `worker.threadName`.","examples":[],"children":[]},{"kind":"property","id":"worker_threadsworkerdata","name":"workerData","title":"`worker_threads.workerData`","scope":"module","overloadOf":null,"stability":null,"added":["v10.5.0"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"type":null,"default":null,"description":"An arbitrary JavaScript value that contains a clone of the data passed\nto this thread's `Worker` constructor.\n\nThe data is cloned as if using [`postMessage()`](#portpostmessagevalue-transferlist),\naccording to the [HTML structured clone algorithm](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm).\n\n```mjs\nimport { Worker, isMainThread, workerData } from 'node:worker_threads';\n\nif (isMainThread) {\n  const worker = new Worker(new URL(import.meta.url), { workerData: 'Hello, world!' });\n} else {\n  console.log(workerData);  // Prints 'Hello, world!'.\n}\n```\n\n```cjs\nconst { Worker, isMainThread, workerData } = require('node:worker_threads');\n\nif (isMainThread) {\n  const worker = new Worker(__filename, { workerData: 'Hello, world!' });\n} else {\n  console.log(workerData);  // Prints 'Hello, world!'.\n}\n```","summary":"An arbitrary JavaScript value that contains a clone of the data passed to this thread's `Worker` constructor.","examples":[{"language":"mjs","displayName":null,"code":"import { Worker, isMainThread, workerData } from 'node:worker_threads';\n\nif (isMainThread) {\n  const worker = new Worker(new URL(import.meta.url), { workerData: 'Hello, world!' });\n} else {\n  console.log(workerData);  // Prints 'Hello, world!'.\n}"},{"language":"cjs","displayName":null,"code":"const { Worker, isMainThread, workerData } = require('node:worker_threads');\n\nif (isMainThread) {\n  const worker = new Worker(__filename, { workerData: 'Hello, world!' });\n} else {\n  console.log(workerData);  // Prints 'Hello, world!'.\n}"}],"children":[]},{"kind":"property","id":"worker_threadslocks","name":"locks","title":"`worker_threads.locks`","scope":"module","overloadOf":null,"stability":{"index":"1","description":"Experimental"},"added":["v24.5.0"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"type":{"text":"LockManager","links":[{"name":"LockManager","href":"worker_threads.html#class-lockmanager","start":0,"end":11}]},"default":null,"description":"An instance of a [`LockManager`](#class-lockmanager) that can be used to coordinate\naccess to resources that may be shared across multiple threads within the same\nprocess. The API mirrors the semantics of the\n[browser `LockManager`](https://developer.mozilla.org/en-US/docs/Web/API/LockManager)","summary":"An instance of a `LockManager` that can be used to coordinate access to resources that may be shared across multiple threads within the same process. The API mirrors the semantics of the browser `LockManager`","examples":[],"children":[{"kind":"class","id":"class-lock","name":"Lock","title":"Class: `Lock`","scope":"module","overloadOf":null,"stability":null,"added":["v24.5.0"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"extends":null,"description":"The `Lock` interface provides information about a lock that has been granted via\n[`locks.request()`](#locksrequestname-options-callback)","summary":"The `Lock` interface provides information about a lock that has been granted via `locks.request()`","examples":[],"children":[{"kind":"property","id":"lockname","name":"name","title":"`lock.name`","scope":"module","overloadOf":null,"stability":null,"added":["v24.5.0"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"type":{"text":"string","links":[{"name":"string","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#string_type","start":0,"end":6}]},"default":null,"description":"The name of the lock.","summary":"The name of the lock.","examples":[],"children":[]},{"kind":"property","id":"lockmode","name":"mode","title":"`lock.mode`","scope":"module","overloadOf":null,"stability":null,"added":["v24.5.0"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"type":{"text":"string","links":[{"name":"string","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#string_type","start":0,"end":6}]},"default":null,"description":"The mode of the lock. Either `shared` or `exclusive`.","summary":"The mode of the lock. Either `shared` or `exclusive`.","examples":[],"children":[]}]},{"kind":"class","id":"class-lockmanager","name":"LockManager","title":"Class: `LockManager`","scope":"module","overloadOf":null,"stability":null,"added":["v24.5.0"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"extends":null,"description":"The `LockManager` interface provides methods for requesting and introspecting\nlocks. To obtain a `LockManager` instance use\n\n```mjs\nimport { locks } from 'node:worker_threads';\n```\n\n```cjs\nconst { locks } = require('node:worker_threads');\n```\n\nThis implementation matches the [browser `LockManager`](https://developer.mozilla.org/en-US/docs/Web/API/LockManager) API.","summary":"The `LockManager` interface provides methods for requesting and introspecting locks. To obtain a `LockManager` instance use","examples":[{"language":"mjs","displayName":null,"code":"import { locks } from 'node:worker_threads';"},{"language":"cjs","displayName":null,"code":"const { locks } = require('node:worker_threads');"}],"children":[{"kind":"method","id":"locksrequestname-options-callback","name":"request","title":"`locks.request(name[, options], callback)`","scope":"module","overloadOf":null,"stability":null,"added":["v24.5.0"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"signature":{"parameters":[{"name":"name","type":{"text":"string","links":[{"name":"string","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#string_type","start":0,"end":6}]},"description":"","default":null,"optional":false,"rest":false,"properties":[]},{"name":"options","type":{"text":"Object","links":[{"name":"Object","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object","start":0,"end":6}]},"description":"","default":null,"optional":true,"rest":false,"properties":[{"name":"mode","type":{"text":"string","links":[{"name":"string","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#string_type","start":0,"end":6}]},"description":"Either `'exclusive'` or `'shared'`.","default":"'exclusive'","optional":true,"rest":false,"properties":[]},{"name":"ifAvailable","type":{"text":"boolean","links":[{"name":"boolean","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#boolean_type","start":0,"end":7}]},"description":"If `true`, the request will only be granted if the\nlock is not already held. If it cannot be granted, `callback` will be\ninvoked with `null` instead of a `Lock` instance.","default":"false","optional":true,"rest":false,"properties":[]},{"name":"steal","type":{"text":"boolean","links":[{"name":"boolean","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#boolean_type","start":0,"end":7}]},"description":"If `true`, any existing locks with the same name are\nreleased and the request is granted immediately, pre-empting any queued\nrequests.","default":"false","optional":true,"rest":false,"properties":[]},{"name":"signal","type":{"text":"AbortSignal","links":[{"name":"AbortSignal","href":"globals.html#class-abortsignal","start":0,"end":11}]},"description":"that can be used to abort a\npending (but not yet granted) lock request.","default":null,"optional":false,"rest":false,"properties":[]}]},{"name":"callback","type":{"text":"Function","links":[{"name":"Function","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Function","start":0,"end":8}]},"description":"Invoked once the lock is granted (or immediately with\n`null` if `ifAvailable` is `true` and the lock is unavailable). The lock is\nreleased automatically when the function returns, or—if the function returns\na promise—when that promise settles.","default":null,"optional":false,"rest":false,"properties":[]}],"returns":{"type":{"text":"Promise","links":[{"name":"Promise","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise","start":0,"end":7}]},"description":"Resolves once the lock has been released."}},"description":"```mjs\nimport { locks } from 'node:worker_threads';\n\nawait locks.request('my_resource', async (lock) => {\n  // The lock has been acquired.\n});\n// The lock has been released here.\n```\n\n```cjs\nconst { locks } = require('node:worker_threads');\n\nlocks.request('my_resource', async (lock) => {\n  // The lock has been acquired.\n}).then(() => {\n  // The lock has been released here.\n});\n```","summary":"","examples":[{"language":"mjs","displayName":null,"code":"import { locks } from 'node:worker_threads';\n\nawait locks.request('my_resource', async (lock) => {\n  // The lock has been acquired.\n});\n// The lock has been released here."},{"language":"cjs","displayName":null,"code":"const { locks } = require('node:worker_threads');\n\nlocks.request('my_resource', async (lock) => {\n  // The lock has been acquired.\n}).then(() => {\n  // The lock has been released here.\n});"}],"children":[]},{"kind":"method","id":"locksquery","name":"query","title":"`locks.query()`","scope":"module","overloadOf":null,"stability":null,"added":["v24.5.0"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"signature":{"parameters":[],"returns":{"type":{"text":"Promise","links":[{"name":"Promise","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise","start":0,"end":7}]},"description":""}},"description":"Resolves with a `LockManagerSnapshot` describing the currently held and pending\nlocks for the current process.\n\n```mjs\nimport { locks } from 'node:worker_threads';\n\nconst snapshot = await locks.query();\nfor (const lock of snapshot.held) {\n  console.log(`held lock: name ${lock.name}, mode ${lock.mode}`);\n}\nfor (const pending of snapshot.pending) {\n  console.log(`pending lock: name ${pending.name}, mode ${pending.mode}`);\n}\n```\n\n```cjs\nconst { locks } = require('node:worker_threads');\n\nlocks.query().then((snapshot) => {\n  for (const lock of snapshot.held) {\n    console.log(`held lock: name ${lock.name}, mode ${lock.mode}`);\n  }\n  for (const pending of snapshot.pending) {\n    console.log(`pending lock: name ${pending.name}, mode ${pending.mode}`);\n  }\n});\n```","summary":"Resolves with a `LockManagerSnapshot` describing the currently held and pending locks for the current process.","examples":[{"language":"mjs","displayName":null,"code":"import { locks } from 'node:worker_threads';\n\nconst snapshot = await locks.query();\nfor (const lock of snapshot.held) {\n  console.log(`held lock: name ${lock.name}, mode ${lock.mode}`);\n}\nfor (const pending of snapshot.pending) {\n  console.log(`pending lock: name ${pending.name}, mode ${pending.mode}`);\n}"},{"language":"cjs","displayName":null,"code":"const { locks } = require('node:worker_threads');\n\nlocks.query().then((snapshot) => {\n  for (const lock of snapshot.held) {\n    console.log(`held lock: name ${lock.name}, mode ${lock.mode}`);\n  }\n  for (const pending of snapshot.pending) {\n    console.log(`pending lock: name ${pending.name}, mode ${pending.mode}`);\n  }\n});"}],"children":[]}]}]},{"kind":"class","id":"class-broadcastchannel-extends-eventtarget","name":"BroadcastChannel","title":"Class: `BroadcastChannel extends EventTarget`","scope":"module","overloadOf":null,"stability":null,"added":["v15.4.0"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[{"versions":["v18.0.0"],"prUrl":"https://github.com/nodejs/node/pull/41271","commit":null,"description":"No longer experimental."}],"extends":{"text":"EventTarget","links":[]},"description":"Instances of `BroadcastChannel` allow asynchronous one-to-many communication\nwith all other `BroadcastChannel` instances bound to the same channel name.\n\n```mjs\nimport {\n  isMainThread,\n  BroadcastChannel,\n  Worker,\n} from 'node:worker_threads';\n\nconst bc = new BroadcastChannel('hello');\n\nif (isMainThread) {\n  let c = 0;\n  bc.onmessage = (event) => {\n    console.log(event.data);\n    if (++c === 10) bc.close();\n  };\n  for (let n = 0; n < 10; n++)\n    new Worker(new URL(import.meta.url));\n} else {\n  bc.postMessage('hello from every worker');\n  bc.close();\n}\n```\n\n```cjs\nconst {\n  isMainThread,\n  BroadcastChannel,\n  Worker,\n} = require('node:worker_threads');\n\nconst bc = new BroadcastChannel('hello');\n\nif (isMainThread) {\n  let c = 0;\n  bc.onmessage = (event) => {\n    console.log(event.data);\n    if (++c === 10) bc.close();\n  };\n  for (let n = 0; n < 10; n++)\n    new Worker(__filename);\n} else {\n  bc.postMessage('hello from every worker');\n  bc.close();\n}\n```","summary":"Instances of `BroadcastChannel` allow asynchronous one-to-many communication with all other `BroadcastChannel` instances bound to the same channel name.","examples":[{"language":"mjs","displayName":null,"code":"import {\n  isMainThread,\n  BroadcastChannel,\n  Worker,\n} from 'node:worker_threads';\n\nconst bc = new BroadcastChannel('hello');\n\nif (isMainThread) {\n  let c = 0;\n  bc.onmessage = (event) => {\n    console.log(event.data);\n    if (++c === 10) bc.close();\n  };\n  for (let n = 0; n < 10; n++)\n    new Worker(new URL(import.meta.url));\n} else {\n  bc.postMessage('hello from every worker');\n  bc.close();\n}"},{"language":"cjs","displayName":null,"code":"const {\n  isMainThread,\n  BroadcastChannel,\n  Worker,\n} = require('node:worker_threads');\n\nconst bc = new BroadcastChannel('hello');\n\nif (isMainThread) {\n  let c = 0;\n  bc.onmessage = (event) => {\n    console.log(event.data);\n    if (++c === 10) bc.close();\n  };\n  for (let n = 0; n < 10; n++)\n    new Worker(__filename);\n} else {\n  bc.postMessage('hello from every worker');\n  bc.close();\n}"}],"children":[{"kind":"constructor","id":"new-broadcastchannelname","name":"BroadcastChannel","title":"`new BroadcastChannel(name)`","scope":"module","overloadOf":null,"stability":null,"added":["v15.4.0"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"signature":{"parameters":[{"name":"name","type":{"text":"any","links":[{"name":"any","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types","start":0,"end":3}]},"description":"The name of the channel to connect to. Any JavaScript value\nthat can be converted to a string using `` `${name}` `` is permitted.","default":null,"optional":false,"rest":false,"properties":[]}],"returns":null},"description":"","summary":"","examples":[],"children":[]},{"kind":"method","id":"broadcastchannelclose","name":"close","title":"`broadcastChannel.close()`","scope":"module","overloadOf":null,"stability":null,"added":["v15.4.0"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"signature":{"parameters":[],"returns":null},"description":"Closes the `BroadcastChannel` connection.","summary":"Closes the `BroadcastChannel` connection.","examples":[],"children":[]},{"kind":"property","id":"broadcastchannelonmessage","name":"onmessage","title":"`broadcastChannel.onmessage`","scope":"module","overloadOf":null,"stability":null,"added":["v15.4.0"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"type":{"text":"Function","links":[{"name":"Function","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Function","start":0,"end":8}]},"default":null,"description":"Invoked with a single `MessageEvent` argument\nwhen a message is received.","summary":"","examples":[],"children":[]},{"kind":"property","id":"broadcastchannelonmessageerror","name":"onmessageerror","title":"`broadcastChannel.onmessageerror`","scope":"module","overloadOf":null,"stability":null,"added":["v15.4.0"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"type":{"text":"Function","links":[{"name":"Function","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Function","start":0,"end":8}]},"default":null,"description":"Invoked with a received message cannot be\ndeserialized.","summary":"","examples":[],"children":[]},{"kind":"method","id":"broadcastchannelpostmessagemessage","name":"postMessage","title":"`broadcastChannel.postMessage(message)`","scope":"module","overloadOf":null,"stability":null,"added":["v15.4.0"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"signature":{"parameters":[{"name":"message","type":{"text":"any","links":[{"name":"any","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types","start":0,"end":3}]},"description":"Any cloneable JavaScript value.","default":null,"optional":false,"rest":false,"properties":[]}],"returns":null},"description":"","summary":"","examples":[],"children":[]},{"kind":"method","id":"broadcastchannelref","name":"ref","title":"`broadcastChannel.ref()`","scope":"module","overloadOf":null,"stability":null,"added":["v15.4.0"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"signature":{"parameters":[],"returns":null},"description":"Opposite of `unref()`. Calling `ref()` on a previously `unref()`ed\nBroadcastChannel does *not* let the program exit if it's the only active handle\nleft (the default behavior). If the port is `ref()`ed, calling `ref()` again\nhas no effect.","summary":"Opposite of `unref()`. Calling `ref()` on a previously `unref()`ed BroadcastChannel does _not_ let the program exit if it's the only active handle left (the default behavior). If the port is `ref()`ed, calling `ref()` again has no effect.","examples":[],"children":[]},{"kind":"method","id":"broadcastchannelunref","name":"unref","title":"`broadcastChannel.unref()`","scope":"module","overloadOf":null,"stability":null,"added":["v15.4.0"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"signature":{"parameters":[],"returns":null},"description":"Calling `unref()` on a BroadcastChannel allows the thread to exit if this\nis the only active handle in the event system. If the BroadcastChannel is\nalready `unref()`ed calling `unref()` again has no effect.","summary":"Calling `unref()` on a BroadcastChannel allows the thread to exit if this is the only active handle in the event system. If the BroadcastChannel is already `unref()`ed calling `unref()` again has no effect.","examples":[],"children":[]}]},{"kind":"class","id":"class-messagechannel","name":"MessageChannel","title":"Class: `MessageChannel`","scope":"module","overloadOf":null,"stability":null,"added":["v10.5.0"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"extends":null,"description":"Instances of the `worker.MessageChannel` class represent an asynchronous,\ntwo-way communications channel.\nThe `MessageChannel` has no methods of its own. `new MessageChannel()`\nyields an object with `port1` and `port2` properties, which refer to linked\n[`MessagePort`](#class-messageport) instances.\n\n```mjs\nimport { MessageChannel } from 'node:worker_threads';\n\nconst { port1, port2 } = new MessageChannel();\nport1.on('message', (message) => console.log('received', message));\nport2.postMessage({ foo: 'bar' });\n// Prints: received { foo: 'bar' } from the `port1.on('message')` listener\n```\n\n```cjs\nconst { MessageChannel } = require('node:worker_threads');\n\nconst { port1, port2 } = new MessageChannel();\nport1.on('message', (message) => console.log('received', message));\nport2.postMessage({ foo: 'bar' });\n// Prints: received { foo: 'bar' } from the `port1.on('message')` listener\n```","summary":"Instances of the `worker.MessageChannel` class represent an asynchronous, two-way communications channel. The `MessageChannel` has no methods of its own. `new MessageChannel()` yields an object with `port1` and `port2` properties, which refer to linked `MessagePort` instances.","examples":[{"language":"mjs","displayName":null,"code":"import { MessageChannel } from 'node:worker_threads';\n\nconst { port1, port2 } = new MessageChannel();\nport1.on('message', (message) => console.log('received', message));\nport2.postMessage({ foo: 'bar' });\n// Prints: received { foo: 'bar' } from the `port1.on('message')` listener"},{"language":"cjs","displayName":null,"code":"const { MessageChannel } = require('node:worker_threads');\n\nconst { port1, port2 } = new MessageChannel();\nport1.on('message', (message) => console.log('received', message));\nport2.postMessage({ foo: 'bar' });\n// Prints: received { foo: 'bar' } from the `port1.on('message')` listener"}],"children":[]},{"kind":"class","id":"class-messageport","name":"MessagePort","title":"Class: `MessagePort`","scope":"module","overloadOf":null,"stability":null,"added":["v10.5.0"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[{"versions":["v14.7.0"],"prUrl":"https://github.com/nodejs/node/pull/34057","commit":null,"description":"This class now inherits from `EventTarget` rather than from `EventEmitter`."}],"extends":{"text":"EventTarget","links":[{"name":"EventTarget","href":"events.html#class-eventtarget","start":0,"end":11}]},"description":"Instances of the `worker.MessagePort` class represent one end of an\nasynchronous, two-way communications channel. It can be used to transfer\nstructured data, memory regions and other `MessagePort`s between different\n[`Worker`](#class-worker)s.\n\nThis implementation matches [browser `MessagePort`](https://developer.mozilla.org/en-US/docs/Web/API/MessagePort)s.","summary":"Instances of the `worker.MessagePort` class represent one end of an asynchronous, two-way communications channel. It can be used to transfer structured data, memory regions and other `MessagePort`s between different `Worker`s.","examples":[],"children":[{"kind":"event","id":"event-close","name":"close","title":"Event: `'close'`","scope":"module","overloadOf":null,"stability":null,"added":["v10.5.0"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"parameters":[],"description":"The `'close'` event is emitted once either side of the channel has been\ndisconnected.\n\n```mjs\nimport { MessageChannel } from 'node:worker_threads';\nconst { port1, port2 } = new MessageChannel();\n\n// Prints:\n//   foobar\n//   closed!\nport2.on('message', (message) => console.log(message));\nport2.once('close', () => console.log('closed!'));\n\nport1.postMessage('foobar');\nport1.close();\n```\n\n```cjs\nconst { MessageChannel } = require('node:worker_threads');\nconst { port1, port2 } = new MessageChannel();\n\n// Prints:\n//   foobar\n//   closed!\nport2.on('message', (message) => console.log(message));\nport2.once('close', () => console.log('closed!'));\n\nport1.postMessage('foobar');\nport1.close();\n```","summary":"The `'close'` event is emitted once either side of the channel has been disconnected.","examples":[{"language":"mjs","displayName":null,"code":"import { MessageChannel } from 'node:worker_threads';\nconst { port1, port2 } = new MessageChannel();\n\n// Prints:\n//   foobar\n//   closed!\nport2.on('message', (message) => console.log(message));\nport2.once('close', () => console.log('closed!'));\n\nport1.postMessage('foobar');\nport1.close();"},{"language":"cjs","displayName":null,"code":"const { MessageChannel } = require('node:worker_threads');\nconst { port1, port2 } = new MessageChannel();\n\n// Prints:\n//   foobar\n//   closed!\nport2.on('message', (message) => console.log(message));\nport2.once('close', () => console.log('closed!'));\n\nport1.postMessage('foobar');\nport1.close();"}],"children":[]},{"kind":"event","id":"event-message","name":"message","title":"Event: `'message'`","scope":"module","overloadOf":null,"stability":null,"added":["v10.5.0"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"parameters":[{"name":"value","type":{"text":"any","links":[{"name":"any","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types","start":0,"end":3}]},"description":"The transmitted value","default":null,"optional":false,"rest":false,"properties":[]}],"description":"The `'message'` event is emitted for any incoming message, containing the cloned\ninput of [`port.postMessage()`](#portpostmessagevalue-transferlist).\n\nListeners on this event receive a clone of the `value` parameter as passed\nto `postMessage()` and no further arguments.","summary":"The `'message'` event is emitted for any incoming message, containing the cloned input of `port.postMessage()`.","examples":[],"children":[]},{"kind":"event","id":"event-messageerror","name":"messageerror","title":"Event: `'messageerror'`","scope":"module","overloadOf":null,"stability":null,"added":["v14.5.0","v12.19.0"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"parameters":[{"name":"error","type":{"text":"Error","links":[{"name":"Error","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Error","start":0,"end":5}]},"description":"An Error object","default":null,"optional":false,"rest":false,"properties":[]}],"description":"The `'messageerror'` event is emitted when deserializing a message failed.\n\nCurrently, this event is emitted when there is an error occurring while\ninstantiating the posted JS object on the receiving end. Such situations\nare rare, but can happen, for instance, when certain Node.js API objects\nare received in a `vm.Context` (where Node.js APIs are currently\nunavailable).","summary":"The `'messageerror'` event is emitted when deserializing a message failed.","examples":[],"children":[]},{"kind":"method","id":"portclose","name":"close","title":"`port.close()`","scope":"module","overloadOf":null,"stability":null,"added":["v10.5.0"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"signature":{"parameters":[],"returns":null},"description":"Disables further sending of messages on either side of the connection.\nThis method can be called when no further communication will happen over this\n`MessagePort`.\n\nThe [`'close'` event](#event-close) is emitted on both `MessagePort` instances that\nare part of the channel.","summary":"Disables further sending of messages on either side of the connection. This method can be called when no further communication will happen over this `MessagePort`.","examples":[],"children":[]},{"kind":"method","id":"portpostmessagevalue-transferlist","name":"postMessage","title":"`port.postMessage(value[, transferList])`","scope":"module","overloadOf":null,"stability":null,"added":["v10.5.0"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[{"versions":["v21.0.0"],"prUrl":"https://github.com/nodejs/node/pull/47604","commit":null,"description":"An error is thrown when an untransferable object is in the transfer list."},{"versions":["v15.14.0","v14.18.0"],"prUrl":"https://github.com/nodejs/node/pull/37917","commit":null,"description":"Add 'BlockList' to the list of cloneable types."},{"versions":["v15.9.0","v14.18.0"],"prUrl":"https://github.com/nodejs/node/pull/37155","commit":null,"description":"Add 'Histogram' types to the list of cloneable types."},{"versions":["v15.6.0"],"prUrl":"https://github.com/nodejs/node/pull/36804","commit":null,"description":"Added `X509Certificate` to the list of cloneable types."},{"versions":["v15.0.0"],"prUrl":"https://github.com/nodejs/node/pull/35093","commit":null,"description":"Added `CryptoKey` to the list of cloneable types."},{"versions":["v14.5.0","v12.19.0"],"prUrl":"https://github.com/nodejs/node/pull/33360","commit":null,"description":"Added `KeyObject` to the list of cloneable types."},{"versions":["v14.5.0","v12.19.0"],"prUrl":"https://github.com/nodejs/node/pull/33772","commit":null,"description":"Added `FileHandle` to the list of transferable types."}],"signature":{"parameters":[{"name":"value","type":{"text":"any","links":[{"name":"any","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types","start":0,"end":3}]},"description":"","default":null,"optional":false,"rest":false,"properties":[]},{"name":"transferList","type":{"text":"Object[]","links":[{"name":"Object","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object","start":0,"end":6}]},"description":"","default":null,"optional":true,"rest":false,"properties":[]}],"returns":null},"description":"Sends a JavaScript value to the receiving side of this channel.\n`value` is transferred in a way which is compatible with\nthe [HTML structured clone algorithm](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm).\n\nIn particular, the significant differences to `JSON` are:\n\n* `value` may contain circular references.\n* `value` may contain instances of builtin JS types such as `RegExp`s,\n  `BigInt`s, `Map`s, `Set`s, etc.\n* `value` may contain typed arrays, both using `ArrayBuffer`s\n  and `SharedArrayBuffer`s.\n* `value` may contain [`WebAssembly.Module`](https://developer.mozilla.org/en-US/docs/WebAssembly/Reference/JavaScript_interface/Module) instances.\n* `value` may not contain native (C++-backed) objects other than:\n  * {CryptoKey}s,\n  * {FileHandle}s,\n  * {Histogram}s,\n  * {KeyObject}s,\n  * {MessagePort}s,\n  * {net.BlockList}s,\n  * {net.Server}s (TCP only, when listed in `transferList`),\n  * {net.Socket}s (TCP only, when listed in `transferList`),\n  * {net.SocketAddress}es,\n  * {X509Certificate}s.\n\n```mjs\nimport { MessageChannel } from 'node:worker_threads';\nconst { port1, port2 } = new MessageChannel();\n\nport1.on('message', (message) => console.log(message));\n\nconst circularData = {};\ncircularData.foo = circularData;\n// Prints: { foo: [Circular] }\nport2.postMessage(circularData);\n```\n\n```cjs\nconst { MessageChannel } = require('node:worker_threads');\nconst { port1, port2 } = new MessageChannel();\n\nport1.on('message', (message) => console.log(message));\n\nconst circularData = {};\ncircularData.foo = circularData;\n// Prints: { foo: [Circular] }\nport2.postMessage(circularData);\n```\n\n`transferList` may be a list of {ArrayBuffer}, [`MessagePort`](#class-messageport),\n[`FileHandle`](fs.html#class-filehandle), {net.Server}, and {net.Socket} objects.\nAfter transferring, they are not usable on the sending side of the channel\nanymore (even if they are not contained in `value`).\n\nTransferring a {net.Server} moves its listening socket — together with any\npending connections in the accept queue — to the receiving thread's event loop.\nTransferring a {net.Socket} moves a single connection; the socket must be a\nfreshly accepted or created TCP connection that has not yet started reading and\nhas no buffered data, otherwise `postMessage()` throws\n`ERR_WORKER_HANDLE_NOT_TRANSFERABLE`. This makes it possible to accept\nconnections on one thread and distribute them across a pool of worker threads.\nOnly TCP handles are supported.\n\nIf `value` contains {SharedArrayBuffer} instances, those are accessible\nfrom either thread. They cannot be listed in `transferList`.\n\n`value` may still contain `ArrayBuffer` instances that are not in\n`transferList`; in that case, the underlying memory is copied rather than moved.\n\n```mjs\nimport { MessageChannel } from 'node:worker_threads';\nconst { port1, port2 } = new MessageChannel();\n\nport1.on('message', (message) => console.log(message));\n\nconst uint8Array = new Uint8Array([ 1, 2, 3, 4 ]);\n// This posts a copy of `uint8Array`:\nport2.postMessage(uint8Array);\n// This does not copy data, but renders `uint8Array` unusable:\nport2.postMessage(uint8Array, [ uint8Array.buffer ]);\n\n// The memory for the `sharedUint8Array` is accessible from both the\n// original and the copy received by `.on('message')`:\nconst sharedUint8Array = new Uint8Array(new SharedArrayBuffer(4));\nport2.postMessage(sharedUint8Array);\n\n// This transfers a freshly created message port to the receiver.\n// This can be used, for example, to create communication channels between\n// multiple `Worker` threads that are children of the same parent thread.\nconst otherChannel = new MessageChannel();\nport2.postMessage({ port: otherChannel.port1 }, [ otherChannel.port1 ]);\n```\n\n```cjs\nconst { MessageChannel } = require('node:worker_threads');\nconst { port1, port2 } = new MessageChannel();\n\nport1.on('message', (message) => console.log(message));\n\nconst uint8Array = new Uint8Array([ 1, 2, 3, 4 ]);\n// This posts a copy of `uint8Array`:\nport2.postMessage(uint8Array);\n// This does not copy data, but renders `uint8Array` unusable:\nport2.postMessage(uint8Array, [ uint8Array.buffer ]);\n\n// The memory for the `sharedUint8Array` is accessible from both the\n// original and the copy received by `.on('message')`:\nconst sharedUint8Array = new Uint8Array(new SharedArrayBuffer(4));\nport2.postMessage(sharedUint8Array);\n\n// This transfers a freshly created message port to the receiver.\n// This can be used, for example, to create communication channels between\n// multiple `Worker` threads that are children of the same parent thread.\nconst otherChannel = new MessageChannel();\nport2.postMessage({ port: otherChannel.port1 }, [ otherChannel.port1 ]);\n```\n\nThe message object is cloned immediately, and can be modified after\nposting without having side effects.\n\nFor more information on the serialization and deserialization mechanisms\nbehind this API, see the [serialization API of the `node:v8` module](v8.html#serialization-api).","summary":"Sends a JavaScript value to the receiving side of this channel. `value` is transferred in a way which is compatible with the HTML structured clone algorithm.","examples":[{"language":"mjs","displayName":null,"code":"import { MessageChannel } from 'node:worker_threads';\nconst { port1, port2 } = new MessageChannel();\n\nport1.on('message', (message) => console.log(message));\n\nconst circularData = {};\ncircularData.foo = circularData;\n// Prints: { foo: [Circular] }\nport2.postMessage(circularData);"},{"language":"cjs","displayName":null,"code":"const { MessageChannel } = require('node:worker_threads');\nconst { port1, port2 } = new MessageChannel();\n\nport1.on('message', (message) => console.log(message));\n\nconst circularData = {};\ncircularData.foo = circularData;\n// Prints: { foo: [Circular] }\nport2.postMessage(circularData);"},{"language":"mjs","displayName":null,"code":"import { MessageChannel } from 'node:worker_threads';\nconst { port1, port2 } = new MessageChannel();\n\nport1.on('message', (message) => console.log(message));\n\nconst uint8Array = new Uint8Array([ 1, 2, 3, 4 ]);\n// This posts a copy of `uint8Array`:\nport2.postMessage(uint8Array);\n// This does not copy data, but renders `uint8Array` unusable:\nport2.postMessage(uint8Array, [ uint8Array.buffer ]);\n\n// The memory for the `sharedUint8Array` is accessible from both the\n// original and the copy received by `.on('message')`:\nconst sharedUint8Array = new Uint8Array(new SharedArrayBuffer(4));\nport2.postMessage(sharedUint8Array);\n\n// This transfers a freshly created message port to the receiver.\n// This can be used, for example, to create communication channels between\n// multiple `Worker` threads that are children of the same parent thread.\nconst otherChannel = new MessageChannel();\nport2.postMessage({ port: otherChannel.port1 }, [ otherChannel.port1 ]);"},{"language":"cjs","displayName":null,"code":"const { MessageChannel } = require('node:worker_threads');\nconst { port1, port2 } = new MessageChannel();\n\nport1.on('message', (message) => console.log(message));\n\nconst uint8Array = new Uint8Array([ 1, 2, 3, 4 ]);\n// This posts a copy of `uint8Array`:\nport2.postMessage(uint8Array);\n// This does not copy data, but renders `uint8Array` unusable:\nport2.postMessage(uint8Array, [ uint8Array.buffer ]);\n\n// The memory for the `sharedUint8Array` is accessible from both the\n// original and the copy received by `.on('message')`:\nconst sharedUint8Array = new Uint8Array(new SharedArrayBuffer(4));\nport2.postMessage(sharedUint8Array);\n\n// This transfers a freshly created message port to the receiver.\n// This can be used, for example, to create communication channels between\n// multiple `Worker` threads that are children of the same parent thread.\nconst otherChannel = new MessageChannel();\nport2.postMessage({ port: otherChannel.port1 }, [ otherChannel.port1 ]);"}],"children":[{"kind":"section","id":"considerations-when-transferring-typedarrays-and-buffers","name":"Considerations when transferring TypedArrays and Buffers","title":"Considerations when transferring TypedArrays and Buffers","scope":"module","overloadOf":null,"stability":null,"added":[],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"description":"All {TypedArray | Buffer} instances are views over an underlying\n{ArrayBuffer}. That is, it is the `ArrayBuffer` that actually stores\nthe raw data while the `TypedArray` and `Buffer` objects provide a\nway of viewing and manipulating the data. It is possible and common\nfor multiple views to be created over the same `ArrayBuffer` instance.\nGreat care must be taken when using a transfer list to transfer an\n`ArrayBuffer` as doing so causes all `TypedArray` and `Buffer`\ninstances that share that same `ArrayBuffer` to become unusable.\n\n```js\nconst ab = new ArrayBuffer(10);\n\nconst u1 = new Uint8Array(ab);\nconst u2 = new Uint16Array(ab);\n\nconsole.log(u2.length);  // prints 5\n\nport.postMessage(u1, [u1.buffer]);\n\nconsole.log(u2.length);  // prints 0\n```\n\nFor `Buffer` instances, specifically, whether the underlying\n`ArrayBuffer` can be transferred or cloned depends entirely on how\ninstances were created, which often cannot be reliably determined.\n\nAn `ArrayBuffer` can be marked with [`markAsUntransferable()`](#worker_threadsmarkasuntransferableobject) to indicate\nthat it should always be cloned and never transferred.\n\nDepending on how a `Buffer` instance was created, it may or may\nnot own its underlying `ArrayBuffer`. An `ArrayBuffer` must not\nbe transferred unless it is known that the `Buffer` instance\nowns it. In particular, for `Buffer`s created from the internal\n`Buffer` pool (using, for instance `Buffer.from()` or `Buffer.allocUnsafe()`),\ntransferring them is not possible and they are always cloned,\nwhich sends a copy of the entire `Buffer` pool.\nThis behavior may come with unintended higher memory\nusage and possible security concerns.\n\nSee [`Buffer.allocUnsafe()`](buffer.html#static-method-bufferallocunsafesize-alignment) for more details on `Buffer` pooling.\n\nThe `ArrayBuffer`s for `Buffer` instances created using\n`Buffer.alloc()` or `Buffer.allocUnsafeSlow()` can always be\ntransferred but doing so renders all other existing views of\nthose `ArrayBuffer`s unusable.","summary":"All {TypedArray | Buffer} instances are views over an underlying {ArrayBuffer}. That is, it is the `ArrayBuffer` that actually stores the raw data while the `TypedArray` and `Buffer` objects provide a way of viewing and manipulating the data. It is possible and common for multiple views to be created over the same `ArrayBuffer` instance. Great care must be taken when using a transfer list to transfer an `ArrayBuffer` as doing so causes all `TypedArray` and `Buffer` instances that share that same `ArrayBuffer` to become unusable.","examples":[{"language":"js","displayName":null,"code":"const ab = new ArrayBuffer(10);\n\nconst u1 = new Uint8Array(ab);\nconst u2 = new Uint16Array(ab);\n\nconsole.log(u2.length);  // prints 5\n\nport.postMessage(u1, [u1.buffer]);\n\nconsole.log(u2.length);  // prints 0"}],"children":[]},{"kind":"section","id":"considerations-when-cloning-objects-with-prototypes-classes-and-accessors","name":"Considerations when cloning objects with prototypes, classes, and accessors","title":"Considerations when cloning objects with prototypes, classes, and accessors","scope":"module","overloadOf":null,"stability":null,"added":[],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"description":"Because object cloning uses the [HTML structured clone algorithm](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm),\nnon-enumerable properties, property accessors, and object prototypes are\nnot preserved. In particular, {Buffer} objects will be read as\nplain {Uint8Array}s on the receiving side, and instances of JavaScript\nclasses will be cloned as plain JavaScript objects.\n\n```js\nconst b = Symbol('b');\n\nclass Foo {\n  #a = 1;\n  constructor() {\n    this[b] = 2;\n    this.c = 3;\n  }\n\n  get d() { return this.#a + 3; }\n}\n\nconst { port1, port2 } = new MessageChannel();\n\nport1.onmessage = ({ data }) => console.log(data);\n\nport2.postMessage(new Foo());\n\n// Prints: { c: 3 }\n```\n\nSome built-in objects cannot be cloned at all. For example, posting a\n`URL` object throws a `DataCloneError`:\n\n```js\nconst { port1, port2 } = new MessageChannel();\n\nport2.postMessage(new URL('https://example.org'));\n// Throws DataCloneError: Cannot clone object of unsupported type.\n```","summary":"Because object cloning uses the HTML structured clone algorithm, non-enumerable properties, property accessors, and object prototypes are not preserved. In particular, {Buffer} objects will be read as plain {Uint8Array}s on the receiving side, and instances of JavaScript classes will be cloned as plain JavaScript objects.","examples":[{"language":"js","displayName":null,"code":"const b = Symbol('b');\n\nclass Foo {\n  #a = 1;\n  constructor() {\n    this[b] = 2;\n    this.c = 3;\n  }\n\n  get d() { return this.#a + 3; }\n}\n\nconst { port1, port2 } = new MessageChannel();\n\nport1.onmessage = ({ data }) => console.log(data);\n\nport2.postMessage(new Foo());\n\n// Prints: { c: 3 }"},{"language":"js","displayName":null,"code":"const { port1, port2 } = new MessageChannel();\n\nport2.postMessage(new URL('https://example.org'));\n// Throws DataCloneError: Cannot clone object of unsupported type."}],"children":[]}]},{"kind":"method","id":"porthasref","name":"hasRef","title":"`port.hasRef()`","scope":"module","overloadOf":null,"stability":null,"added":["v18.1.0","v16.17.0"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[{"versions":["v24.0.0","v22.17.0"],"prUrl":"https://github.com/nodejs/node/pull/57513","commit":null,"description":"Marking the API stable."}],"signature":{"parameters":[],"returns":{"type":{"text":"boolean","links":[{"name":"boolean","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#boolean_type","start":0,"end":7}]},"description":""}},"description":"If true, the `MessagePort` object will keep the Node.js event loop active.","summary":"If true, the `MessagePort` object will keep the Node.js event loop active.","examples":[],"children":[]},{"kind":"method","id":"portref","name":"ref","title":"`port.ref()`","scope":"module","overloadOf":null,"stability":null,"added":["v10.5.0"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"signature":{"parameters":[],"returns":null},"description":"Opposite of `unref()`. Calling `ref()` on a previously `unref()`ed port does\n*not* let the program exit if it's the only active handle left (the default\nbehavior). If the port is `ref()`ed, calling `ref()` again has no effect.\n\nIf listeners are attached or removed using `.on('message')`, the port\nis `ref()`ed and `unref()`ed automatically depending on whether\nlisteners for the event exist.","summary":"Opposite of `unref()`. Calling `ref()` on a previously `unref()`ed port does _not_ let the program exit if it's the only active handle left (the default behavior). If the port is `ref()`ed, calling `ref()` again has no effect.","examples":[],"children":[]},{"kind":"method","id":"portstart","name":"start","title":"`port.start()`","scope":"module","overloadOf":null,"stability":null,"added":["v10.5.0"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"signature":{"parameters":[],"returns":null},"description":"Starts receiving messages on this `MessagePort`. When using this port\nas an event emitter, this is called automatically once `'message'`\nlisteners are attached.\n\nThis method exists for parity with the Web `MessagePort` API. In Node.js,\nit is only useful for ignoring messages when no event listener is present.\nNode.js also diverges in its handling of `.onmessage`. Setting it\nautomatically calls `.start()`, but unsetting it lets messages queue up\nuntil a new handler is set or the port is discarded.","summary":"Starts receiving messages on this `MessagePort`. When using this port as an event emitter, this is called automatically once `'message'` listeners are attached.","examples":[],"children":[]},{"kind":"method","id":"portunref","name":"unref","title":"`port.unref()`","scope":"module","overloadOf":null,"stability":null,"added":["v10.5.0"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"signature":{"parameters":[],"returns":null},"description":"Calling `unref()` on a port allows the thread to exit if this is the only\nactive handle in the event system. If the port is already `unref()`ed calling\n`unref()` again has no effect.\n\nIf listeners are attached or removed using `.on('message')`, the port is\n`ref()`ed and `unref()`ed automatically depending on whether\nlisteners for the event exist.","summary":"Calling `unref()` on a port allows the thread to exit if this is the only active handle in the event system. If the port is already `unref()`ed calling `unref()` again has no effect.","examples":[],"children":[]}]},{"kind":"class","id":"class-worker","name":"Worker","title":"Class: `Worker`","scope":"module","overloadOf":null,"stability":null,"added":["v10.5.0"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"extends":{"text":"EventEmitter","links":[{"name":"EventEmitter","href":"events.html#class-eventemitter","start":0,"end":12}]},"description":"The `Worker` class represents an independent JavaScript execution thread.\nMost Node.js APIs are available inside of it.\n\nNotable differences inside a Worker environment are:\n\n* The [`process.stdin`](process.html#processstdin), [`process.stdout`](process.html#processstdout), and [`process.stderr`](process.html#processstderr)\n  streams may be redirected by the parent thread.\n* The [`require('node:worker_threads').isMainThread`](#worker_threadsismainthread) property is set to `false`.\n* The [`require('node:worker_threads').parentPort`](#worker_threadsparentport) message port is available.\n* [`process.exit()`](process.html#processexitcode) does not stop the whole program, just the single thread,\n  and [`process.abort()`](process.html#processabort) is not available.\n* [`process.chdir()`](process.html#processchdirdirectory) and `process` methods that set group or user ids\n  are not available.\n* [`process.env`](process.html#processenv) is a copy of the parent thread's environment variables,\n  unless otherwise specified. Changes to one copy are not visible in other\n  threads, and are not visible to native add-ons (unless\n  [`worker.SHARE_ENV`](#worker_threadsshare_env) is passed as the `env` option to the\n  [`Worker`](#class-worker) constructor). On Windows, unlike the main thread, a copy of the\n  environment variables operates in a case-sensitive manner.\n* [`process.title`](process.html#processtitle) cannot be modified.\n* Signals are not delivered through [`process.on('...')`](process.html#signal-events).\n* Execution may stop at any point as a result of [`worker.terminate()`](#workerterminate)\n  being invoked.\n* IPC channels from parent processes are not accessible.\n* The [`trace_events`](tracing.html) module is not supported.\n* Native add-ons can only be loaded from multiple threads if they fulfill\n  [certain conditions](addons.html#worker-support).\n\nCreating `Worker` instances inside of other `Worker`s is possible.\n\nLike [Web Workers](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API) and the [`node:cluster` module](cluster.html), two-way communication\ncan be achieved through inter-thread message passing. Internally, a `Worker` has\na built-in pair of [`MessagePort`](#class-messageport)s that are already associated with each\nother when the `Worker` is created. While the `MessagePort` object on the parent\nside is not directly exposed, its functionalities are exposed through\n[`worker.postMessage()`](#workerpostmessagevalue-transferlist) and the [`worker.on('message')`](#event-message_1) event\non the `Worker` object for the parent thread.\n\nTo create custom messaging channels (which is encouraged over using the default\nglobal channel because it facilitates separation of concerns), users can create\na `MessageChannel` object on either thread and pass one of the\n`MessagePort`s on that `MessageChannel` to the other thread through a\npre-existing channel, such as the global one.\n\nSee [`port.postMessage()`](#portpostmessagevalue-transferlist) for more information on how messages are passed,\nand what kind of JavaScript values can be successfully transported through\nthe thread barrier.\n\n```mjs\nimport assert from 'node:assert';\nimport {\n  Worker, MessageChannel, MessagePort, isMainThread, parentPort,\n} from 'node:worker_threads';\nif (isMainThread) {\n  const worker = new Worker(new URL(import.meta.url));\n  const subChannel = new MessageChannel();\n  worker.postMessage({ hereIsYourPort: subChannel.port1 }, [subChannel.port1]);\n  subChannel.port2.on('message', (value) => {\n    console.log('received:', value);\n  });\n} else {\n  parentPort.once('message', (value) => {\n    assert(value.hereIsYourPort instanceof MessagePort);\n    value.hereIsYourPort.postMessage('the worker is sending this');\n    value.hereIsYourPort.close();\n  });\n}\n```\n\n```cjs\nconst assert = require('node:assert');\nconst {\n  Worker, MessageChannel, MessagePort, isMainThread, parentPort,\n} = require('node:worker_threads');\nif (isMainThread) {\n  const worker = new Worker(__filename);\n  const subChannel = new MessageChannel();\n  worker.postMessage({ hereIsYourPort: subChannel.port1 }, [subChannel.port1]);\n  subChannel.port2.on('message', (value) => {\n    console.log('received:', value);\n  });\n} else {\n  parentPort.once('message', (value) => {\n    assert(value.hereIsYourPort instanceof MessagePort);\n    value.hereIsYourPort.postMessage('the worker is sending this');\n    value.hereIsYourPort.close();\n  });\n}\n```","summary":"The `Worker` class represents an independent JavaScript execution thread. Most Node.js APIs are available inside of it.","examples":[{"language":"mjs","displayName":null,"code":"import assert from 'node:assert';\nimport {\n  Worker, MessageChannel, MessagePort, isMainThread, parentPort,\n} from 'node:worker_threads';\nif (isMainThread) {\n  const worker = new Worker(new URL(import.meta.url));\n  const subChannel = new MessageChannel();\n  worker.postMessage({ hereIsYourPort: subChannel.port1 }, [subChannel.port1]);\n  subChannel.port2.on('message', (value) => {\n    console.log('received:', value);\n  });\n} else {\n  parentPort.once('message', (value) => {\n    assert(value.hereIsYourPort instanceof MessagePort);\n    value.hereIsYourPort.postMessage('the worker is sending this');\n    value.hereIsYourPort.close();\n  });\n}"},{"language":"cjs","displayName":null,"code":"const assert = require('node:assert');\nconst {\n  Worker, MessageChannel, MessagePort, isMainThread, parentPort,\n} = require('node:worker_threads');\nif (isMainThread) {\n  const worker = new Worker(__filename);\n  const subChannel = new MessageChannel();\n  worker.postMessage({ hereIsYourPort: subChannel.port1 }, [subChannel.port1]);\n  subChannel.port2.on('message', (value) => {\n    console.log('received:', value);\n  });\n} else {\n  parentPort.once('message', (value) => {\n    assert(value.hereIsYourPort instanceof MessagePort);\n    value.hereIsYourPort.postMessage('the worker is sending this');\n    value.hereIsYourPort.close();\n  });\n}"}],"children":[{"kind":"constructor","id":"new-workerfilename-options","name":"Worker","title":"`new Worker(filename[, options])`","scope":"module","overloadOf":null,"stability":null,"added":["v10.5.0"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[{"versions":["v19.8.0","v18.16.0"],"prUrl":"https://github.com/nodejs/node/pull/46832","commit":null,"description":"Added support for a `name` option, which allows adding a name to worker title for debugging."},{"versions":["v14.9.0"],"prUrl":"https://github.com/nodejs/node/pull/34584","commit":null,"description":"The `filename` parameter can be a WHATWG `URL` object using `data:` protocol."},{"versions":["v14.9.0"],"prUrl":"https://github.com/nodejs/node/pull/34394","commit":null,"description":"The `trackUnmanagedFds` option was set to `true` by default."},{"versions":["v14.6.0","v12.19.0"],"prUrl":"https://github.com/nodejs/node/pull/34303","commit":null,"description":"The `trackUnmanagedFds` option was introduced."},{"versions":["v13.13.0","v12.17.0"],"prUrl":"https://github.com/nodejs/node/pull/32278","commit":null,"description":"The `transferList` option was introduced."},{"versions":["v13.12.0","v12.17.0"],"prUrl":"https://github.com/nodejs/node/pull/31664","commit":null,"description":"The `filename` parameter can be a WHATWG `URL` object using `file:` protocol."},{"versions":["v13.4.0","v12.16.0"],"prUrl":"https://github.com/nodejs/node/pull/30559","commit":null,"description":"The `argv` option was introduced."},{"versions":["v13.2.0","v12.16.0"],"prUrl":"https://github.com/nodejs/node/pull/26628","commit":null,"description":"The `resourceLimits` option was introduced."}],"signature":{"parameters":[{"name":"filename","type":{"text":"string | URL","links":[{"name":"string","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#string_type","start":0,"end":6},{"name":"URL","href":"url.html#the-whatwg-url-api","start":9,"end":12}]},"description":"The path to the Worker's main script or module. Must\nbe either an absolute path or a relative path (i.e. relative to the\ncurrent working directory) starting with `./` or `../`, or a WHATWG `URL`\nobject using `file:` or `data:` protocol.\nWhen using a [`data:` URL](https://developer.mozilla.org/en-US/docs/Web/URI/Reference/Schemes/data), the data is interpreted based on MIME type using\nthe [ECMAScript module loader](esm.html#data-imports).\nIf `options.eval` is `true`, this is a string containing JavaScript code\nrather than a path.","default":null,"optional":false,"rest":false,"properties":[]},{"name":"options","type":{"text":"Object","links":[{"name":"Object","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object","start":0,"end":6}]},"description":"","default":null,"optional":true,"rest":false,"properties":[{"name":"argv","type":{"text":"any[]","links":[{"name":"any","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types","start":0,"end":3}]},"description":"List of arguments which would be stringified and appended to\n`process.argv` in the worker. This is mostly similar to the `workerData`\nbut the values are available on the global `process.argv` as if they\nwere passed as CLI options to the script.","default":null,"optional":false,"rest":false,"properties":[]},{"name":"env","type":{"text":"Object","links":[{"name":"Object","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object","start":0,"end":6}]},"description":"If set, specifies the initial value of `process.env` inside\nthe Worker thread. As a special value, [`worker.SHARE_ENV`](#worker_threadsshare_env) may be used\nto specify that the parent thread and the child thread should share their\nenvironment variables; in that case, changes to one thread's `process.env`\nobject affect the other thread as well.","default":"process.env","optional":true,"rest":false,"properties":[]},{"name":"eval","type":{"text":"boolean","links":[{"name":"boolean","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#boolean_type","start":0,"end":7}]},"description":"If `true` and the first argument is a `string`, interpret\nthe first argument to the constructor as a script that is executed once the\nworker is online.","default":null,"optional":false,"rest":false,"properties":[]},{"name":"execArgv","type":{"text":"string[]","links":[{"name":"string","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#string_type","start":0,"end":6}]},"description":"List of node CLI options passed to the worker.\nV8 options (such as `--max-old-space-size`) and options that affect the\nprocess (such as `--title`) are not supported. If set, this is provided\nas [`process.execArgv`](process.html#processexecargv) inside the worker. By default, options are\ninherited from the parent thread.","default":null,"optional":false,"rest":false,"properties":[]},{"name":"stdin","type":{"text":"boolean","links":[{"name":"boolean","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#boolean_type","start":0,"end":7}]},"description":"If this is set to `true`, then `worker.stdin`\nprovides a writable stream whose contents appear as `process.stdin`\ninside the Worker. By default, no data is provided.","default":null,"optional":false,"rest":false,"properties":[]},{"name":"stdout","type":{"text":"boolean","links":[{"name":"boolean","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#boolean_type","start":0,"end":7}]},"description":"If this is set to `true`, then `worker.stdout` is\nnot automatically piped through to `process.stdout` in the parent.","default":null,"optional":false,"rest":false,"properties":[]},{"name":"stderr","type":{"text":"boolean","links":[{"name":"boolean","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#boolean_type","start":0,"end":7}]},"description":"If this is set to `true`, then `worker.stderr` is\nnot automatically piped through to `process.stderr` in the parent.","default":null,"optional":false,"rest":false,"properties":[]},{"name":"workerData","type":{"text":"any","links":[{"name":"any","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types","start":0,"end":3}]},"description":"Any JavaScript value that is cloned and made\navailable as [`require('node:worker_threads').workerData`](#worker_threadsworkerdata). The cloning\noccurs as described in the [HTML structured clone algorithm](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm), and an error\nis thrown if the object cannot be cloned (e.g. because it contains\n`function`s).","default":null,"optional":false,"rest":false,"properties":[]},{"name":"trackUnmanagedFds","type":{"text":"boolean","links":[{"name":"boolean","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#boolean_type","start":0,"end":7}]},"description":"If this is set to `true`, then the Worker\ntracks raw file descriptors managed through [`fs.open()`](fs.html#fsopenpath-flags-mode-callback) and\n[`fs.close()`](fs.html#fsclosefd-callback), and closes them when the Worker exits, similar to other\nresources like network sockets or file descriptors managed through\nthe [`FileHandle`](fs.html#class-filehandle) API. This option is automatically inherited by all\nnested `Worker`s.","default":"true","optional":true,"rest":false,"properties":[]},{"name":"transferList","type":{"text":"Object[]","links":[{"name":"Object","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object","start":0,"end":6}]},"description":"If one or more `MessagePort`-like objects\nare passed in `workerData`, a `transferList` is required for those\nitems or [`ERR_MISSING_MESSAGE_PORT_IN_TRANSFER_LIST`](errors.html#err_missing_message_port_in_transfer_list) is thrown.\nSee [`port.postMessage()`](#portpostmessagevalue-transferlist) for more information.","default":null,"optional":false,"rest":false,"properties":[]},{"name":"resourceLimits","type":{"text":"Object","links":[{"name":"Object","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object","start":0,"end":6}]},"description":"An optional set of resource limits for the new JS\nengine instance. Reaching these limits leads to termination of the `Worker`\ninstance. These limits only affect the JS engine, and no external data,\nincluding no `ArrayBuffer`s. Even if these limits are set, the process may\nstill abort if it encounters a global out-of-memory situation.","default":null,"optional":false,"rest":false,"properties":[{"name":"maxOldGenerationSizeMb","type":{"text":"number","links":[{"name":"number","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#number_type","start":0,"end":6}]},"description":"The maximum size of the main heap in\nMB. If the command-line argument [`--max-old-space-size`](cli.html#--max-old-space-sizesize-in-mib) is set, it\noverrides this setting.","default":null,"optional":false,"rest":false,"properties":[]},{"name":"maxYoungGenerationSizeMb","type":{"text":"number","links":[{"name":"number","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#number_type","start":0,"end":6}]},"description":"The maximum size of a heap space for\nrecently created objects. If the command-line argument\n[`--max-semi-space-size`](cli.html#--max-semi-space-sizesize-in-mib) is set, it overrides this setting.","default":null,"optional":false,"rest":false,"properties":[]},{"name":"codeRangeSizeMb","type":{"text":"number","links":[{"name":"number","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#number_type","start":0,"end":6}]},"description":"The size of a pre-allocated memory range\nused for generated code.","default":null,"optional":false,"rest":false,"properties":[]},{"name":"stackSizeMb","type":{"text":"number","links":[{"name":"number","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#number_type","start":0,"end":6}]},"description":"The default maximum stack size for the thread.\nSmall values may lead to unusable Worker instances.","default":"4","optional":true,"rest":false,"properties":[]}]},{"name":"name","type":{"text":"string","links":[{"name":"string","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#string_type","start":0,"end":6}]},"description":"An optional `name` to be replaced in the thread name\nand to the worker title for debugging/identification purposes,\nmaking the final title as `[worker ${id}] ${name}`.\nThis parameter has a maximum allowed size, depending on the operating\nsystem. If the provided name exceeds the limit, it will be truncated\n\n* Maximum sizes:\n  * Windows: 32,767 characters\n  * macOS: 64 characters\n  * Linux: 16 characters\n  * NetBSD: limited to `PTHREAD_MAX_NAMELEN_NP`\n  * FreeBSD and OpenBSD: limited to `MAXCOMLEN`\n    **Default:** `'WorkerThread'`.","default":null,"optional":false,"rest":false,"properties":[]}]}],"returns":null},"description":"","summary":"","examples":[],"children":[]},{"kind":"event","id":"event-error","name":"error","title":"Event: `'error'`","scope":"module","overloadOf":null,"stability":null,"added":["v10.5.0"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"parameters":[{"name":"err","type":{"text":"any","links":[{"name":"any","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types","start":0,"end":3}]},"description":"","default":null,"optional":false,"rest":false,"properties":[]}],"description":"The `'error'` event is emitted if the worker thread throws an uncaught\nexception. In that case, the worker is terminated.","summary":"The `'error'` event is emitted if the worker thread throws an uncaught exception. In that case, the worker is terminated.","examples":[],"children":[]},{"kind":"event","id":"event-exit","name":"exit","title":"Event: `'exit'`","scope":"module","overloadOf":null,"stability":null,"added":["v10.5.0"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"parameters":[{"name":"exitCode","type":{"text":"integer","links":[{"name":"integer","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#number_type","start":0,"end":7}]},"description":"","default":null,"optional":false,"rest":false,"properties":[]}],"description":"The `'exit'` event is emitted once the worker has stopped. If the worker\nexited by calling [`process.exit()`](process.html#processexitcode), the `exitCode` parameter is the\npassed exit code. If the worker was terminated, the `exitCode` parameter is\n`1`.\n\nThis is the final event emitted by any `Worker` instance.","summary":"The `'exit'` event is emitted once the worker has stopped. If the worker exited by calling `process.exit()`, the `exitCode` parameter is the passed exit code. If the worker was terminated, the `exitCode` parameter is `1`.","examples":[],"children":[]},{"kind":"event","id":"event-message-1","name":"message","title":"Event: `'message'`","scope":"module","overloadOf":null,"stability":null,"added":["v10.5.0"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"parameters":[{"name":"value","type":{"text":"any","links":[{"name":"any","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types","start":0,"end":3}]},"description":"The transmitted value","default":null,"optional":false,"rest":false,"properties":[]}],"description":"The `'message'` event is emitted when the worker thread has invoked\n[`require('node:worker_threads').parentPort.postMessage()`](#workerpostmessagevalue-transferlist).\nSee the [`port.on('message')`](#event-message) event for more details.\n\nAll messages sent from the worker thread are emitted before the\n[`'exit'` event](#event-exit) is emitted on the `Worker` object.","summary":"The `'message'` event is emitted when the worker thread has invoked `require('node:worker_threads').parentPort.postMessage()`. See the `port.on('message')` event for more details.","examples":[],"children":[]},{"kind":"event","id":"event-messageerror-1","name":"messageerror","title":"Event: `'messageerror'`","scope":"module","overloadOf":null,"stability":null,"added":["v14.5.0","v12.19.0"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"parameters":[{"name":"error","type":{"text":"Error","links":[{"name":"Error","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Error","start":0,"end":5}]},"description":"An Error object","default":null,"optional":false,"rest":false,"properties":[]}],"description":"The `'messageerror'` event is emitted when deserializing a message failed.","summary":"The `'messageerror'` event is emitted when deserializing a message failed.","examples":[],"children":[]},{"kind":"event","id":"event-online","name":"online","title":"Event: `'online'`","scope":"module","overloadOf":null,"stability":null,"added":["v10.5.0"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"parameters":[],"description":"The `'online'` event is emitted when the worker thread has started executing\nJavaScript code.","summary":"The `'online'` event is emitted when the worker thread has started executing JavaScript code.","examples":[],"children":[]},{"kind":"method","id":"workercpuusageprev","name":"cpuUsage","title":"`worker.cpuUsage([prev])`","scope":"module","overloadOf":null,"stability":null,"added":["v24.6.0","v22.19.0"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"signature":{"parameters":[{"name":"prev","type":null,"description":"","default":null,"optional":true,"rest":false,"properties":[]}],"returns":{"type":{"text":"Promise","links":[{"name":"Promise","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise","start":0,"end":7}]},"description":""}},"description":"This method returns a `Promise` that will resolve to an object identical to [`process.threadCpuUsage()`](process.html#processthreadcpuusagepreviousvalue),\nor reject with an [`ERR_WORKER_NOT_RUNNING`](errors.html#err_worker_not_running) error if the worker is no longer running.\nThis methods allows the statistics to be observed from outside the actual thread.","summary":"This method returns a `Promise` that will resolve to an object identical to `process.threadCpuUsage()`, or reject with an `ERR_WORKER_NOT_RUNNING` error if the worker is no longer running. This methods allows the statistics to be observed from outside the actual thread.","examples":[],"children":[]},{"kind":"method","id":"workergetheapsnapshotoptions","name":"getHeapSnapshot","title":"`worker.getHeapSnapshot([options])`","scope":"module","overloadOf":null,"stability":null,"added":["v13.9.0","v12.17.0"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[{"versions":["v19.1.0"],"prUrl":"https://github.com/nodejs/node/pull/44989","commit":null,"description":"Support options to configure the heap snapshot."}],"signature":{"parameters":[{"name":"options","type":{"text":"Object","links":[{"name":"Object","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object","start":0,"end":6}]},"description":"","default":null,"optional":true,"rest":false,"properties":[{"name":"exposeInternals","type":{"text":"boolean","links":[{"name":"boolean","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#boolean_type","start":0,"end":7}]},"description":"If true, expose internals in the heap snapshot.","default":"false","optional":true,"rest":false,"properties":[]},{"name":"exposeNumericValues","type":{"text":"boolean","links":[{"name":"boolean","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#boolean_type","start":0,"end":7}]},"description":"If true, expose numeric values in\nartificial fields.","default":"false","optional":true,"rest":false,"properties":[]}]}],"returns":{"type":{"text":"Promise","links":[{"name":"Promise","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise","start":0,"end":7}]},"description":"A promise for a Readable Stream containing\na V8 heap snapshot"}},"description":"Returns a readable stream for a V8 snapshot of the current state of the Worker.\nSee [`v8.getHeapSnapshot()`](v8.html#v8getheapsnapshotoptions) for more details.\n\nIf the Worker thread is no longer running, which may occur before the\n[`'exit'` event](#event-exit) is emitted, the returned `Promise` is rejected\nimmediately with an [`ERR_WORKER_NOT_RUNNING`](errors.html#err_worker_not_running) error.","summary":"Returns a readable stream for a V8 snapshot of the current state of the Worker. See `v8.getHeapSnapshot()` for more details.","examples":[],"children":[]},{"kind":"method","id":"workergetheapstatistics","name":"getHeapStatistics","title":"`worker.getHeapStatistics()`","scope":"module","overloadOf":null,"stability":null,"added":["v24.0.0","v22.16.0"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"signature":{"parameters":[],"returns":{"type":{"text":"Promise","links":[{"name":"Promise","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise","start":0,"end":7}]},"description":""}},"description":"This method returns a `Promise` that will resolve to an object identical to [`v8.getHeapStatistics()`](v8.html#v8getheapstatistics),\nor reject with an [`ERR_WORKER_NOT_RUNNING`](errors.html#err_worker_not_running) error if the worker is no longer running.\nThis methods allows the statistics to be observed from outside the actual thread.","summary":"This method returns a `Promise` that will resolve to an object identical to `v8.getHeapStatistics()`, or reject with an `ERR_WORKER_NOT_RUNNING` error if the worker is no longer running. This methods allows the statistics to be observed from outside the actual thread.","examples":[],"children":[]},{"kind":"property","id":"workerperformance","name":"performance","title":"`worker.performance`","scope":"module","overloadOf":null,"stability":null,"added":["v15.1.0","v14.17.0","v12.22.0"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"type":null,"default":null,"description":"An object that can be used to query performance information from a worker\ninstance.","summary":"An object that can be used to query performance information from a worker instance.","examples":[],"children":[{"kind":"method","id":"performanceeventlooputilizationutilization1-utilization2","name":"eventLoopUtilization","title":"`performance.eventLoopUtilization([utilization1[, utilization2]])`","scope":"module","overloadOf":null,"stability":null,"added":["v15.1.0","v14.17.0","v12.22.0"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"signature":{"parameters":[{"name":"utilization1","type":{"text":"Object","links":[{"name":"Object","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object","start":0,"end":6}]},"description":"The result of a previous call to\n`eventLoopUtilization()`.","default":null,"optional":true,"rest":false,"properties":[]},{"name":"utilization2","type":{"text":"Object","links":[{"name":"Object","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object","start":0,"end":6}]},"description":"The result of a previous call to\n`eventLoopUtilization()` prior to `utilization1`.","default":null,"optional":true,"rest":false,"properties":[]}],"returns":{"type":{"text":"Object","links":[{"name":"Object","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object","start":0,"end":6}]},"description":""}},"description":"The same call as [`perf_hooks` `eventLoopUtilization()`](perf_hooks.html#perf_hookseventlooputilizationutilization1-utilization2), except the values\nof the worker instance are returned.\n\nOne difference is that, unlike the main thread, bootstrapping within a worker\nis done within the event loop. So the event loop utilization is\nimmediately available once the worker's script begins execution.\n\nAn `idle` time that does not increase does not indicate that the worker is\nstuck in bootstrap. The following example shows how the worker's entire\nlifetime never accumulates any `idle` time, but is still able to process\nmessages.\n\n```mjs\nimport { Worker, isMainThread, parentPort } from 'node:worker_threads';\n\nif (isMainThread) {\n  const worker = new Worker(new URL(import.meta.url));\n  setInterval(() => {\n    worker.postMessage('hi');\n    console.log(worker.performance.eventLoopUtilization());\n  }, 100).unref();\n} else {\n  parentPort.on('message', () => console.log('msg')).unref();\n  (function r(n) {\n    if (--n < 0) return;\n    const t = Date.now();\n    while (Date.now() - t < 300);\n    setImmediate(r, n);\n  })(10);\n}\n```\n\n```cjs\nconst { Worker, isMainThread, parentPort } = require('node:worker_threads');\n\nif (isMainThread) {\n  const worker = new Worker(__filename);\n  setInterval(() => {\n    worker.postMessage('hi');\n    console.log(worker.performance.eventLoopUtilization());\n  }, 100).unref();\n} else {\n  parentPort.on('message', () => console.log('msg')).unref();\n  (function r(n) {\n    if (--n < 0) return;\n    const t = Date.now();\n    while (Date.now() - t < 300);\n    setImmediate(r, n);\n  })(10);\n}\n```\n\nThe event loop utilization of a worker is available only after the [`'online'`\nevent](#event-online) emitted, and if called before this, or after the [`'exit'`\nevent](#event-exit), then all properties have the value of `0`.","summary":"The same call as `perf_hooks` `eventLoopUtilization()`, except the values of the worker instance are returned.","examples":[{"language":"mjs","displayName":null,"code":"import { Worker, isMainThread, parentPort } from 'node:worker_threads';\n\nif (isMainThread) {\n  const worker = new Worker(new URL(import.meta.url));\n  setInterval(() => {\n    worker.postMessage('hi');\n    console.log(worker.performance.eventLoopUtilization());\n  }, 100).unref();\n} else {\n  parentPort.on('message', () => console.log('msg')).unref();\n  (function r(n) {\n    if (--n < 0) return;\n    const t = Date.now();\n    while (Date.now() - t < 300);\n    setImmediate(r, n);\n  })(10);\n}"},{"language":"cjs","displayName":null,"code":"const { Worker, isMainThread, parentPort } = require('node:worker_threads');\n\nif (isMainThread) {\n  const worker = new Worker(__filename);\n  setInterval(() => {\n    worker.postMessage('hi');\n    console.log(worker.performance.eventLoopUtilization());\n  }, 100).unref();\n} else {\n  parentPort.on('message', () => console.log('msg')).unref();\n  (function r(n) {\n    if (--n < 0) return;\n    const t = Date.now();\n    while (Date.now() - t < 300);\n    setImmediate(r, n);\n  })(10);\n}"}],"children":[]}]},{"kind":"method","id":"workerpostmessagevalue-transferlist","name":"postMessage","title":"`worker.postMessage(value[, transferList])`","scope":"module","overloadOf":null,"stability":null,"added":["v10.5.0"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"signature":{"parameters":[{"name":"value","type":{"text":"any","links":[{"name":"any","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types","start":0,"end":3}]},"description":"","default":null,"optional":false,"rest":false,"properties":[]},{"name":"transferList","type":{"text":"Object[]","links":[{"name":"Object","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object","start":0,"end":6}]},"description":"","default":null,"optional":true,"rest":false,"properties":[]}],"returns":null},"description":"Send a message to the worker that is received via\n[`require('node:worker_threads').parentPort.on('message')`](#event-message).\nSee [`port.postMessage()`](#portpostmessagevalue-transferlist) for more details.","summary":"Send a message to the worker that is received via `require('node:worker_threads').parentPort.on('message')`. See `port.postMessage()` for more details.","examples":[],"children":[]},{"kind":"method","id":"workerref","name":"ref","title":"`worker.ref()`","scope":"module","overloadOf":null,"stability":null,"added":["v10.5.0"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"signature":{"parameters":[],"returns":null},"description":"Opposite of `unref()`, calling `ref()` on a previously `unref()`ed worker does\n*not* let the program exit if it's the only active handle left (the default\nbehavior). If the worker is `ref()`ed, calling `ref()` again has\nno effect.","summary":"Opposite of `unref()`, calling `ref()` on a previously `unref()`ed worker does _not_ let the program exit if it's the only active handle left (the default behavior). If the worker is `ref()`ed, calling `ref()` again has no effect.","examples":[],"children":[]},{"kind":"property","id":"workerresourcelimits","name":"resourceLimits","title":"`worker.resourceLimits`","scope":"module","overloadOf":null,"stability":null,"added":["v13.2.0","v12.16.0"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"type":{"text":"Object","links":[{"name":"Object","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object","start":0,"end":6}]},"default":null,"description":"Provides the set of JS engine resource constraints for this Worker thread.\nIf the `resourceLimits` option was passed to the [`Worker`](#class-worker) constructor,\nthis matches its values.\n\nIf the worker has stopped, the return value is an empty object.","summary":"Provides the set of JS engine resource constraints for this Worker thread. If the `resourceLimits` option was passed to the `Worker` constructor, this matches its values.","examples":[],"children":[]},{"kind":"method","id":"workerstartcpuprofileoptions","name":"startCpuProfile","title":"`worker.startCpuProfile([options])`","scope":"module","overloadOf":null,"stability":null,"added":["v24.8.0"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"signature":{"parameters":[{"name":"options","type":{"text":"Object","links":[{"name":"Object","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object","start":0,"end":6}]},"description":"","default":null,"optional":true,"rest":false,"properties":[{"name":"sampleInterval","type":{"text":"number","links":[{"name":"number","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#number_type","start":0,"end":6}]},"description":"Requested sampling interval in milliseconds.","default":"0","optional":true,"rest":false,"properties":[]},{"name":"maxBufferSize","type":{"text":"integer","links":[{"name":"integer","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#number_type","start":0,"end":7}]},"description":"Maximum number of samples to retain.","default":"4294967295","optional":true,"rest":false,"properties":[]}]}],"returns":{"type":{"text":"Promise","links":[{"name":"Promise","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise","start":0,"end":7}]},"description":""}},"description":"Starting a CPU profile then return a Promise that fulfills with an error\nor an `CPUProfileHandle` object. This API supports `await using` syntax.\n\n```cjs\nconst { Worker } = require('node:worker_threads');\n\nconst worker = new Worker(`\n  const { parentPort } = require('worker_threads');\n  parentPort.on('message', () => {});\n  `, { eval: true });\n\nworker.on('online', async () => {\n  const handle = await worker.startCpuProfile({ sampleInterval: 1 });\n  const profile = await handle.stop();\n  console.log(profile);\n  worker.terminate();\n});\n```\n\n`await using` example.\n\n```cjs\nconst { Worker } = require('node:worker_threads');\n\nconst w = new Worker(`\n  const { parentPort } = require('node:worker_threads');\n  parentPort.on('message', () => {});\n  `, { eval: true });\n\nw.on('online', async () => {\n  // Stop profile automatically when return and profile will be discarded\n  await using handle = await w.startCpuProfile();\n});\n```","summary":"Starting a CPU profile then return a Promise that fulfills with an error or an `CPUProfileHandle` object. This API supports `await using` syntax.","examples":[{"language":"cjs","displayName":null,"code":"const { Worker } = require('node:worker_threads');\n\nconst worker = new Worker(`\n  const { parentPort } = require('worker_threads');\n  parentPort.on('message', () => {});\n  `, { eval: true });\n\nworker.on('online', async () => {\n  const handle = await worker.startCpuProfile({ sampleInterval: 1 });\n  const profile = await handle.stop();\n  console.log(profile);\n  worker.terminate();\n});"},{"language":"cjs","displayName":null,"code":"const { Worker } = require('node:worker_threads');\n\nconst w = new Worker(`\n  const { parentPort } = require('node:worker_threads');\n  parentPort.on('message', () => {});\n  `, { eval: true });\n\nw.on('online', async () => {\n  // Stop profile automatically when return and profile will be discarded\n  await using handle = await w.startCpuProfile();\n});"}],"children":[]},{"kind":"method","id":"workerstartheapprofileoptions","name":"startHeapProfile","title":"`worker.startHeapProfile([options])`","scope":"module","overloadOf":null,"stability":null,"added":["v24.9.0","v22.20.0"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"signature":{"parameters":[{"name":"options","type":{"text":"Object","links":[{"name":"Object","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object","start":0,"end":6}]},"description":"","default":null,"optional":true,"rest":false,"properties":[{"name":"sampleInterval","type":{"text":"number","links":[{"name":"number","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#number_type","start":0,"end":6}]},"description":"The average sampling interval in bytes.","default":"`524288` (512 KiB)","optional":true,"rest":false,"properties":[]},{"name":"stackDepth","type":{"text":"integer","links":[{"name":"integer","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#number_type","start":0,"end":7}]},"description":"The maximum stack depth for samples.","default":"16","optional":true,"rest":false,"properties":[]},{"name":"forceGC","type":{"text":"boolean","links":[{"name":"boolean","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#boolean_type","start":0,"end":7}]},"description":"Force garbage collection before taking the profile.","default":"false","optional":true,"rest":false,"properties":[]},{"name":"includeObjectsCollectedByMajorGC","type":{"text":"boolean","links":[{"name":"boolean","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#boolean_type","start":0,"end":7}]},"description":"Include objects collected\nby major GC.","default":"false","optional":true,"rest":false,"properties":[]},{"name":"includeObjectsCollectedByMinorGC","type":{"text":"boolean","links":[{"name":"boolean","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#boolean_type","start":0,"end":7}]},"description":"Include objects collected\nby minor GC.","default":"false","optional":true,"rest":false,"properties":[]}]}],"returns":{"type":{"text":"Promise","links":[{"name":"Promise","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise","start":0,"end":7}]},"description":""}},"description":"Starting a Heap profile then return a Promise that fulfills with an error\nor an `HeapProfileHandle` object. This API supports `await using` syntax.\n\n```cjs\nconst { Worker } = require('node:worker_threads');\n\nconst worker = new Worker(`\n  const { parentPort } = require('worker_threads');\n  parentPort.on('message', () => {});\n  `, { eval: true });\n\nworker.on('online', async () => {\n  const handle = await worker.startHeapProfile();\n  const profile = await handle.stop();\n  console.log(profile);\n  worker.terminate();\n});\n```\n\n```mjs\nimport { Worker } from 'node:worker_threads';\n\nconst worker = new Worker(`\n  const { parentPort } = require('node:worker_threads');\n  parentPort.on('message', () => {});\n  `, { eval: true });\n\nworker.on('online', async () => {\n  const handle = await worker.startHeapProfile();\n  const profile = await handle.stop();\n  console.log(profile);\n  worker.terminate();\n});\n```\n\n`await using` example.\n\n```cjs\nconst { Worker } = require('node:worker_threads');\n\nconst w = new Worker(`\n  const { parentPort } = require('node:worker_threads');\n  parentPort.on('message', () => {});\n  `, { eval: true });\n\nw.on('online', async () => {\n  // Stop profile automatically when return and profile will be discarded\n  await using handle = await w.startHeapProfile();\n});\n```\n\n```mjs\nimport { Worker } from 'node:worker_threads';\n\nconst w = new Worker(`\n  const { parentPort } = require('node:worker_threads');\n  parentPort.on('message', () => {});\n  `, { eval: true });\n\nw.on('online', async () => {\n  // Stop profile automatically when return and profile will be discarded\n  await using handle = await w.startHeapProfile();\n});\n```","summary":"Starting a Heap profile then return a Promise that fulfills with an error or an `HeapProfileHandle` object. This API supports `await using` syntax.","examples":[{"language":"cjs","displayName":null,"code":"const { Worker } = require('node:worker_threads');\n\nconst worker = new Worker(`\n  const { parentPort } = require('worker_threads');\n  parentPort.on('message', () => {});\n  `, { eval: true });\n\nworker.on('online', async () => {\n  const handle = await worker.startHeapProfile();\n  const profile = await handle.stop();\n  console.log(profile);\n  worker.terminate();\n});"},{"language":"mjs","displayName":null,"code":"import { Worker } from 'node:worker_threads';\n\nconst worker = new Worker(`\n  const { parentPort } = require('node:worker_threads');\n  parentPort.on('message', () => {});\n  `, { eval: true });\n\nworker.on('online', async () => {\n  const handle = await worker.startHeapProfile();\n  const profile = await handle.stop();\n  console.log(profile);\n  worker.terminate();\n});"},{"language":"cjs","displayName":null,"code":"const { Worker } = require('node:worker_threads');\n\nconst w = new Worker(`\n  const { parentPort } = require('node:worker_threads');\n  parentPort.on('message', () => {});\n  `, { eval: true });\n\nw.on('online', async () => {\n  // Stop profile automatically when return and profile will be discarded\n  await using handle = await w.startHeapProfile();\n});"},{"language":"mjs","displayName":null,"code":"import { Worker } from 'node:worker_threads';\n\nconst w = new Worker(`\n  const { parentPort } = require('node:worker_threads');\n  parentPort.on('message', () => {});\n  `, { eval: true });\n\nw.on('online', async () => {\n  // Stop profile automatically when return and profile will be discarded\n  await using handle = await w.startHeapProfile();\n});"}],"children":[]},{"kind":"property","id":"workerstderr","name":"stderr","title":"`worker.stderr`","scope":"module","overloadOf":null,"stability":null,"added":["v10.5.0"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"type":{"text":"stream.Readable","links":[{"name":"stream.Readable","href":"stream.html#class-streamreadable","start":0,"end":15}]},"default":null,"description":"This is a readable stream which contains data written to [`process.stderr`](process.html#processstderr)\ninside the worker thread. If `stderr: true` was not passed to the\n[`Worker`](#class-worker) constructor, then data is piped to the parent thread's\n[`process.stderr`](process.html#processstderr) stream.","summary":"This is a readable stream which contains data written to `process.stderr` inside the worker thread. If `stderr: true` was not passed to the `Worker` constructor, then data is piped to the parent thread's `process.stderr` stream.","examples":[],"children":[]},{"kind":"property","id":"workerstdin","name":"stdin","title":"`worker.stdin`","scope":"module","overloadOf":null,"stability":null,"added":["v10.5.0"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"type":{"text":"null | stream.Writable","links":[{"name":"null","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#null_type","start":0,"end":4},{"name":"stream.Writable","href":"stream.html#class-streamwritable","start":7,"end":22}]},"default":null,"description":"If `stdin: true` was passed to the [`Worker`](#class-worker) constructor, this is a\nwritable stream. The data written to this stream will be made available in\nthe worker thread as [`process.stdin`](process.html#processstdin).","summary":"If `stdin: true` was passed to the `Worker` constructor, this is a writable stream. The data written to this stream will be made available in the worker thread as `process.stdin`.","examples":[],"children":[]},{"kind":"property","id":"workerstdout","name":"stdout","title":"`worker.stdout`","scope":"module","overloadOf":null,"stability":null,"added":["v10.5.0"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"type":{"text":"stream.Readable","links":[{"name":"stream.Readable","href":"stream.html#class-streamreadable","start":0,"end":15}]},"default":null,"description":"This is a readable stream which contains data written to [`process.stdout`](process.html#processstdout)\ninside the worker thread. If `stdout: true` was not passed to the\n[`Worker`](#class-worker) constructor, then data is piped to the parent thread's\n[`process.stdout`](process.html#processstdout) stream.","summary":"This is a readable stream which contains data written to `process.stdout` inside the worker thread. If `stdout: true` was not passed to the `Worker` constructor, then data is piped to the parent thread's `process.stdout` stream.","examples":[],"children":[]},{"kind":"method","id":"workerterminate","name":"terminate","title":"`worker.terminate()`","scope":"module","overloadOf":null,"stability":null,"added":["v10.5.0"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[{"versions":["v12.5.0"],"prUrl":"https://github.com/nodejs/node/pull/28021","commit":null,"description":"This function now returns a Promise. Passing a callback is deprecated, and was useless up to this version, as the Worker was actually terminated synchronously. Terminating is now a fully asynchronous operation."}],"signature":{"parameters":[],"returns":{"type":{"text":"Promise","links":[{"name":"Promise","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise","start":0,"end":7}]},"description":""}},"description":"Stop all JavaScript execution in the worker thread as soon as possible.\nReturns a Promise for the exit code that is fulfilled when the\n[`'exit'` event](#event-exit) is emitted.","summary":"Stop all JavaScript execution in the worker thread as soon as possible. Returns a Promise for the exit code that is fulfilled when the `'exit'` event is emitted.","examples":[],"children":[]},{"kind":"property","id":"workerthreadid","name":"threadId","title":"`worker.threadId`","scope":"module","overloadOf":null,"stability":null,"added":["v10.5.0"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"type":{"text":"integer","links":[{"name":"integer","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#number_type","start":0,"end":7}]},"default":null,"description":"An integer identifier for the referenced thread. Inside the worker thread,\nit is available as [`require('node:worker_threads').threadId`](#worker_threadsthreadid).\nThis value is unique for each `Worker` instance inside a single process.","summary":"An integer identifier for the referenced thread. Inside the worker thread, it is available as `require('node:worker_threads').threadId`. This value is unique for each `Worker` instance inside a single process.","examples":[],"children":[]},{"kind":"property","id":"workerthreadname","name":"threadName","title":"`worker.threadName`","scope":"module","overloadOf":null,"stability":null,"added":["v24.6.0","v22.20.0"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"type":{"text":"string | null","links":[{"name":"string","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#string_type","start":0,"end":6},{"name":"null","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#null_type","start":9,"end":13}]},"default":null,"description":"A string identifier for the referenced thread or null if the thread is not running.\nInside the worker thread, it is available as [`require('node:worker_threads').threadName`](#worker_threadsthreadname).","summary":"A string identifier for the referenced thread or null if the thread is not running. Inside the worker thread, it is available as `require('node:worker_threads').threadName`.","examples":[],"children":[]},{"kind":"method","id":"workerunref","name":"unref","title":"`worker.unref()`","scope":"module","overloadOf":null,"stability":null,"added":["v10.5.0"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"signature":{"parameters":[],"returns":null},"description":"Calling `unref()` on a worker allows the thread to exit if this is the only\nactive handle in the event system. If the worker is already `unref()`ed calling\n`unref()` again has no effect.","summary":"Calling `unref()` on a worker allows the thread to exit if this is the only active handle in the event system. If the worker is already `unref()`ed calling `unref()` again has no effect.","examples":[],"children":[]},{"kind":"method","id":"workersymbolasyncdispose","name":"[Symbol.asyncDispose]","title":"`worker[Symbol.asyncDispose]()`","scope":"module","overloadOf":null,"stability":null,"added":["v24.2.0","v22.18.0"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"signature":{"parameters":[],"returns":null},"description":"Calls [`worker.terminate()`](#workerterminate) when the dispose scope is exited.\n\n```js\nasync function example() {\n  await using worker = new Worker('for (;;) {}', { eval: true });\n  // Worker is automatically terminate when the scope is exited.\n}\n```","summary":"Calls `worker.terminate()` when the dispose scope is exited.","examples":[{"language":"js","displayName":null,"code":"async function example() {\n  await using worker = new Worker('for (;;) {}', { eval: true });\n  // Worker is automatically terminate when the scope is exited.\n}"}],"children":[]}]},{"kind":"section","id":"notes","name":"Notes","title":"Notes","scope":"module","overloadOf":null,"stability":null,"added":[],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"description":"","summary":"","examples":[],"children":[{"kind":"section","id":"synchronous-blocking-of-stdio","name":"Synchronous blocking of stdio","title":"Synchronous blocking of stdio","scope":"module","overloadOf":null,"stability":null,"added":[],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"description":"`Worker`s utilize message passing via {MessagePort} to implement interactions\nwith `stdio`. This means that `stdio` output originating from a `Worker` can\nget blocked by synchronous code on the receiving end that is blocking the\nNode.js event loop.\n\n```mjs\nimport {\n  Worker,\n  isMainThread,\n} from 'node:worker_threads';\n\nif (isMainThread) {\n  new Worker(new URL(import.meta.url));\n  for (let n = 0; n < 1e10; n++) {\n    // Looping to simulate work.\n  }\n} else {\n  // This output will be blocked by the for loop in the main thread.\n  console.log('foo');\n}\n```\n\n```cjs\nconst {\n  Worker,\n  isMainThread,\n} = require('node:worker_threads');\n\nif (isMainThread) {\n  new Worker(__filename);\n  for (let n = 0; n < 1e10; n++) {\n    // Looping to simulate work.\n  }\n} else {\n  // This output will be blocked by the for loop in the main thread.\n  console.log('foo');\n}\n```","summary":"`Worker`s utilize message passing via {MessagePort} to implement interactions with `stdio`. This means that `stdio` output originating from a `Worker` can get blocked by synchronous code on the receiving end that is blocking the Node.js event loop.","examples":[{"language":"mjs","displayName":null,"code":"import {\n  Worker,\n  isMainThread,\n} from 'node:worker_threads';\n\nif (isMainThread) {\n  new Worker(new URL(import.meta.url));\n  for (let n = 0; n < 1e10; n++) {\n    // Looping to simulate work.\n  }\n} else {\n  // This output will be blocked by the for loop in the main thread.\n  console.log('foo');\n}"},{"language":"cjs","displayName":null,"code":"const {\n  Worker,\n  isMainThread,\n} = require('node:worker_threads');\n\nif (isMainThread) {\n  new Worker(__filename);\n  for (let n = 0; n < 1e10; n++) {\n    // Looping to simulate work.\n  }\n} else {\n  // This output will be blocked by the for loop in the main thread.\n  console.log('foo');\n}"}],"children":[]},{"kind":"section","id":"launching-worker-threads-from-preload-scripts","name":"Launching worker threads from preload scripts","title":"Launching worker threads from preload scripts","scope":"module","overloadOf":null,"stability":null,"added":[],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"description":"Take care when launching worker threads from preload scripts (scripts loaded\nand run using the `-r` command line flag). Unless the `execArgv` option is\nexplicitly set, new Worker threads automatically inherit the command line flags\nfrom the running process and will preload the same preload scripts as the main\nthread. If the preload script unconditionally launches a worker thread, every\nthread spawned will spawn another until the application crashes.","summary":"Take care when launching worker threads from preload scripts (scripts loaded and run using the `-r` command line flag). Unless the `execArgv` option is explicitly set, new Worker threads automatically inherit the command line flags from the running process and will preload the same preload scripts as the main thread. If the preload script unconditionally launches a worker thread, every thread spawned will spawn another until the application crashes.","examples":[],"children":[]}]}]}