3370933be7d82a90b8daf87719ba0218214174126fc6353868a46672d77304f7da24c6f302ba3b2aacdb982b1abe9c0d0caa14dcb7fa4c8d5331aaa63d5e99 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835
  1. /**
  2. * The `node:worker_threads` module enables the use of threads that execute
  3. * JavaScript in parallel. To access it:
  4. *
  5. * ```js
  6. * import worker from 'node:worker_threads';
  7. * ```
  8. *
  9. * Workers (threads) are useful for performing CPU-intensive JavaScript operations.
  10. * They do not help much with I/O-intensive work. The Node.js built-in
  11. * asynchronous I/O operations are more efficient than Workers can be.
  12. *
  13. * Unlike `child_process` or `cluster`, `worker_threads` can share memory. They do
  14. * so by transferring `ArrayBuffer` instances or sharing `SharedArrayBuffer` instances.
  15. *
  16. * ```js
  17. * import {
  18. * Worker,
  19. * isMainThread,
  20. * parentPort,
  21. * workerData,
  22. * } from 'node:worker_threads';
  23. *
  24. * if (!isMainThread) {
  25. * const { parse } = await import('some-js-parsing-library');
  26. * const script = workerData;
  27. * parentPort.postMessage(parse(script));
  28. * }
  29. *
  30. * export default function parseJSAsync(script) {
  31. * return new Promise((resolve, reject) => {
  32. * const worker = new Worker(new URL(import.meta.url), {
  33. * workerData: script,
  34. * });
  35. * worker.on('message', resolve);
  36. * worker.on('error', reject);
  37. * worker.on('exit', (code) => {
  38. * if (code !== 0)
  39. * reject(new Error(`Worker stopped with exit code ${code}`));
  40. * });
  41. * });
  42. * };
  43. * ```
  44. *
  45. * The above example spawns a Worker thread for each `parseJSAsync()` call. In
  46. * practice, use a pool of Workers for these kinds of tasks. Otherwise, the
  47. * overhead of creating Workers would likely exceed their benefit.
  48. *
  49. * When implementing a worker pool, use the `AsyncResource` API to inform
  50. * diagnostic tools (e.g. to provide asynchronous stack traces) about the
  51. * correlation between tasks and their outcomes. See `"Using AsyncResource for a Worker thread pool"` in the `async_hooks` documentation for an example implementation.
  52. *
  53. * Worker threads inherit non-process-specific options by default. Refer to `Worker constructor options` to know how to customize worker thread options,
  54. * specifically `argv` and `execArgv` options.
  55. * @see [source](https://github.com/nodejs/node/blob/v24.x/lib/worker_threads.js)
  56. */
  57. declare module "worker_threads" {
  58. import { Context } from "node:vm";
  59. import { EventEmitter } from "node:events";
  60. import { EventLoopUtilityFunction } from "node:perf_hooks";
  61. import { FileHandle } from "node:fs/promises";
  62. import { Readable, Writable } from "node:stream";
  63. import { ReadableStream, TransformStream, WritableStream } from "node:stream/web";
  64. import { URL } from "node:url";
  65. import { HeapInfo } from "node:v8";
  66. import { MessageEvent } from "undici-types";
  67. const isInternalThread: boolean;
  68. const isMainThread: boolean;
  69. const parentPort: null | MessagePort;
  70. const resourceLimits: ResourceLimits;
  71. const SHARE_ENV: unique symbol;
  72. const threadId: number;
  73. const workerData: any;
  74. /**
  75. * Instances of the `worker.MessageChannel` class represent an asynchronous,
  76. * two-way communications channel.
  77. * The `MessageChannel` has no methods of its own. `new MessageChannel()` yields an object with `port1` and `port2` properties, which refer to linked `MessagePort` instances.
  78. *
  79. * ```js
  80. * import { MessageChannel } from 'node:worker_threads';
  81. *
  82. * const { port1, port2 } = new MessageChannel();
  83. * port1.on('message', (message) => console.log('received', message));
  84. * port2.postMessage({ foo: 'bar' });
  85. * // Prints: received { foo: 'bar' } from the `port1.on('message')` listener
  86. * ```
  87. * @since v10.5.0
  88. */
  89. class MessageChannel {
  90. readonly port1: MessagePort;
  91. readonly port2: MessagePort;
  92. }
  93. interface WorkerPerformance {
  94. eventLoopUtilization: EventLoopUtilityFunction;
  95. }
  96. type Transferable =
  97. | ArrayBuffer
  98. | MessagePort
  99. | AbortSignal
  100. | FileHandle
  101. | ReadableStream
  102. | WritableStream
  103. | TransformStream;
  104. /** @deprecated Use `import { Transferable } from "node:worker_threads"` instead. */
  105. // TODO: remove in a future major @types/node version.
  106. type TransferListItem = Transferable;
  107. /**
  108. * Instances of the `worker.MessagePort` class represent one end of an
  109. * asynchronous, two-way communications channel. It can be used to transfer
  110. * structured data, memory regions and other `MessagePort`s between different `Worker`s.
  111. *
  112. * This implementation matches [browser `MessagePort`](https://developer.mozilla.org/en-US/docs/Web/API/MessagePort) s.
  113. * @since v10.5.0
  114. */
  115. class MessagePort extends EventEmitter {
  116. /**
  117. * Disables further sending of messages on either side of the connection.
  118. * This method can be called when no further communication will happen over this `MessagePort`.
  119. *
  120. * The `'close' event` is emitted on both `MessagePort` instances that
  121. * are part of the channel.
  122. * @since v10.5.0
  123. */
  124. close(): void;
  125. /**
  126. * Sends a JavaScript value to the receiving side of this channel. `value` is transferred in a way which is compatible with
  127. * the [HTML structured clone algorithm](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm).
  128. *
  129. * In particular, the significant differences to `JSON` are:
  130. *
  131. * * `value` may contain circular references.
  132. * * `value` may contain instances of builtin JS types such as `RegExp`s, `BigInt`s, `Map`s, `Set`s, etc.
  133. * * `value` may contain typed arrays, both using `ArrayBuffer`s
  134. * and `SharedArrayBuffer`s.
  135. * * `value` may contain [`WebAssembly.Module`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/Module) instances.
  136. * * `value` may not contain native (C++-backed) objects other than:
  137. *
  138. * ```js
  139. * import { MessageChannel } from 'node:worker_threads';
  140. * const { port1, port2 } = new MessageChannel();
  141. *
  142. * port1.on('message', (message) => console.log(message));
  143. *
  144. * const circularData = {};
  145. * circularData.foo = circularData;
  146. * // Prints: { foo: [Circular] }
  147. * port2.postMessage(circularData);
  148. * ```
  149. *
  150. * `transferList` may be a list of [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer), `MessagePort`, and `FileHandle` objects.
  151. * After transferring, they are not usable on the sending side of the channel
  152. * anymore (even if they are not contained in `value`). Unlike with `child processes`, transferring handles such as network sockets is currently
  153. * not supported.
  154. *
  155. * If `value` contains [`SharedArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer) instances, those are accessible
  156. * from either thread. They cannot be listed in `transferList`.
  157. *
  158. * `value` may still contain `ArrayBuffer` instances that are not in `transferList`; in that case, the underlying memory is copied rather than moved.
  159. *
  160. * ```js
  161. * import { MessageChannel } from 'node:worker_threads';
  162. * const { port1, port2 } = new MessageChannel();
  163. *
  164. * port1.on('message', (message) => console.log(message));
  165. *
  166. * const uint8Array = new Uint8Array([ 1, 2, 3, 4 ]);
  167. * // This posts a copy of `uint8Array`:
  168. * port2.postMessage(uint8Array);
  169. * // This does not copy data, but renders `uint8Array` unusable:
  170. * port2.postMessage(uint8Array, [ uint8Array.buffer ]);
  171. *
  172. * // The memory for the `sharedUint8Array` is accessible from both the
  173. * // original and the copy received by `.on('message')`:
  174. * const sharedUint8Array = new Uint8Array(new SharedArrayBuffer(4));
  175. * port2.postMessage(sharedUint8Array);
  176. *
  177. * // This transfers a freshly created message port to the receiver.
  178. * // This can be used, for example, to create communication channels between
  179. * // multiple `Worker` threads that are children of the same parent thread.
  180. * const otherChannel = new MessageChannel();
  181. * port2.postMessage({ port: otherChannel.port1 }, [ otherChannel.port1 ]);
  182. * ```
  183. *
  184. * The message object is cloned immediately, and can be modified after
  185. * posting without having side effects.
  186. *
  187. * For more information on the serialization and deserialization mechanisms
  188. * behind this API, see the `serialization API of the node:v8 module`.
  189. * @since v10.5.0
  190. */
  191. postMessage(value: any, transferList?: readonly Transferable[]): void;
  192. /**
  193. * If true, the `MessagePort` object will keep the Node.js event loop active.
  194. * @since v18.1.0, v16.17.0
  195. */
  196. hasRef(): boolean;
  197. /**
  198. * 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
  199. * behavior). If the port is `ref()`ed, calling `ref()` again has no effect.
  200. *
  201. * If listeners are attached or removed using `.on('message')`, the port
  202. * is `ref()`ed and `unref()`ed automatically depending on whether
  203. * listeners for the event exist.
  204. * @since v10.5.0
  205. */
  206. ref(): void;
  207. /**
  208. * Calling `unref()` on a port allows the thread to exit if this is the only
  209. * active handle in the event system. If the port is already `unref()`ed calling `unref()` again has no effect.
  210. *
  211. * If listeners are attached or removed using `.on('message')`, the port is `ref()`ed and `unref()`ed automatically depending on whether
  212. * listeners for the event exist.
  213. * @since v10.5.0
  214. */
  215. unref(): void;
  216. /**
  217. * Starts receiving messages on this `MessagePort`. When using this port
  218. * as an event emitter, this is called automatically once `'message'` listeners are attached.
  219. *
  220. * This method exists for parity with the Web `MessagePort` API. In Node.js,
  221. * it is only useful for ignoring messages when no event listener is present.
  222. * Node.js also diverges in its handling of `.onmessage`. Setting it
  223. * automatically calls `.start()`, but unsetting it lets messages queue up
  224. * until a new handler is set or the port is discarded.
  225. * @since v10.5.0
  226. */
  227. start(): void;
  228. addListener(event: "close", listener: () => void): this;
  229. addListener(event: "message", listener: (value: any) => void): this;
  230. addListener(event: "messageerror", listener: (error: Error) => void): this;
  231. addListener(event: string | symbol, listener: (...args: any[]) => void): this;
  232. emit(event: "close"): boolean;
  233. emit(event: "message", value: any): boolean;
  234. emit(event: "messageerror", error: Error): boolean;
  235. emit(event: string | symbol, ...args: any[]): boolean;
  236. on(event: "close", listener: () => void): this;
  237. on(event: "message", listener: (value: any) => void): this;
  238. on(event: "messageerror", listener: (error: Error) => void): this;
  239. on(event: string | symbol, listener: (...args: any[]) => void): this;
  240. once(event: "close", listener: () => void): this;
  241. once(event: "message", listener: (value: any) => void): this;
  242. once(event: "messageerror", listener: (error: Error) => void): this;
  243. once(event: string | symbol, listener: (...args: any[]) => void): this;
  244. prependListener(event: "close", listener: () => void): this;
  245. prependListener(event: "message", listener: (value: any) => void): this;
  246. prependListener(event: "messageerror", listener: (error: Error) => void): this;
  247. prependListener(event: string | symbol, listener: (...args: any[]) => void): this;
  248. prependOnceListener(event: "close", listener: () => void): this;
  249. prependOnceListener(event: "message", listener: (value: any) => void): this;
  250. prependOnceListener(event: "messageerror", listener: (error: Error) => void): this;
  251. prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this;
  252. removeListener(event: "close", listener: () => void): this;
  253. removeListener(event: "message", listener: (value: any) => void): this;
  254. removeListener(event: "messageerror", listener: (error: Error) => void): this;
  255. removeListener(event: string | symbol, listener: (...args: any[]) => void): this;
  256. off(event: "close", listener: () => void): this;
  257. off(event: "message", listener: (value: any) => void): this;
  258. off(event: "messageerror", listener: (error: Error) => void): this;
  259. off(event: string | symbol, listener: (...args: any[]) => void): this;
  260. addEventListener: EventTarget["addEventListener"];
  261. dispatchEvent: EventTarget["dispatchEvent"];
  262. removeEventListener: EventTarget["removeEventListener"];
  263. }
  264. interface WorkerOptions {
  265. /**
  266. * List of arguments which would be stringified and appended to
  267. * `process.argv` in the worker. This is mostly similar to the `workerData`
  268. * but the values will be available on the global `process.argv` as if they
  269. * were passed as CLI options to the script.
  270. */
  271. argv?: any[] | undefined;
  272. env?: NodeJS.Dict<string> | typeof SHARE_ENV | undefined;
  273. eval?: boolean | undefined;
  274. workerData?: any;
  275. stdin?: boolean | undefined;
  276. stdout?: boolean | undefined;
  277. stderr?: boolean | undefined;
  278. execArgv?: string[] | undefined;
  279. resourceLimits?: ResourceLimits | undefined;
  280. /**
  281. * Additional data to send in the first worker message.
  282. */
  283. transferList?: Transferable[] | undefined;
  284. /**
  285. * @default true
  286. */
  287. trackUnmanagedFds?: boolean | undefined;
  288. /**
  289. * An optional `name` to be appended to the worker title
  290. * for debugging/identification purposes, making the final title as
  291. * `[worker ${id}] ${name}`.
  292. */
  293. name?: string | undefined;
  294. }
  295. interface ResourceLimits {
  296. /**
  297. * The maximum size of a heap space for recently created objects.
  298. */
  299. maxYoungGenerationSizeMb?: number | undefined;
  300. /**
  301. * The maximum size of the main heap in MB.
  302. */
  303. maxOldGenerationSizeMb?: number | undefined;
  304. /**
  305. * The size of a pre-allocated memory range used for generated code.
  306. */
  307. codeRangeSizeMb?: number | undefined;
  308. /**
  309. * The default maximum stack size for the thread. Small values may lead to unusable Worker instances.
  310. * @default 4
  311. */
  312. stackSizeMb?: number | undefined;
  313. }
  314. /**
  315. * The `Worker` class represents an independent JavaScript execution thread.
  316. * Most Node.js APIs are available inside of it.
  317. *
  318. * Notable differences inside a Worker environment are:
  319. *
  320. * * The `process.stdin`, `process.stdout`, and `process.stderr` streams may be redirected by the parent thread.
  321. * * The `import { isMainThread } from 'node:worker_threads'` variable is set to `false`.
  322. * * The `import { parentPort } from 'node:worker_threads'` message port is available.
  323. * * `process.exit()` does not stop the whole program, just the single thread,
  324. * and `process.abort()` is not available.
  325. * * `process.chdir()` and `process` methods that set group or user ids
  326. * are not available.
  327. * * `process.env` is a copy of the parent thread's environment variables,
  328. * unless otherwise specified. Changes to one copy are not visible in other
  329. * threads, and are not visible to native add-ons (unless `worker.SHARE_ENV` is passed as the `env` option to the `Worker` constructor). On Windows, unlike the main thread, a copy of the
  330. * environment variables operates in a case-sensitive manner.
  331. * * `process.title` cannot be modified.
  332. * * Signals are not delivered through `process.on('...')`.
  333. * * Execution may stop at any point as a result of `worker.terminate()` being invoked.
  334. * * IPC channels from parent processes are not accessible.
  335. * * The `trace_events` module is not supported.
  336. * * Native add-ons can only be loaded from multiple threads if they fulfill `certain conditions`.
  337. *
  338. * Creating `Worker` instances inside of other `Worker`s is possible.
  339. *
  340. * Like [Web Workers](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API) and the `node:cluster module`, two-way communication
  341. * can be achieved through inter-thread message passing. Internally, a `Worker` has
  342. * a built-in pair of `MessagePort` s that are already associated with each
  343. * other when the `Worker` is created. While the `MessagePort` object on the parent
  344. * side is not directly exposed, its functionalities are exposed through `worker.postMessage()` and the `worker.on('message')` event
  345. * on the `Worker` object for the parent thread.
  346. *
  347. * To create custom messaging channels (which is encouraged over using the default
  348. * global channel because it facilitates separation of concerns), users can create
  349. * a `MessageChannel` object on either thread and pass one of the`MessagePort`s on that `MessageChannel` to the other thread through a
  350. * pre-existing channel, such as the global one.
  351. *
  352. * See `port.postMessage()` for more information on how messages are passed,
  353. * and what kind of JavaScript values can be successfully transported through
  354. * the thread barrier.
  355. *
  356. * ```js
  357. * import assert from 'node:assert';
  358. * import {
  359. * Worker, MessageChannel, MessagePort, isMainThread, parentPort,
  360. * } from 'node:worker_threads';
  361. * if (isMainThread) {
  362. * const worker = new Worker(__filename);
  363. * const subChannel = new MessageChannel();
  364. * worker.postMessage({ hereIsYourPort: subChannel.port1 }, [subChannel.port1]);
  365. * subChannel.port2.on('message', (value) => {
  366. * console.log('received:', value);
  367. * });
  368. * } else {
  369. * parentPort.once('message', (value) => {
  370. * assert(value.hereIsYourPort instanceof MessagePort);
  371. * value.hereIsYourPort.postMessage('the worker is sending this');
  372. * value.hereIsYourPort.close();
  373. * });
  374. * }
  375. * ```
  376. * @since v10.5.0
  377. */
  378. class Worker extends EventEmitter {
  379. /**
  380. * If `stdin: true` was passed to the `Worker` constructor, this is a
  381. * writable stream. The data written to this stream will be made available in
  382. * the worker thread as `process.stdin`.
  383. * @since v10.5.0
  384. */
  385. readonly stdin: Writable | null;
  386. /**
  387. * 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
  388. * parent thread's `process.stdout` stream.
  389. * @since v10.5.0
  390. */
  391. readonly stdout: Readable;
  392. /**
  393. * 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
  394. * parent thread's `process.stderr` stream.
  395. * @since v10.5.0
  396. */
  397. readonly stderr: Readable;
  398. /**
  399. * An integer identifier for the referenced thread. Inside the worker thread,
  400. * it is available as `import { threadId } from 'node:worker_threads'`.
  401. * This value is unique for each `Worker` instance inside a single process.
  402. * @since v10.5.0
  403. */
  404. readonly threadId: number;
  405. /**
  406. * Provides the set of JS engine resource constraints for this Worker thread.
  407. * If the `resourceLimits` option was passed to the `Worker` constructor,
  408. * this matches its values.
  409. *
  410. * If the worker has stopped, the return value is an empty object.
  411. * @since v13.2.0, v12.16.0
  412. */
  413. readonly resourceLimits?: ResourceLimits | undefined;
  414. /**
  415. * An object that can be used to query performance information from a worker
  416. * instance. Similar to `perf_hooks.performance`.
  417. * @since v15.1.0, v14.17.0, v12.22.0
  418. */
  419. readonly performance: WorkerPerformance;
  420. /**
  421. * @param filename The path to the Worker’s main script or module.
  422. * Must be either an absolute path or a relative path (i.e. relative to the current working directory) starting with ./ or ../,
  423. * or a WHATWG URL object using file: protocol. If options.eval is true, this is a string containing JavaScript code rather than a path.
  424. */
  425. constructor(filename: string | URL, options?: WorkerOptions);
  426. /**
  427. * Send a message to the worker that is received via `require('node:worker_threads').parentPort.on('message')`.
  428. * See `port.postMessage()` for more details.
  429. * @since v10.5.0
  430. */
  431. postMessage(value: any, transferList?: readonly Transferable[]): void;
  432. /**
  433. * Sends a value to another worker, identified by its thread ID.
  434. * @param threadId The target thread ID. If the thread ID is invalid, a `ERR_WORKER_MESSAGING_FAILED` error will be thrown.
  435. * If the target thread ID is the current thread ID, a `ERR_WORKER_MESSAGING_SAME_THREAD` error will be thrown.
  436. * @param value The value to send.
  437. * @param transferList If one or more `MessagePort`-like objects are passed in value, a `transferList` is required for those items
  438. * or `ERR_MISSING_MESSAGE_PORT_IN_TRANSFER_LIST` is thrown. See `port.postMessage()` for more information.
  439. * @param timeout Time to wait for the message to be delivered in milliseconds. By default it's `undefined`, which means wait forever.
  440. * If the operation times out, a `ERR_WORKER_MESSAGING_TIMEOUT` error is thrown.
  441. * @since v22.5.0
  442. */
  443. postMessageToThread(threadId: number, value: any, timeout?: number): Promise<void>;
  444. postMessageToThread(
  445. threadId: number,
  446. value: any,
  447. transferList: readonly Transferable[],
  448. timeout?: number,
  449. ): Promise<void>;
  450. /**
  451. * 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
  452. * behavior). If the worker is `ref()`ed, calling `ref()` again has
  453. * no effect.
  454. * @since v10.5.0
  455. */
  456. ref(): void;
  457. /**
  458. * Calling `unref()` on a worker allows the thread to exit if this is the only
  459. * active handle in the event system. If the worker is already `unref()`ed calling `unref()` again has no effect.
  460. * @since v10.5.0
  461. */
  462. unref(): void;
  463. /**
  464. * Stop all JavaScript execution in the worker thread as soon as possible.
  465. * Returns a Promise for the exit code that is fulfilled when the `'exit' event` is emitted.
  466. * @since v10.5.0
  467. */
  468. terminate(): Promise<number>;
  469. /**
  470. * Returns a readable stream for a V8 snapshot of the current state of the Worker.
  471. * See `v8.getHeapSnapshot()` for more details.
  472. *
  473. * If the Worker thread is no longer running, which may occur before the `'exit' event` is emitted, the returned `Promise` is rejected
  474. * immediately with an `ERR_WORKER_NOT_RUNNING` error.
  475. * @since v13.9.0, v12.17.0
  476. * @return A promise for a Readable Stream containing a V8 heap snapshot
  477. */
  478. getHeapSnapshot(): Promise<Readable>;
  479. /**
  480. * This method returns a `Promise` that will resolve to an object identical to `v8.getHeapStatistics()`,
  481. * or reject with an `ERR_WORKER_NOT_RUNNING` error if the worker is no longer running.
  482. * This methods allows the statistics to be observed from outside the actual thread.
  483. * @since v24.0.0
  484. */
  485. getHeapStatistics(): Promise<HeapInfo>;
  486. /**
  487. * Calls `worker.terminate()` when the dispose scope is exited.
  488. *
  489. * ```js
  490. * async function example() {
  491. * await using worker = new Worker('for (;;) {}', { eval: true });
  492. * // Worker is automatically terminate when the scope is exited.
  493. * }
  494. * ```
  495. * @since v24.2.0
  496. */
  497. [Symbol.asyncDispose](): Promise<void>;
  498. addListener(event: "error", listener: (err: Error) => void): this;
  499. addListener(event: "exit", listener: (exitCode: number) => void): this;
  500. addListener(event: "message", listener: (value: any) => void): this;
  501. addListener(event: "messageerror", listener: (error: Error) => void): this;
  502. addListener(event: "online", listener: () => void): this;
  503. addListener(event: string | symbol, listener: (...args: any[]) => void): this;
  504. emit(event: "error", err: Error): boolean;
  505. emit(event: "exit", exitCode: number): boolean;
  506. emit(event: "message", value: any): boolean;
  507. emit(event: "messageerror", error: Error): boolean;
  508. emit(event: "online"): boolean;
  509. emit(event: string | symbol, ...args: any[]): boolean;
  510. on(event: "error", listener: (err: Error) => void): this;
  511. on(event: "exit", listener: (exitCode: number) => void): this;
  512. on(event: "message", listener: (value: any) => void): this;
  513. on(event: "messageerror", listener: (error: Error) => void): this;
  514. on(event: "online", listener: () => void): this;
  515. on(event: string | symbol, listener: (...args: any[]) => void): this;
  516. once(event: "error", listener: (err: Error) => void): this;
  517. once(event: "exit", listener: (exitCode: number) => void): this;
  518. once(event: "message", listener: (value: any) => void): this;
  519. once(event: "messageerror", listener: (error: Error) => void): this;
  520. once(event: "online", listener: () => void): this;
  521. once(event: string | symbol, listener: (...args: any[]) => void): this;
  522. prependListener(event: "error", listener: (err: Error) => void): this;
  523. prependListener(event: "exit", listener: (exitCode: number) => void): this;
  524. prependListener(event: "message", listener: (value: any) => void): this;
  525. prependListener(event: "messageerror", listener: (error: Error) => void): this;
  526. prependListener(event: "online", listener: () => void): this;
  527. prependListener(event: string | symbol, listener: (...args: any[]) => void): this;
  528. prependOnceListener(event: "error", listener: (err: Error) => void): this;
  529. prependOnceListener(event: "exit", listener: (exitCode: number) => void): this;
  530. prependOnceListener(event: "message", listener: (value: any) => void): this;
  531. prependOnceListener(event: "messageerror", listener: (error: Error) => void): this;
  532. prependOnceListener(event: "online", listener: () => void): this;
  533. prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this;
  534. removeListener(event: "error", listener: (err: Error) => void): this;
  535. removeListener(event: "exit", listener: (exitCode: number) => void): this;
  536. removeListener(event: "message", listener: (value: any) => void): this;
  537. removeListener(event: "messageerror", listener: (error: Error) => void): this;
  538. removeListener(event: "online", listener: () => void): this;
  539. removeListener(event: string | symbol, listener: (...args: any[]) => void): this;
  540. off(event: "error", listener: (err: Error) => void): this;
  541. off(event: "exit", listener: (exitCode: number) => void): this;
  542. off(event: "message", listener: (value: any) => void): this;
  543. off(event: "messageerror", listener: (error: Error) => void): this;
  544. off(event: "online", listener: () => void): this;
  545. off(event: string | symbol, listener: (...args: any[]) => void): this;
  546. }
  547. interface BroadcastChannel extends NodeJS.RefCounted {}
  548. /**
  549. * Instances of `BroadcastChannel` allow asynchronous one-to-many communication
  550. * with all other `BroadcastChannel` instances bound to the same channel name.
  551. *
  552. * ```js
  553. * 'use strict';
  554. *
  555. * import {
  556. * isMainThread,
  557. * BroadcastChannel,
  558. * Worker,
  559. * } from 'node:worker_threads';
  560. *
  561. * const bc = new BroadcastChannel('hello');
  562. *
  563. * if (isMainThread) {
  564. * let c = 0;
  565. * bc.onmessage = (event) => {
  566. * console.log(event.data);
  567. * if (++c === 10) bc.close();
  568. * };
  569. * for (let n = 0; n < 10; n++)
  570. * new Worker(__filename);
  571. * } else {
  572. * bc.postMessage('hello from every worker');
  573. * bc.close();
  574. * }
  575. * ```
  576. * @since v15.4.0
  577. */
  578. class BroadcastChannel extends EventTarget {
  579. readonly name: string;
  580. /**
  581. * Invoked with a single \`MessageEvent\` argument when a message is received.
  582. * @since v15.4.0
  583. */
  584. onmessage: (message: MessageEvent) => void;
  585. /**
  586. * Invoked with a received message cannot be deserialized.
  587. * @since v15.4.0
  588. */
  589. onmessageerror: (message: MessageEvent) => void;
  590. constructor(name: string);
  591. /**
  592. * Closes the `BroadcastChannel` connection.
  593. * @since v15.4.0
  594. */
  595. close(): void;
  596. /**
  597. * @since v15.4.0
  598. * @param message Any cloneable JavaScript value.
  599. */
  600. postMessage(message: unknown): void;
  601. }
  602. interface Lock {
  603. readonly mode: LockMode;
  604. readonly name: string;
  605. }
  606. interface LockGrantedCallback<T> {
  607. (lock: Lock | null): T;
  608. }
  609. interface LockInfo {
  610. clientId: string;
  611. mode: LockMode;
  612. name: string;
  613. }
  614. interface LockManager {
  615. query(): Promise<LockManagerSnapshot>;
  616. request<T>(name: string, callback: LockGrantedCallback<T>): Promise<Awaited<T>>;
  617. request<T>(name: string, options: LockOptions, callback: LockGrantedCallback<T>): Promise<Awaited<T>>;
  618. }
  619. interface LockManagerSnapshot {
  620. held: LockInfo[];
  621. pending: LockInfo[];
  622. }
  623. type LockMode = "exclusive" | "shared";
  624. interface LockOptions {
  625. ifAvailable?: boolean;
  626. mode?: LockMode;
  627. signal?: AbortSignal;
  628. steal?: boolean;
  629. }
  630. var locks: LockManager;
  631. /**
  632. * Mark an object as not transferable. If `object` occurs in the transfer list of
  633. * a `port.postMessage()` call, it is ignored.
  634. *
  635. * In particular, this makes sense for objects that can be cloned, rather than
  636. * transferred, and which are used by other objects on the sending side.
  637. * For example, Node.js marks the `ArrayBuffer`s it uses for its `Buffer pool` with this.
  638. *
  639. * This operation cannot be undone.
  640. *
  641. * ```js
  642. * import { MessageChannel, markAsUntransferable } from 'node:worker_threads';
  643. *
  644. * const pooledBuffer = new ArrayBuffer(8);
  645. * const typedArray1 = new Uint8Array(pooledBuffer);
  646. * const typedArray2 = new Float64Array(pooledBuffer);
  647. *
  648. * markAsUntransferable(pooledBuffer);
  649. *
  650. * const { port1 } = new MessageChannel();
  651. * port1.postMessage(typedArray1, [ typedArray1.buffer ]);
  652. *
  653. * // The following line prints the contents of typedArray1 -- it still owns
  654. * // its memory and has been cloned, not transferred. Without
  655. * // `markAsUntransferable()`, this would print an empty Uint8Array.
  656. * // typedArray2 is intact as well.
  657. * console.log(typedArray1);
  658. * console.log(typedArray2);
  659. * ```
  660. *
  661. * There is no equivalent to this API in browsers.
  662. * @since v14.5.0, v12.19.0
  663. */
  664. function markAsUntransferable(object: object): void;
  665. /**
  666. * Check if an object is marked as not transferable with
  667. * {@link markAsUntransferable}.
  668. * @since v21.0.0
  669. */
  670. function isMarkedAsUntransferable(object: object): boolean;
  671. /**
  672. * Mark an object as not cloneable. If `object` is used as `message` in
  673. * a `port.postMessage()` call, an error is thrown. This is a no-op if `object` is a
  674. * primitive value.
  675. *
  676. * This has no effect on `ArrayBuffer`, or any `Buffer` like objects.
  677. *
  678. * This operation cannot be undone.
  679. *
  680. * ```js
  681. * const { markAsUncloneable } = require('node:worker_threads');
  682. *
  683. * const anyObject = { foo: 'bar' };
  684. * markAsUncloneable(anyObject);
  685. * const { port1 } = new MessageChannel();
  686. * try {
  687. * // This will throw an error, because anyObject is not cloneable.
  688. * port1.postMessage(anyObject)
  689. * } catch (error) {
  690. * // error.name === 'DataCloneError'
  691. * }
  692. * ```
  693. *
  694. * There is no equivalent to this API in browsers.
  695. * @since v22.10.0
  696. */
  697. function markAsUncloneable(object: object): void;
  698. /**
  699. * Transfer a `MessagePort` to a different `vm` Context. The original `port` object is rendered unusable, and the returned `MessagePort` instance
  700. * takes its place.
  701. *
  702. * The returned `MessagePort` is an object in the target context and
  703. * inherits from its global `Object` class. Objects passed to the [`port.onmessage()`](https://developer.mozilla.org/en-US/docs/Web/API/MessagePort/onmessage) listener are also created in the
  704. * target context
  705. * and inherit from its global `Object` class.
  706. *
  707. * However, the created `MessagePort` no longer inherits from [`EventTarget`](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget), and only
  708. * [`port.onmessage()`](https://developer.mozilla.org/en-US/docs/Web/API/MessagePort/onmessage) can be used to receive
  709. * events using it.
  710. * @since v11.13.0
  711. * @param port The message port to transfer.
  712. * @param contextifiedSandbox A `contextified` object as returned by the `vm.createContext()` method.
  713. */
  714. function moveMessagePortToContext(port: MessagePort, contextifiedSandbox: Context): MessagePort;
  715. /**
  716. * Receive a single message from a given `MessagePort`. If no message is available,`undefined` is returned, otherwise an object with a single `message` property
  717. * that contains the message payload, corresponding to the oldest message in the `MessagePort`'s queue.
  718. *
  719. * ```js
  720. * import { MessageChannel, receiveMessageOnPort } from 'node:worker_threads';
  721. * const { port1, port2 } = new MessageChannel();
  722. * port1.postMessage({ hello: 'world' });
  723. *
  724. * console.log(receiveMessageOnPort(port2));
  725. * // Prints: { message: { hello: 'world' } }
  726. * console.log(receiveMessageOnPort(port2));
  727. * // Prints: undefined
  728. * ```
  729. *
  730. * When this function is used, no `'message'` event is emitted and the `onmessage` listener is not invoked.
  731. * @since v12.3.0
  732. */
  733. function receiveMessageOnPort(port: MessagePort):
  734. | {
  735. message: any;
  736. }
  737. | undefined;
  738. type Serializable = string | object | number | boolean | bigint;
  739. /**
  740. * Within a worker thread, `worker.getEnvironmentData()` returns a clone
  741. * of data passed to the spawning thread's `worker.setEnvironmentData()`.
  742. * Every new `Worker` receives its own copy of the environment data
  743. * automatically.
  744. *
  745. * ```js
  746. * import {
  747. * Worker,
  748. * isMainThread,
  749. * setEnvironmentData,
  750. * getEnvironmentData,
  751. * } from 'node:worker_threads';
  752. *
  753. * if (isMainThread) {
  754. * setEnvironmentData('Hello', 'World!');
  755. * const worker = new Worker(__filename);
  756. * } else {
  757. * console.log(getEnvironmentData('Hello')); // Prints 'World!'.
  758. * }
  759. * ```
  760. * @since v15.12.0, v14.18.0
  761. * @param key Any arbitrary, cloneable JavaScript value that can be used as a {Map} key.
  762. */
  763. function getEnvironmentData(key: Serializable): Serializable;
  764. /**
  765. * The `worker.setEnvironmentData()` API sets the content of `worker.getEnvironmentData()` in the current thread and all new `Worker` instances spawned from the current context.
  766. * @since v15.12.0, v14.18.0
  767. * @param key Any arbitrary, cloneable JavaScript value that can be used as a {Map} key.
  768. * @param value Any arbitrary, cloneable JavaScript value that will be cloned and passed automatically to all new `Worker` instances. If `value` is passed as `undefined`, any previously set value
  769. * for the `key` will be deleted.
  770. */
  771. function setEnvironmentData(key: Serializable, value?: Serializable): void;
  772. /**
  773. * Sends a value to another worker, identified by its thread ID.
  774. * @param threadId The target thread ID. If the thread ID is invalid, a `ERR_WORKER_MESSAGING_FAILED` error will be thrown.
  775. * If the target thread ID is the current thread ID, a `ERR_WORKER_MESSAGING_SAME_THREAD` error will be thrown.
  776. * @param value The value to send.
  777. * @param transferList If one or more `MessagePort`-like objects are passed in value, a `transferList` is required for those items
  778. * or `ERR_MISSING_MESSAGE_PORT_IN_TRANSFER_LIST` is thrown. See `port.postMessage()` for more information.
  779. * @param timeout Time to wait for the message to be delivered in milliseconds. By default it's `undefined`, which means wait forever.
  780. * If the operation times out, a `ERR_WORKER_MESSAGING_TIMEOUT` error is thrown.
  781. * @since v22.5.0
  782. */
  783. function postMessageToThread(threadId: number, value: any, timeout?: number): Promise<void>;
  784. function postMessageToThread(
  785. threadId: number,
  786. value: any,
  787. transferList: readonly Transferable[],
  788. timeout?: number,
  789. ): Promise<void>;
  790. import {
  791. BroadcastChannel as _BroadcastChannel,
  792. MessageChannel as _MessageChannel,
  793. MessagePort as _MessagePort,
  794. } from "worker_threads";
  795. global {
  796. function structuredClone<T>(
  797. value: T,
  798. options?: { transfer?: Transferable[] },
  799. ): T;
  800. /**
  801. * `BroadcastChannel` class is a global reference for `import { BroadcastChannel } from 'worker_threads'`
  802. * https://nodejs.org/api/globals.html#broadcastchannel
  803. * @since v18.0.0
  804. */
  805. var BroadcastChannel: typeof globalThis extends {
  806. onmessage: any;
  807. BroadcastChannel: infer T;
  808. } ? T
  809. : typeof _BroadcastChannel;
  810. /**
  811. * `MessageChannel` class is a global reference for `import { MessageChannel } from 'worker_threads'`
  812. * https://nodejs.org/api/globals.html#messagechannel
  813. * @since v15.0.0
  814. */
  815. var MessageChannel: typeof globalThis extends {
  816. onmessage: any;
  817. MessageChannel: infer T;
  818. } ? T
  819. : typeof _MessageChannel;
  820. /**
  821. * `MessagePort` class is a global reference for `import { MessagePort } from 'worker_threads'`
  822. * https://nodejs.org/api/globals.html#messageport
  823. * @since v15.0.0
  824. */
  825. var MessagePort: typeof globalThis extends {
  826. onmessage: any;
  827. MessagePort: infer T;
  828. } ? T
  829. : typeof _MessagePort;
  830. }
  831. }
  832. declare module "node:worker_threads" {
  833. export * from "worker_threads";
  834. }