207dfd2ecf126f7ccb3dd3277c5aed206d992b6493cf65c21e770a6064f51f5828edfc6592e4052a50a338bb5aa0dd403646186a446618fbee25be1c9eb246 36 KB

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