nodejs/doc/api/worker_threads.md

1997 lines
58 KiB
Markdown
Raw Permalink Normal View History

# Worker threads
<!--introduced_in=v10.5.0-->
> Stability: 2 - Stable
<!-- source_link=lib/worker_threads.js -->
The `node:worker_threads` module enables the use of threads that execute
JavaScript in parallel. To access it:
```mjs
import worker from 'node:worker_threads';
```
```cjs
'use strict';
const worker = require('node:worker_threads');
```
Workers (threads) are useful for performing CPU-intensive JavaScript operations.
They do not help much with I/O-intensive work. The Node.js built-in
asynchronous I/O operations are more efficient than Workers can be.
Unlike `child_process` or `cluster`, `worker_threads` can share memory. They do
so by transferring `ArrayBuffer` instances or sharing `SharedArrayBuffer`
instances.
```mjs
import {
Worker,
isMainThread,
parentPort,
workerData,
} from 'node:worker_threads';
if (!isMainThread) {
const { parse } = await import('some-js-parsing-library');
const script = workerData;
parentPort.postMessage(parse(script));
}
export default function parseJSAsync(script) {
return new Promise((resolve, reject) => {
const worker = new Worker(new URL(import.meta.url), {
workerData: script,
});
worker.on('message', resolve);
worker.on('error', reject);
worker.on('exit', (code) => {
if (code !== 0)
reject(new Error(`Worker stopped with exit code ${code}`));
});
});
};
```
```cjs
'use strict';
const {
Worker,
isMainThread,
parentPort,
workerData,
} = require('node:worker_threads');
if (isMainThread) {
module.exports = function parseJSAsync(script) {
return new Promise((resolve, reject) => {
const worker = new Worker(__filename, {
workerData: script,
});
worker.on('message', resolve);
worker.on('error', reject);
worker.on('exit', (code) => {
if (code !== 0)
reject(new Error(`Worker stopped with exit code ${code}`));
});
});
};
} else {
const { parse } = require('some-js-parsing-library');
const script = workerData;
parentPort.postMessage(parse(script));
}
```
The above example spawns a Worker thread for each `parseJSAsync()` call. In
practice, use a pool of Workers for these kinds of tasks. Otherwise, the
overhead of creating Workers would likely exceed their benefit.
When implementing a worker pool, use the [`AsyncResource`][] API to inform
diagnostic tools (e.g. to provide asynchronous stack traces) about the
correlation between tasks and their outcomes. See
["Using `AsyncResource` for a `Worker` thread pool"][async-resource-worker-pool]
in the `async_hooks` documentation for an example implementation.
Worker threads inherit non-process-specific options by default. Refer to
[`Worker constructor options`][] to know how to customize worker thread options,
specifically `argv` and `execArgv` options.
## `worker.getEnvironmentData(key)`
<!-- YAML
2021-09-28, Version 14.18.0 'Fermium' (LTS) Notable changes: assert: * change status of legacy asserts (James M Snell) https://github.com/nodejs/node/pull/38113 buffer: * (SEMVER-MINOR) introduce Blob (James M Snell) https://github.com/nodejs/node/pull/36811 * (SEMVER-MINOR) add base64url encoding option (Filip Skokan) https://github.com/nodejs/node/pull/36952 child_process: * (SEMVER-MINOR) allow `options.cwd` receive a URL (Khaidi Chu) https://github.com/nodejs/node/pull/38862 * (SEMVER-MINOR) add timeout to spawn and fork (Nitzan Uziely) https://github.com/nodejs/node/pull/37256 * (SEMVER-MINOR) allow promisified exec to be cancel (Carlos Fuentes) https://github.com/nodejs/node/pull/34249 * (SEMVER-MINOR) add 'overlapped' stdio flag (Thiago Padilha) https://github.com/nodejs/node/pull/29412 cli: * (SEMVER-MINOR) add -C alias for --conditions flag (Guy Bedford) https://github.com/nodejs/node/pull/38755 * (SEMVER-MINOR) add --node-memory-debug option (Anna Henningsen) https://github.com/nodejs/node/pull/35537 dns: * (SEMVER-MINOR) add "tries" option to Resolve options (Luan Devecchi) https://github.com/nodejs/node/pull/39610 * (SEMVER-MINOR) allow `--dns-result-order` to change default dns verbatim (Ouyang Yadong) https://github.com/nodejs/node/pull/38099 doc: * (SEMVER-MINOR) add missing change to resolver ctor (Luan Devecchi) https://github.com/nodejs/node/pull/39610 * refactor fs docs structure (James M Snell) https://github.com/nodejs/node/pull/37170 errors: * (SEMVER-MINOR) remove experimental from --enable-source-maps (Benjamin Coe) https://github.com/nodejs/node/pull/37362 esm: * deprecate legacy main lookup for modules (Guy Bedford) https://github.com/nodejs/node/pull/36918 fs: * (SEMVER-MINOR) allow empty string for temp directory prefix (Voltrex) https://github.com/nodejs/node/pull/39028 * (SEMVER-MINOR) allow no-params fsPromises fileHandle read (Nitzan Uziely) https://github.com/nodejs/node/pull/38287 * (SEMVER-MINOR) add support for async iterators to `fsPromises.writeFile` (HiroyukiYagihashi) https://github.com/nodejs/node/pull/37490 * improve fsPromises readFile performance (Nitzan Uziely) https://github.com/nodejs/node/pull/37608 * (SEMVER-MINOR) add fsPromises.watch() (James M Snell) https://github.com/nodejs/node/pull/37179 * (SEMVER-MINOR) allow `position` parameter to be a `BigInt` in read and readSync (Darshan Sen) https://github.com/nodejs/node/pull/36190 http2: * (SEMVER-MINOR) add support for sensitive headers (Anna Henningsen) https://github.com/nodejs/node/pull/34145 * (SEMVER-MINOR) allow setting the local window size of a session (Yongsheng Zhang) https://github.com/nodejs/node/pull/35978 inspector: * mark as stable (Gireesh Punathil) https://github.com/nodejs/node/pull/37748 module: * (SEMVER-MINOR) add support for `URL` to `import.meta.resolve` (Antoine du Hamel) https://github.com/nodejs/node/pull/38587 * (SEMVER-MINOR) add support for `node:`‑prefixed `require(…)` calls (ExE Boss) https://github.com/nodejs/node/pull/37246 net: * (SEMVER-MINOR) introduce net.BlockList (James M Snell) https://github.com/nodejs/node/pull/34625 node-api: * (SEMVER-MINOR) allow retrieval of add-on file name (Gabriel Schulhof) https://github.com/nodejs/node/pull/37195 os: * (SEMVER-MINOR) add os.devNull (Luigi Pinca) https://github.com/nodejs/node/pull/38569 perf_hooks: * (SEMVER-MINOR) introduce createHistogram (James M Snell) https://github.com/nodejs/node/pull/37155 process: * (SEMVER-MINOR) add api to enable source-maps programmatically (legendecas) https://github.com/nodejs/node/pull/39085 * (SEMVER-MINOR) add `'worker'` event (James M Snell) https://github.com/nodejs/node/pull/38659 * (SEMVER-MINOR) add direct access to rss without iterating pages (Adrien Maret) https://github.com/nodejs/node/pull/34291 readline: * (SEMVER-MINOR) add AbortSignal support to interface (Nitzan Uziely) https://github.com/nodejs/node/pull/37932 * (SEMVER-MINOR) add support for the AbortController to the question method (Mattias Runge-Broberg) https://github.com/nodejs/node/pull/33676 * (SEMVER-MINOR) add history event and option to set initial history (Mattias Runge-Broberg) https://github.com/nodejs/node/pull/33662 repl: * (SEMVER-MINOR) add auto‑completion for `node:`‑prefixed `require(…)` calls (ExE Boss) https://github.com/nodejs/node/pull/37246 src: * (SEMVER-MINOR) call overload ctor from the original ctor (Darshan Sen) https://github.com/nodejs/node/pull/39768 * (SEMVER-MINOR) add a constructor overload for CallbackScope (Darshan Sen) https://github.com/nodejs/node/pull/39768 * (SEMVER-MINOR) allow to negate boolean CLI flags (Michaël Zasso) https://github.com/nodejs/node/pull/39023 * (SEMVER-MINOR) add --heapsnapshot-near-heap-limit option (Joyee Cheung) https://github.com/nodejs/node/pull/33010 * (SEMVER-MINOR) add way to get IsolateData and allocator from Environment (Anna Henningsen) https://github.com/nodejs/node/pull/36441 * (SEMVER-MINOR) allow preventing SetPrepareStackTraceCallback (Shelley Vohr) https://github.com/nodejs/node/pull/36447 * (SEMVER-MINOR) add maybe versions of EmitExit and EmitBeforeExit (Anna Henningsen) https://github.com/nodejs/node/pull/35486 stream: * (SEMVER-MINOR) add readableDidRead if has been read from (Robert Nagy) https://github.com/nodejs/node/pull/39589 * (SEMVER-MINOR) pipeline accept Buffer as a valid first argument (Nitzan Uziely) https://github.com/nodejs/node/pull/37739 tls: * (SEMVER-MINOR) allow reading data into a static buffer (Andrey Pechkurov) https://github.com/nodejs/node/pull/35753 tools: * (SEMVER-MINOR) add `Worker` to type-parser (James M Snell) https://github.com/nodejs/node/pull/38659 url: * (SEMVER-MINOR) expose urlToHttpOptions utility (Yongsheng Zhang) https://github.com/nodejs/node/pull/35960 util: * (SEMVER-MINOR) expose toUSVString (Robert Nagy) https://github.com/nodejs/node/pull/39814 v8: * (SEMVER-MINOR) implement v8.stopCoverage() (Joyee Cheung) https://github.com/nodejs/node/pull/33807 * (SEMVER-MINOR) implement v8.takeCoverage() (Joyee Cheung) https://github.com/nodejs/node/pull/33807 worker: * (SEMVER-MINOR) add setEnvironmentData/getEnvironmentData (James M Snell) https://github.com/nodejs/node/pull/37486 PR-URL: https://github.com/nodejs/node/pull/39990
2021-09-04 15:29:35 +02:00
added:
- v15.12.0
- v14.18.0
changes:
2022-04-26, Version 16.15.0 'Gallium' (LTS) Notable changes: Add fetch API Adds experimental support to the fetch API. This adds the `--experimental-fetch` flag that installs the `fetch`, `Request`, `Response`, `Headers`, and `FormData` globals. * (SEMVER-MINOR) add fetch (Michaël Zasso) https://github.com/nodejs/node/pull/41749 * (SEMVER-MINOR) add FormData global when fetch is enabled (Michaël Zasso) https://github.com/nodejs/node/pull/41956 Other notable changes * build: * remove broken x32 arch support (Ben Noordhuis) https://github.com/nodejs/node/pull/41905 * crypto: * (SEMVER-MINOR) add KeyObject.prototype.equals method (Filip Skokan) https://github.com/nodejs/node/pull/42093 * doc: * add @ShogunPanda to collaborators (Paolo Insogna) https://github.com/nodejs/node/pull/42362 * add JakobJingleheimer to collaborators list (Jacob Smith) https://github.com/nodejs/node/pull/42185 * add joesepi to collaborators (Joe Sepi) https://github.com/nodejs/node/pull/41914 * add marsonya to collaborators (Akhil Marsonya) https://github.com/nodejs/node/pull/41991 * deprecate string coercion in `fs.write`, `fs.writeFileSync` (Livia Medeiros) https://github.com/nodejs/node/pull/42149 * deprecate notice for process methods (Yash Ladha) https://github.com/nodejs/node/pull/41587 * esm: * (SEMVER-MINOR) support https remotely and http locally under flag (Bradley Farias) https://github.com/nodejs/node/pull/36328 * module: * (SEMVER-MINOR) unflag esm json modules (Geoffrey Booth) https://github.com/nodejs/node/pull/41736 * node-api: * (SEMVER-MINOR) add node_api_symbol_for() (Darshan Sen) https://github.com/nodejs/node/pull/41329 * process: * deprecate multipleResolves (Benjamin Gruenbaum) https://github.com/nodejs/node/pull/41872 * stream: * (SEMVER-MINOR) support some and every (Benjamin Gruenbaum) https://github.com/nodejs/node/pull/41573 * (SEMVER-MINOR) add toArray (Benjamin Gruenbaum) https://github.com/nodejs/node/pull/41553 * (SEMVER-MINOR) add forEach method (Benjamin Gruenbaum) https://github.com/nodejs/node/pull/41445 PR-URL: https://github.com/nodejs/node/pull/42847
2022-04-23 21:03:46 -04:00
- version:
- v17.5.0
- v16.15.0
pr-url: https://github.com/nodejs/node/pull/41272
description: No longer experimental.
-->
* `key` {any} Any arbitrary, cloneable JavaScript value that can be used as a
{Map} key.
* Returns: {any}
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.
```mjs
import {
Worker,
isMainThread,
setEnvironmentData,
getEnvironmentData,
} from 'node:worker_threads';
if (isMainThread) {
setEnvironmentData('Hello', 'World!');
const worker = new Worker(new URL(import.meta.url));
} else {
console.log(getEnvironmentData('Hello')); // Prints 'World!'.
}
```
```cjs
'use strict';
const {
Worker,
isMainThread,
setEnvironmentData,
getEnvironmentData,
} = require('node:worker_threads');
if (isMainThread) {
setEnvironmentData('Hello', 'World!');
const worker = new Worker(__filename);
} else {
console.log(getEnvironmentData('Hello')); // Prints 'World!'.
}
```
## `worker.isInternalThread`
<!-- YAML
2025-02-11, Version 22.14.0 'Jod' (LTS) Notable changes: crypto: * update root certificates to NSS 3.107 (Node.js GitHub Bot) https://github.com/nodejs/node/pull/56566 fs: * (SEMVER-MINOR) allow `exclude` option in globs to accept glob patterns (Daeyeon Jeong) https://github.com/nodejs/node/pull/56489 lib: * (SEMVER-MINOR) add typescript support to STDIN eval (Marco Ippolito) https://github.com/nodejs/node/pull/56359 module: * (SEMVER-MINOR) add ERR_UNSUPPORTED_TYPESCRIPT_SYNTAX (Marco Ippolito) https://github.com/nodejs/node/pull/56610 * (SEMVER-MINOR) add `findPackageJSON` util (Jacob Smith) https://github.com/nodejs/node/pull/55412 process: * (SEMVER-MINOR) add process.ref() and process.unref() methods (James M Snell) https://github.com/nodejs/node/pull/56400 sqlite: * (SEMVER-MINOR) support TypedArray and DataView in `StatementSync` (Alex Yang) https://github.com/nodejs/node/pull/56385 src: * (SEMVER-MINOR) add --disable-sigusr1 to prevent signal i/o thread (Rafael Gonzaga) https://github.com/nodejs/node/pull/56441 src,worker: * (SEMVER-MINOR) add isInternalWorker (Carlos Espa) https://github.com/nodejs/node/pull/56469 test_runner: * (SEMVER-MINOR) add TestContext.prototype.waitFor() (Colin Ihrig) https://github.com/nodejs/node/pull/56595 * (SEMVER-MINOR) add t.assert.fileSnapshot() (Colin Ihrig) https://github.com/nodejs/node/pull/56459 * (SEMVER-MINOR) add assert.register() API (Colin Ihrig) https://github.com/nodejs/node/pull/56434 worker: * (SEMVER-MINOR) add eval ts input (Marco Ippolito) https://github.com/nodejs/node/pull/56394 PR-URL: https://github.com/nodejs/node/pull/56910
2025-02-06 11:04:25 +01:00
added:
- v23.7.0
- v22.14.0
-->
* {boolean}
Is `true` if this code is running inside of an internal [`Worker`][] thread (e.g the loader thread).
```bash
node --experimental-loader ./loader.js main.js
```
```mjs
// loader.js
import { isInternalThread } from 'node:worker_threads';
console.log(isInternalThread); // true
```
```cjs
// loader.js
'use strict';
const { isInternalThread } = require('node:worker_threads');
console.log(isInternalThread); // true
```
```mjs
// main.js
import { isInternalThread } from 'node:worker_threads';
console.log(isInternalThread); // false
```
```cjs
// main.js
'use strict';
const { isInternalThread } = require('node:worker_threads');
console.log(isInternalThread); // false
```
## `worker.isMainThread`
<!-- YAML
added: v10.5.0
-->
* {boolean}
Is `true` if this code is not running inside of a [`Worker`][] thread.
```mjs
import { Worker, isMainThread } from 'node:worker_threads';
if (isMainThread) {
// This re-loads the current file inside a Worker instance.
new Worker(new URL(import.meta.url));
} else {
console.log('Inside Worker!');
console.log(isMainThread); // Prints 'false'.
}
```
```cjs
'use strict';
const { Worker, isMainThread } = require('node:worker_threads');
if (isMainThread) {
// This re-loads the current file inside a Worker instance.
new Worker(__filename);
} else {
console.log('Inside Worker!');
console.log(isMainThread); // Prints 'false'.
}
```
## `worker.markAsUntransferable(object)`
<!-- YAML
2020-10-06, Version 12.19.0 'Erbium' (LTS) Notable changes: assert: * (SEMVER-MINOR) port common.mustCall() to assert (ConorDavenport) https://github.com/nodejs/node/pull/31982 async_hooks: * (SEMVER-MINOR) add AsyncResource.bind utility (James M Snell) https://github.com/nodejs/node/pull/34574 buffer: * (SEMVER-MINOR) also alias BigUInt methods (Anna Henningsen) https://github.com/nodejs/node/pull/34960 * (SEMVER-MINOR) alias UInt ➡️ Uint in buffer methods (Anna Henningsen) https://github.com/nodejs/node/pull/34729 build: * (SEMVER-MINOR) add build flag for OSS-Fuzz integration (davkor) https://github.com/nodejs/node/pull/34761 cli: * (SEMVER-MINOR) add alias for report-directory to make it consistent (Ash Cripps) https://github.com/nodejs/node/pull/33587 crypto: * (SEMVER-MINOR) allow KeyObjects in postMessage (Tobias Nießen) https://github.com/nodejs/node/pull/33360 * (SEMVER-MINOR) add randomInt function (Oli Lalonde) https://github.com/nodejs/node/pull/34600 deps: * upgrade to libuv 1.39.0 (Colin Ihrig) https://github.com/nodejs/node/pull/34915 * upgrade npm to 6.14.7 (claudiahdz) https://github.com/nodejs/node/pull/34468 * upgrade to libuv 1.38.1 (Colin Ihrig) https://github.com/nodejs/node/pull/34187 dgram: * (SEMVER-MINOR) add IPv6 scope id suffix to received udp6 dgrams (Pekka Nikander) https://github.com/nodejs/node/pull/14500 * (SEMVER-MINOR) allow typed arrays in .send() (Sarat Addepalli) https://github.com/nodejs/node/pull/22413 doc: * (SEMVER-MINOR) Add maxTotalSockets option to agent constructor (rickyes) https://github.com/nodejs/node/pull/33617 * (SEMVER-MINOR) add basic embedding example documentation (Anna Henningsen) https://github.com/nodejs/node/pull/30467 * add Ricky Zhou to collaborators (rickyes) https://github.com/nodejs/node/pull/34676 * add release key for Ruy Adorno (Ruy Adorno) https://github.com/nodejs/node/pull/34628 * add DerekNonGeneric to collaborators (Derek Lewis) https://github.com/nodejs/node/pull/34602 * add AshCripps to collaborators (Ash Cripps) https://github.com/nodejs/node/pull/34494 * add HarshithaKP to collaborators (Harshitha K P) https://github.com/nodejs/node/pull/34417 * add rexagod to collaborators (Pranshu Srivastava) https://github.com/nodejs/node/pull/34457 * add release key for Richard Lau (Richard Lau) https://github.com/nodejs/node/pull/34397 * add danielleadams to collaborators (Danielle Adams) https://github.com/nodejs/node/pull/34360 * add sxa as collaborator (Stewart X Addison) https://github.com/nodejs/node/pull/34338 * add ruyadorno to collaborators (Ruy Adorno) https://github.com/nodejs/node/pull/34297 * (SEMVER-MAJOR) deprecate process.umask() with no arguments (Colin Ihrig) https://github.com/nodejs/node/pull/32499 embedding: * (SEMVER-MINOR) make Stop() stop Workers (Anna Henningsen) https://github.com/nodejs/node/pull/32531 * (SEMVER-MINOR) provide hook for custom process.exit() behaviour (Anna Henningsen) https://github.com/nodejs/node/pull/32531 fs: * (SEMVER-MINOR) implement lutimes (Maël Nison) https://github.com/nodejs/node/pull/33399 http: * (SEMVER-MINOR) add maxTotalSockets to agent class (rickyes) https://github.com/nodejs/node/pull/33617 * (SEMVER-MINOR) return this from IncomingMessage#destroy() (Colin Ihrig) https://github.com/nodejs/node/pull/32789 * (SEMVER-MINOR) expose host and protocol on ClientRequest (wenningplus) https://github.com/nodejs/node/pull/33803 http2: * (SEMVER-MINOR) return this for Http2ServerRequest#setTimeout (Pranshu Srivastava) https://github.com/nodejs/node/pull/33994 * (SEMVER-MINOR) do not modify explicity set date headers (Pranshu Srivastava) https://github.com/nodejs/node/pull/33160 module: * (SEMVER-MINOR) named exports for CJS via static analysis (Guy Bedford) https://github.com/nodejs/node/pull/35249 * (SEMVER-MINOR) exports pattern support (Guy Bedford) https://github.com/nodejs/node/pull/34718 * (SEMVER-MINOR) package "imports" field (Guy Bedford) https://github.com/nodejs/node/pull/34117 * (SEMVER-MINOR) deprecate module.parent (Antoine du HAMEL) https://github.com/nodejs/node/pull/32217 n-api: * (SEMVER-MINOR) create N-API version 7 (Gabriel Schulhof) https://github.com/nodejs/node/pull/35199 * (SEMVER-MINOR) support type-tagging objects (Gabriel Schulhof) https://github.com/nodejs/node/pull/28237 n-api,src: * (SEMVER-MINOR) provide asynchronous cleanup hooks (Anna Henningsen) https://github.com/nodejs/node/pull/34572 perf_hooks: * (SEMVER-MINOR) add idleTime and event loop util (Trevor Norris) https://github.com/nodejs/node/pull/34938 timers: * (SEMVER-MINOR) allow timers to be used as primitives (Denys Otrishko) https://github.com/nodejs/node/pull/34017 tls: * (SEMVER-MINOR) make 'createSecureContext' honor more options (Mateusz Krawczuk) https://github.com/nodejs/node/pull/33974 worker: * (SEMVER-MINOR) add public method for marking objects as untransferable (Anna Henningsen) https://github.com/nodejs/node/pull/33979 * (SEMVER-MINOR) emit `'messagerror'` events for failed deserialization (Anna Henningsen) https://github.com/nodejs/node/pull/33772 * (SEMVER-MINOR) allow passing JS wrapper objects via postMessage (Anna Henningsen) https://github.com/nodejs/node/pull/33772 * (SEMVER-MINOR) allow transferring/cloning generic BaseObjects (Anna Henningsen) https://github.com/nodejs/node/pull/33772 * (SEMVER-MINOR) add option to track unmanaged file descriptors (Anna Henningsen) https://github.com/nodejs/node/pull/34303 * (SEMVER-MINOR) add stack size resource limit option (Anna Henningsen) https://github.com/nodejs/node/pull/33085 worker,fs: * (SEMVER-MINOR) make FileHandle transferable (Anna Henningsen) https://github.com/nodejs/node/pull/33772 zlib: * (SEMVER-MINOR) add `maxOutputLength` option (unknown) https://github.com/nodejs/node/pull/33516 * switch to lazy init for zlib streams (Andrey Pechkurov) https://github.com/nodejs/node/pull/34048 PR-URL: https://github.com/nodejs/node/pull/35401
2020-09-28 10:54:13 -07:00
added:
- v14.5.0
- v12.19.0
-->
* `object` {any} Any arbitrary JavaScript value.
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.
In particular, this makes sense for objects that can be cloned, rather than
transferred, and which are used by other objects on the sending side.
For example, Node.js marks the `ArrayBuffer`s it uses for its
[`Buffer` pool][`Buffer.allocUnsafe()`] with this.
This operation cannot be undone.
```mjs
import { MessageChannel, markAsUntransferable } from 'node:worker_threads';
const pooledBuffer = new ArrayBuffer(8);
const typedArray1 = new Uint8Array(pooledBuffer);
const typedArray2 = new Float64Array(pooledBuffer);
markAsUntransferable(pooledBuffer);
const { port1 } = new MessageChannel();
try {
// This will throw an error, because pooledBuffer is not transferable.
port1.postMessage(typedArray1, [ typedArray1.buffer ]);
} catch (error) {
// error.name === 'DataCloneError'
}
// The following line prints the contents of typedArray1 -- it still owns
// its memory and has not been transferred. Without
// `markAsUntransferable()`, this would print an empty Uint8Array and the
// postMessage call would have succeeded.
// typedArray2 is intact as well.
console.log(typedArray1);
console.log(typedArray2);
```
```cjs
'use strict';
const { MessageChannel, markAsUntransferable } = require('node:worker_threads');
const pooledBuffer = new ArrayBuffer(8);
const typedArray1 = new Uint8Array(pooledBuffer);
const typedArray2 = new Float64Array(pooledBuffer);
markAsUntransferable(pooledBuffer);
const { port1 } = new MessageChannel();
try {
// This will throw an error, because pooledBuffer is not transferable.
port1.postMessage(typedArray1, [ typedArray1.buffer ]);
} catch (error) {
// error.name === 'DataCloneError'
}
// The following line prints the contents of typedArray1 -- it still owns
// its memory and has not been transferred. Without
// `markAsUntransferable()`, this would print an empty Uint8Array and the
// postMessage call would have succeeded.
// typedArray2 is intact as well.
console.log(typedArray1);
console.log(typedArray2);
```
There is no equivalent to this API in browsers.
## `worker.isMarkedAsUntransferable(object)`
<!-- YAML
2023-10-17, Version 21.0.0 (Current) Notable Changes: doc: * promote fetch/webstreams from experimental to stable (Steven) https://github.com/nodejs/node/pull/45684 esm: * use import attributes instead of import assertions (Antoine du Hamel) https://github.com/nodejs/node/pull/50140 * --experimental-default-type flag to flip module defaults (Geoffrey Booth) https://github.com/nodejs/node/pull/49869 * remove `globalPreload` hook (superseded by `initialize`) (Jacob Smith) https://github.com/nodejs/node/pull/49144 fs: * add flush option to writeFile() functions (Colin Ihrig) https://github.com/nodejs/node/pull/50009 * (SEMVER-MAJOR) add globSync implementation (Moshe Atlow) https://github.com/nodejs/node/pull/47653 http: * (SEMVER-MAJOR) reduce parts in chunked response when corking (Robert Nagy) https://github.com/nodejs/node/pull/50167 lib: * (SEMVER-MINOR) add WebSocket client (Matthew Aitken) https://github.com/nodejs/node/pull/49830 * (SEMVER-MAJOR) add `navigator.hardwareConcurrency` (Yagiz Nizipli) https://github.com/nodejs/node/pull/47769 stream: * optimize Writable (Robert Nagy) https://github.com/nodejs/node/pull/50012 test_runner: * (SEMVER-MAJOR) support passing globs (Moshe Atlow) https://github.com/nodejs/node/pull/47653 vm: * use default HDO when importModuleDynamically is not set (Joyee Cheung) https://github.com/nodejs/node/pull/49950 Semver-Major Commits: * (SEMVER-MAJOR) build: drop support for Visual Studio 2019 (Michaël Zasso) https://github.com/nodejs/node/pull/49051 * (SEMVER-MAJOR) build: bump supported macOS and Xcode versions (Michaël Zasso) https://github.com/nodejs/node/pull/49164 * (SEMVER-MAJOR) crypto: do not overwrite \_writableState.defaultEncoding (Tobias Nießen) https://github.com/nodejs/node/pull/49140 * (SEMVER-MAJOR) deps: bump minimum ICU version to 73 (Michaël Zasso) https://github.com/nodejs/node/pull/49639 * (SEMVER-MAJOR) deps: update V8 to 11.8.172.13 (Michaël Zasso) https://github.com/nodejs/node/pull/49639 * (SEMVER-MAJOR) deps: update llhttp to 9.1.2 (Paolo Insogna) https://github.com/nodejs/node/pull/48981 * (SEMVER-MAJOR) events: validate options of `on` and `once` (Deokjin Kim) https://github.com/nodejs/node/pull/46018 * (SEMVER-MAJOR) fs: adjust `position` validation in reading methods (Livia Medeiros) https://github.com/nodejs/node/pull/42835 * (SEMVER-MAJOR) fs: add globSync implementation (Moshe Atlow) https://github.com/nodejs/node/pull/47653 * (SEMVER-MAJOR) http: reduce parts in chunked response when corking (Robert Nagy) https://github.com/nodejs/node/pull/50167 * (SEMVER-MAJOR) lib: mark URL/URLSearchParams as uncloneable and untransferable (Chengzhong Wu) https://github.com/nodejs/node/pull/47497 * (SEMVER-MAJOR) lib: remove aix directory case for package reader (Yagiz Nizipli) https://github.com/nodejs/node/pull/48605 * (SEMVER-MAJOR) lib: add `navigator.hardwareConcurrency` (Yagiz Nizipli) https://github.com/nodejs/node/pull/47769 * (SEMVER-MAJOR) lib: runtime deprecate punycode (Yagiz Nizipli) https://github.com/nodejs/node/pull/47202 * (SEMVER-MAJOR) module: harmonize error code between ESM and CJS (Antoine du Hamel) https://github.com/nodejs/node/pull/48606 * (SEMVER-MAJOR) net: do not treat `server.maxConnections=0` as `Infinity` (ignoramous) https://github.com/nodejs/node/pull/48276 * (SEMVER-MAJOR) net: only defer \_final call when connecting (Jason Zhang) https://github.com/nodejs/node/pull/47385 * (SEMVER-MAJOR) node-api: rename internal NAPI\_VERSION definition (Chengzhong Wu) https://github.com/nodejs/node/pull/48501 * (SEMVER-MAJOR) src: update NODE\_MODULE\_VERSION to 120 (Michaël Zasso) https://github.com/nodejs/node/pull/49639 * (SEMVER-MAJOR) src: throw DOMException on cloning non-serializable objects (Chengzhong Wu) https://github.com/nodejs/node/pull/47839 * (SEMVER-MAJOR) src: throw DataCloneError on transfering untransferable objects (Chengzhong Wu) https://github.com/nodejs/node/pull/47604 * (SEMVER-MAJOR) stream: use private properties for strategies (Yagiz Nizipli) https://github.com/nodejs/node/pull/47218 * (SEMVER-MAJOR) stream: use private properties for encoding (Yagiz Nizipli) https://github.com/nodejs/node/pull/47218 * (SEMVER-MAJOR) stream: use private properties for compression (Yagiz Nizipli) https://github.com/nodejs/node/pull/47218 * (SEMVER-MAJOR) test\_runner: disallow array in `run` options (Raz Luvaton) https://github.com/nodejs/node/pull/49935 * (SEMVER-MAJOR) test\_runner: support passing globs (Moshe Atlow) https://github.com/nodejs/node/pull/47653 * (SEMVER-MAJOR) tls: use `validateNumber` for `options.minDHSize` (Deokjin Kim) https://github.com/nodejs/node/pull/49973 * (SEMVER-MAJOR) tls: use validateFunction for `options.checkServerIdentity` (Deokjin Kim) https://github.com/nodejs/node/pull/49896 * (SEMVER-MAJOR) util: runtime deprecate `promisify`-ing a function returning a `Promise` (Antoine du Hamel) https://github.com/nodejs/node/pull/49609 * (SEMVER-MAJOR) vm: freeze `dependencySpecifiers` array (Antoine du Hamel) https://github.com/nodejs/node/pull/49720 PR-URL: https://github.com/nodejs/node/pull/49870 Co-authored-by: Michaël Zasso <targos@protonmail.com>
2023-09-26 15:03:53 +08:00
added: v21.0.0
-->
* `object` {any} Any JavaScript value.
* Returns: {boolean}
Check if an object is marked as not transferable with
[`markAsUntransferable()`][].
```mjs
import { markAsUntransferable, isMarkedAsUntransferable } from 'node:worker_threads';
const pooledBuffer = new ArrayBuffer(8);
markAsUntransferable(pooledBuffer);
isMarkedAsUntransferable(pooledBuffer); // Returns true.
```
```cjs
'use strict';
const { markAsUntransferable, isMarkedAsUntransferable } = require('node:worker_threads');
const pooledBuffer = new ArrayBuffer(8);
markAsUntransferable(pooledBuffer);
isMarkedAsUntransferable(pooledBuffer); // Returns true.
```
There is no equivalent to this API in browsers.
## `worker.markAsUncloneable(object)`
<!-- YAML
2024-10-16, Version 22.10.0 (Current) Notable changes: crypto: * (SEMVER-MINOR) add `KeyObject.prototype.toCryptoKey` (Filip Skokan) https://github.com/nodejs/node/pull/55262 * (SEMVER-MINOR) add Date fields for `validTo` and `validFrom` (Andrew Moon) https://github.com/nodejs/node/pull/54159 doc: * add abmusse to collaborators (Abdirahim Musse) https://github.com/nodejs/node/pull/55086 http2: * (SEMVER-MINOR) expose `nghttp2_option_set_stream_reset_rate_limit` as an option (Maël Nison) https://github.com/nodejs/node/pull/54875 lib: * (SEMVER-MINOR) propagate aborted state to dependent signals before firing events (jazelly) https://github.com/nodejs/node/pull/54826 module: * (SEMVER-MINOR) support loading entrypoint as url (RedYetiDev) https://github.com/nodejs/node/pull/54933 * (SEMVER-MINOR) implement the `"module-sync"` exports condition (Joyee Cheung) https://github.com/nodejs/node/pull/54648 * (SEMVER-MINOR) implement `flushCompileCache()` (Joyee Cheung) https://github.com/nodejs/node/pull/54971 * (SEMVER-MINOR) throw when invalid argument is passed to `enableCompileCache()` (Joyee Cheung) https://github.com/nodejs/node/pull/54971 * (SEMVER-MINOR) write compile cache to temporary file and then rename it (Joyee Cheung) https://github.com/nodejs/node/pull/54971 process: * (SEMVER-MINOR) add `process.features.require_module` (Joyee Cheung) https://github.com/nodejs/node/pull/55241 * (SEMVER-MINOR) add `process.features.typescript` (Aviv Keller) https://github.com/nodejs/node/pull/54295 src: * mark `node --run` as stable (Yagiz Nizipli) https://github.com/nodejs/node/pull/53763 test_runner: * (SEMVER-MINOR) support custom arguments in `run()` (Aviv Keller) https://github.com/nodejs/node/pull/55126 * (SEMVER-MINOR) add `'test:summary'` event (Colin Ihrig) https://github.com/nodejs/node/pull/54851 * (SEMVER-MINOR) add support for coverage via `run()` (Chemi Atlow) https://github.com/nodejs/node/pull/53937 worker: * (SEMVER-MINOR) add `markAsUncloneable` api (Jason Zhang) https://github.com/nodejs/node/pull/55234 PR-URL: https://github.com/nodejs/node/pull/55343
2024-10-10 00:12:22 +02:00
added:
- v23.0.0
- v22.10.0
-->
* `object` {any} Any arbitrary JavaScript value.
Mark an object as not cloneable. If `object` is used as [`message`](#event-message) in
a [`port.postMessage()`][] call, an error is thrown. This is a no-op if `object` is a
primitive value.
This has no effect on `ArrayBuffer`, or any `Buffer` like objects.
This operation cannot be undone.
```mjs
import { markAsUncloneable } from 'node:worker_threads';
const anyObject = { foo: 'bar' };
markAsUncloneable(anyObject);
const { port1 } = new MessageChannel();
try {
// This will throw an error, because anyObject is not cloneable.
port1.postMessage(anyObject);
} catch (error) {
// error.name === 'DataCloneError'
}
```
```cjs
'use strict';
const { markAsUncloneable } = require('node:worker_threads');
const anyObject = { foo: 'bar' };
markAsUncloneable(anyObject);
const { port1 } = new MessageChannel();
try {
// This will throw an error, because anyObject is not cloneable.
port1.postMessage(anyObject);
} catch (error) {
// error.name === 'DataCloneError'
}
```
There is no equivalent to this API in browsers.
## `worker.moveMessagePortToContext(port, contextifiedSandbox)`
<!-- YAML
2019-03-28, Version 11.13.0 (Current) Notable changes: * crypto * Allow deriving public from private keys (Tobias Nießen) [#26278](https://github.com/nodejs/node/pull/26278). * events * Added a `once` function to use `EventEmitter` with promises (Matteo Collina) [#26078](https://github.com/nodejs/node/pull/26078). * tty * Added a `hasColors` method to `WriteStream` (Ruben Bridgewater) [#26247](https://github.com/nodejs/node/pull/26247). * Added NO_COLOR and FORCE_COLOR support (Ruben Bridgewater) [#26485](https://github.com/nodejs/node/pull/26485). * v8 * Added `v8.getHeapSnapshot` and `v8.writeHeapSnapshot` to generate snapshots in the format used by tools such as Chrome DevTools (James M Snell) [#26501](https://github.com/nodejs/node/pull/26501). * worker * Added `worker.moveMessagePortToContext`. This enables using MessagePorts in different vm.Contexts, aiding with the isolation that the vm module seeks to provide (Anna Henningsen) [#26497](https://github.com/nodejs/node/pull/26497). * C++ API * `AddPromiseHook` is now deprecated. This API was added to fill an use case that is served by `async_hooks`, since that has `Promise` support (Anna Henningsen) [#26529](https://github.com/nodejs/node/pull/26529). * Added a `Stop` API to shut down Node.js while it is running (Gireesh Punathil) [#21283](https://github.com/nodejs/node/pull/21283). * meta * [Gireesh Punathil](https://github.com/gireeshpunathil) is now a member of the Technical Steering Committee [#26657](https://github.com/nodejs/node/pull/26657). * Added [Yongsheng Zhang](https://github.com/ZYSzys) to collaborators [#26730](https://github.com/nodejs/node/pull/26730). PR-URL: https://github.com/nodejs/node/pull/26949
2019-03-27 22:43:03 +01:00
added: v11.13.0
-->
* `port` {MessagePort} The message port to transfer.
* `contextifiedSandbox` {Object} A [contextified][] object as returned by the
`vm.createContext()` method.
* Returns: {MessagePort}
Transfer a `MessagePort` to a different [`vm`][] Context. The original `port`
object is rendered unusable, and the returned `MessagePort` instance
takes its place.
The returned `MessagePort` is an object in the target context and
inherits from its global `Object` class. Objects passed to the
[`port.onmessage()`][] listener are also created in the target context
and inherit from its global `Object` class.
However, the created `MessagePort` no longer inherits from
{EventTarget}, and only [`port.onmessage()`][] can be used to receive
events using it.
## `worker.parentPort`
<!-- YAML
added: v10.5.0
-->
* {null|MessagePort}
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')`.
```mjs
import { Worker, isMainThread, parentPort } from 'node:worker_threads';
if (isMainThread) {
const worker = new Worker(new URL(import.meta.url));
worker.once('message', (message) => {
console.log(message); // Prints 'Hello, world!'.
});
worker.postMessage('Hello, world!');
} else {
// When a message from the parent thread is received, send it back:
parentPort.once('message', (message) => {
parentPort.postMessage(message);
});
}
```
```cjs
'use strict';
const { Worker, isMainThread, parentPort } = require('node:worker_threads');
if (isMainThread) {
const worker = new Worker(__filename);
worker.once('message', (message) => {
console.log(message); // Prints 'Hello, world!'.
});
worker.postMessage('Hello, world!');
} else {
// When a message from the parent thread is received, send it back:
parentPort.once('message', (message) => {
parentPort.postMessage(message);
});
}
```
## `worker.postMessageToThread(threadId, value[, transferList][, timeout])`
<!-- YAML
added:
- v22.5.0
- v20.19.0
-->
> Stability: 1.1 - Active development
* `threadId` {number} The target thread ID. If the thread ID is invalid, a
[`ERR_WORKER_MESSAGING_FAILED`][] error will be thrown. If the target thread ID is the current thread ID,
a [`ERR_WORKER_MESSAGING_SAME_THREAD`][] error will be thrown.
* `value` {any} The value to send.
* `transferList` {Object\[]} If one or more `MessagePort`-like objects are passed in `value`,
a `transferList` is required for those items or [`ERR_MISSING_MESSAGE_PORT_IN_TRANSFER_LIST`][] is thrown.
See [`port.postMessage()`][] for more information.
* `timeout` {number} Time to wait for the message to be delivered in milliseconds.
By default it's `undefined`, which means wait forever. If the operation times out,
a [`ERR_WORKER_MESSAGING_TIMEOUT`][] error is thrown.
* Returns: {Promise} A promise which is fulfilled if the message was successfully processed by destination thread.
Sends a value to another worker, identified by its thread ID.
If the target thread has no listener for the `workerMessage` event, then the operation will throw
a [`ERR_WORKER_MESSAGING_FAILED`][] error.
If the target thread threw an error while processing the `workerMessage` event, then the operation will throw
a [`ERR_WORKER_MESSAGING_ERRORED`][] error.
This method should be used when the target thread is not the direct
parent or child of the current thread.
If the two threads are parent-children, use the [`require('node:worker_threads').parentPort.postMessage()`][]
and the [`worker.postMessage()`][] to let the threads communicate.
The example below shows the use of of `postMessageToThread`: it creates 10 nested threads,
the last one will try to communicate with the main thread.
```mjs
import process from 'node:process';
import {
postMessageToThread,
threadId,
workerData,
Worker,
} from 'node:worker_threads';
const channel = new BroadcastChannel('sync');
const level = workerData?.level ?? 0;
if (level < 10) {
const worker = new Worker(new URL(import.meta.url), {
workerData: { level: level + 1 },
});
}
if (level === 0) {
process.on('workerMessage', (value, source) => {
console.log(`${source} -> ${threadId}:`, value);
postMessageToThread(source, { message: 'pong' });
});
} else if (level === 10) {
process.on('workerMessage', (value, source) => {
console.log(`${source} -> ${threadId}:`, value);
channel.postMessage('done');
channel.close();
});
await postMessageToThread(0, { message: 'ping' });
}
channel.onmessage = channel.close;
```
```cjs
'use strict';
const process = require('node:process');
const {
postMessageToThread,
threadId,
workerData,
Worker,
} = require('node:worker_threads');
const channel = new BroadcastChannel('sync');
const level = workerData?.level ?? 0;
if (level < 10) {
const worker = new Worker(__filename, {
workerData: { level: level + 1 },
});
}
if (level === 0) {
process.on('workerMessage', (value, source) => {
console.log(`${source} -> ${threadId}:`, value);
postMessageToThread(source, { message: 'pong' });
});
} else if (level === 10) {
process.on('workerMessage', (value, source) => {
console.log(`${source} -> ${threadId}:`, value);
channel.postMessage('done');
channel.close();
});
postMessageToThread(0, { message: 'ping' });
}
channel.onmessage = channel.close;
```
## `worker.receiveMessageOnPort(port)`
<!-- YAML
added: v12.3.0
changes:
- version: v15.12.0
pr-url: https://github.com/nodejs/node/pull/37535
description: The port argument can also refer to a `BroadcastChannel` now.
-->
* `port` {MessagePort|BroadcastChannel}
* Returns: {Object|undefined}
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.
```mjs
import { MessageChannel, receiveMessageOnPort } from 'node:worker_threads';
const { port1, port2 } = new MessageChannel();
port1.postMessage({ hello: 'world' });
console.log(receiveMessageOnPort(port2));
// Prints: { message: { hello: 'world' } }
console.log(receiveMessageOnPort(port2));
// Prints: undefined
```
```cjs
'use strict';
const { MessageChannel, receiveMessageOnPort } = require('node:worker_threads');
const { port1, port2 } = new MessageChannel();
port1.postMessage({ hello: 'world' });
console.log(receiveMessageOnPort(port2));
// Prints: { message: { hello: 'world' } }
console.log(receiveMessageOnPort(port2));
// Prints: undefined
```
When this function is used, no `'message'` event is emitted and the
`onmessage` listener is not invoked.
## `worker.resourceLimits`
<!-- YAML
added:
- v13.2.0
- v12.16.0
-->
* {Object}
* `maxYoungGenerationSizeMb` {number}
* `maxOldGenerationSizeMb` {number}
* `codeRangeSizeMb` {number}
* `stackSizeMb` {number}
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.
If this is used in the main thread, its value is an empty object.
## `worker.SHARE_ENV`
<!-- YAML
added: v11.14.0
-->
* {symbol}
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.
```mjs
import process from 'node:process';
import { Worker, SHARE_ENV } from 'node:worker_threads';
new Worker('process.env.SET_IN_WORKER = "foo"', { eval: true, env: SHARE_ENV })
.on('exit', () => {
console.log(process.env.SET_IN_WORKER); // Prints 'foo'.
});
```
```cjs
'use strict';
const { Worker, SHARE_ENV } = require('node:worker_threads');
new Worker('process.env.SET_IN_WORKER = "foo"', { eval: true, env: SHARE_ENV })
.on('exit', () => {
console.log(process.env.SET_IN_WORKER); // Prints 'foo'.
});
```
## `worker.setEnvironmentData(key[, value])`
<!-- YAML
2021-09-28, Version 14.18.0 'Fermium' (LTS) Notable changes: assert: * change status of legacy asserts (James M Snell) https://github.com/nodejs/node/pull/38113 buffer: * (SEMVER-MINOR) introduce Blob (James M Snell) https://github.com/nodejs/node/pull/36811 * (SEMVER-MINOR) add base64url encoding option (Filip Skokan) https://github.com/nodejs/node/pull/36952 child_process: * (SEMVER-MINOR) allow `options.cwd` receive a URL (Khaidi Chu) https://github.com/nodejs/node/pull/38862 * (SEMVER-MINOR) add timeout to spawn and fork (Nitzan Uziely) https://github.com/nodejs/node/pull/37256 * (SEMVER-MINOR) allow promisified exec to be cancel (Carlos Fuentes) https://github.com/nodejs/node/pull/34249 * (SEMVER-MINOR) add 'overlapped' stdio flag (Thiago Padilha) https://github.com/nodejs/node/pull/29412 cli: * (SEMVER-MINOR) add -C alias for --conditions flag (Guy Bedford) https://github.com/nodejs/node/pull/38755 * (SEMVER-MINOR) add --node-memory-debug option (Anna Henningsen) https://github.com/nodejs/node/pull/35537 dns: * (SEMVER-MINOR) add "tries" option to Resolve options (Luan Devecchi) https://github.com/nodejs/node/pull/39610 * (SEMVER-MINOR) allow `--dns-result-order` to change default dns verbatim (Ouyang Yadong) https://github.com/nodejs/node/pull/38099 doc: * (SEMVER-MINOR) add missing change to resolver ctor (Luan Devecchi) https://github.com/nodejs/node/pull/39610 * refactor fs docs structure (James M Snell) https://github.com/nodejs/node/pull/37170 errors: * (SEMVER-MINOR) remove experimental from --enable-source-maps (Benjamin Coe) https://github.com/nodejs/node/pull/37362 esm: * deprecate legacy main lookup for modules (Guy Bedford) https://github.com/nodejs/node/pull/36918 fs: * (SEMVER-MINOR) allow empty string for temp directory prefix (Voltrex) https://github.com/nodejs/node/pull/39028 * (SEMVER-MINOR) allow no-params fsPromises fileHandle read (Nitzan Uziely) https://github.com/nodejs/node/pull/38287 * (SEMVER-MINOR) add support for async iterators to `fsPromises.writeFile` (HiroyukiYagihashi) https://github.com/nodejs/node/pull/37490 * improve fsPromises readFile performance (Nitzan Uziely) https://github.com/nodejs/node/pull/37608 * (SEMVER-MINOR) add fsPromises.watch() (James M Snell) https://github.com/nodejs/node/pull/37179 * (SEMVER-MINOR) allow `position` parameter to be a `BigInt` in read and readSync (Darshan Sen) https://github.com/nodejs/node/pull/36190 http2: * (SEMVER-MINOR) add support for sensitive headers (Anna Henningsen) https://github.com/nodejs/node/pull/34145 * (SEMVER-MINOR) allow setting the local window size of a session (Yongsheng Zhang) https://github.com/nodejs/node/pull/35978 inspector: * mark as stable (Gireesh Punathil) https://github.com/nodejs/node/pull/37748 module: * (SEMVER-MINOR) add support for `URL` to `import.meta.resolve` (Antoine du Hamel) https://github.com/nodejs/node/pull/38587 * (SEMVER-MINOR) add support for `node:`‑prefixed `require(…)` calls (ExE Boss) https://github.com/nodejs/node/pull/37246 net: * (SEMVER-MINOR) introduce net.BlockList (James M Snell) https://github.com/nodejs/node/pull/34625 node-api: * (SEMVER-MINOR) allow retrieval of add-on file name (Gabriel Schulhof) https://github.com/nodejs/node/pull/37195 os: * (SEMVER-MINOR) add os.devNull (Luigi Pinca) https://github.com/nodejs/node/pull/38569 perf_hooks: * (SEMVER-MINOR) introduce createHistogram (James M Snell) https://github.com/nodejs/node/pull/37155 process: * (SEMVER-MINOR) add api to enable source-maps programmatically (legendecas) https://github.com/nodejs/node/pull/39085 * (SEMVER-MINOR) add `'worker'` event (James M Snell) https://github.com/nodejs/node/pull/38659 * (SEMVER-MINOR) add direct access to rss without iterating pages (Adrien Maret) https://github.com/nodejs/node/pull/34291 readline: * (SEMVER-MINOR) add AbortSignal support to interface (Nitzan Uziely) https://github.com/nodejs/node/pull/37932 * (SEMVER-MINOR) add support for the AbortController to the question method (Mattias Runge-Broberg) https://github.com/nodejs/node/pull/33676 * (SEMVER-MINOR) add history event and option to set initial history (Mattias Runge-Broberg) https://github.com/nodejs/node/pull/33662 repl: * (SEMVER-MINOR) add auto‑completion for `node:`‑prefixed `require(…)` calls (ExE Boss) https://github.com/nodejs/node/pull/37246 src: * (SEMVER-MINOR) call overload ctor from the original ctor (Darshan Sen) https://github.com/nodejs/node/pull/39768 * (SEMVER-MINOR) add a constructor overload for CallbackScope (Darshan Sen) https://github.com/nodejs/node/pull/39768 * (SEMVER-MINOR) allow to negate boolean CLI flags (Michaël Zasso) https://github.com/nodejs/node/pull/39023 * (SEMVER-MINOR) add --heapsnapshot-near-heap-limit option (Joyee Cheung) https://github.com/nodejs/node/pull/33010 * (SEMVER-MINOR) add way to get IsolateData and allocator from Environment (Anna Henningsen) https://github.com/nodejs/node/pull/36441 * (SEMVER-MINOR) allow preventing SetPrepareStackTraceCallback (Shelley Vohr) https://github.com/nodejs/node/pull/36447 * (SEMVER-MINOR) add maybe versions of EmitExit and EmitBeforeExit (Anna Henningsen) https://github.com/nodejs/node/pull/35486 stream: * (SEMVER-MINOR) add readableDidRead if has been read from (Robert Nagy) https://github.com/nodejs/node/pull/39589 * (SEMVER-MINOR) pipeline accept Buffer as a valid first argument (Nitzan Uziely) https://github.com/nodejs/node/pull/37739 tls: * (SEMVER-MINOR) allow reading data into a static buffer (Andrey Pechkurov) https://github.com/nodejs/node/pull/35753 tools: * (SEMVER-MINOR) add `Worker` to type-parser (James M Snell) https://github.com/nodejs/node/pull/38659 url: * (SEMVER-MINOR) expose urlToHttpOptions utility (Yongsheng Zhang) https://github.com/nodejs/node/pull/35960 util: * (SEMVER-MINOR) expose toUSVString (Robert Nagy) https://github.com/nodejs/node/pull/39814 v8: * (SEMVER-MINOR) implement v8.stopCoverage() (Joyee Cheung) https://github.com/nodejs/node/pull/33807 * (SEMVER-MINOR) implement v8.takeCoverage() (Joyee Cheung) https://github.com/nodejs/node/pull/33807 worker: * (SEMVER-MINOR) add setEnvironmentData/getEnvironmentData (James M Snell) https://github.com/nodejs/node/pull/37486 PR-URL: https://github.com/nodejs/node/pull/39990
2021-09-04 15:29:35 +02:00
added:
- v15.12.0
- v14.18.0
changes:
2022-04-26, Version 16.15.0 'Gallium' (LTS) Notable changes: Add fetch API Adds experimental support to the fetch API. This adds the `--experimental-fetch` flag that installs the `fetch`, `Request`, `Response`, `Headers`, and `FormData` globals. * (SEMVER-MINOR) add fetch (Michaël Zasso) https://github.com/nodejs/node/pull/41749 * (SEMVER-MINOR) add FormData global when fetch is enabled (Michaël Zasso) https://github.com/nodejs/node/pull/41956 Other notable changes * build: * remove broken x32 arch support (Ben Noordhuis) https://github.com/nodejs/node/pull/41905 * crypto: * (SEMVER-MINOR) add KeyObject.prototype.equals method (Filip Skokan) https://github.com/nodejs/node/pull/42093 * doc: * add @ShogunPanda to collaborators (Paolo Insogna) https://github.com/nodejs/node/pull/42362 * add JakobJingleheimer to collaborators list (Jacob Smith) https://github.com/nodejs/node/pull/42185 * add joesepi to collaborators (Joe Sepi) https://github.com/nodejs/node/pull/41914 * add marsonya to collaborators (Akhil Marsonya) https://github.com/nodejs/node/pull/41991 * deprecate string coercion in `fs.write`, `fs.writeFileSync` (Livia Medeiros) https://github.com/nodejs/node/pull/42149 * deprecate notice for process methods (Yash Ladha) https://github.com/nodejs/node/pull/41587 * esm: * (SEMVER-MINOR) support https remotely and http locally under flag (Bradley Farias) https://github.com/nodejs/node/pull/36328 * module: * (SEMVER-MINOR) unflag esm json modules (Geoffrey Booth) https://github.com/nodejs/node/pull/41736 * node-api: * (SEMVER-MINOR) add node_api_symbol_for() (Darshan Sen) https://github.com/nodejs/node/pull/41329 * process: * deprecate multipleResolves (Benjamin Gruenbaum) https://github.com/nodejs/node/pull/41872 * stream: * (SEMVER-MINOR) support some and every (Benjamin Gruenbaum) https://github.com/nodejs/node/pull/41573 * (SEMVER-MINOR) add toArray (Benjamin Gruenbaum) https://github.com/nodejs/node/pull/41553 * (SEMVER-MINOR) add forEach method (Benjamin Gruenbaum) https://github.com/nodejs/node/pull/41445 PR-URL: https://github.com/nodejs/node/pull/42847
2022-04-23 21:03:46 -04:00
- version:
- v17.5.0
- v16.15.0
pr-url: https://github.com/nodejs/node/pull/41272
description: No longer experimental.
-->
* `key` {any} Any arbitrary, cloneable JavaScript value that can be used as a
{Map} key.
* `value` {any} 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 for the `key` will be deleted.
The `worker.setEnvironmentData()` API sets the content of
`worker.getEnvironmentData()` in the current thread and all new `Worker`
instances spawned from the current context.
## `worker.threadId`
<!-- YAML
added: v10.5.0
-->
* {integer}
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.
## `worker.workerData`
<!-- YAML
added: v10.5.0
-->
An arbitrary JavaScript value that contains a clone of the data passed
to this thread's `Worker` constructor.
The data is cloned as if using [`postMessage()`][`port.postMessage()`],
according to the [HTML structured clone algorithm][].
```mjs
import { Worker, isMainThread, workerData } from 'node:worker_threads';
if (isMainThread) {
const worker = new Worker(new URL(import.meta.url), { workerData: 'Hello, world!' });
} else {
console.log(workerData); // Prints 'Hello, world!'.
}
```
```cjs
'use strict';
const { Worker, isMainThread, workerData } = require('node:worker_threads');
if (isMainThread) {
const worker = new Worker(__filename, { workerData: 'Hello, world!' });
} else {
console.log(workerData); // Prints 'Hello, world!'.
}
```
## Class: `BroadcastChannel extends EventTarget`
<!-- YAML
added: v15.4.0
changes:
2022-04-19, Version 18.0.0 (Current) Notable Changes: Deprecations and Removals: - (SEMVER-MAJOR) fs: runtime deprecate string coercion in `fs.write`, `fs.writeFileSync` (Livia Medeiros) (https://github.com/nodejs/node/pull/42607) - (SEMVER-MAJOR) dns: remove `dns.lookup` and `dnsPromises.lookup` options type coercion (Antoine du Hamel) (https://github.com/nodejs/node/pull/41431) - (SEMVER-MAJOR) process: runtime deprecate multipleResolves (Benjamin Gruenbaum) (https://github.com/nodejs/node/pull/41896) - (SEMVER-MAJOR) stream: remove thenable support (Robert Nagy) (https://github.com/nodejs/node/pull/40773) - (SEMVER-MAJOR) tls: move tls.parseCertString to end-of-life (Tobias Nießen) (https://github.com/nodejs/node/pull/41479) fetch (experimental): An experimental fetch API is available on the global scope by default. The implementation is based upon https://undici.nodejs.org/#/, an HTTP/1.1 client written for Node.js by contributors to the project. Through this addition, the following globals are made available: `fetch` , `FormData`, `Headers`, `Request`, `Response`. Disable this API with the `--no-experimental-fetch` command-line flag. Contributed by Michaël Zasso in https://github.com/nodejs/node/pull/41811. HTTP Timeouts: `server.headersTimeout`, which limits the amount of time the parser will wait to receive the complete HTTP headers, is now set to `60000` (60 seconds) by default. `server.requestTimeout`, which sets the timeout value in milliseconds for receiving the entire request from the client, is now set to `300000` (5 minutes) by default. If these timeouts expire, the server responds with status 408 without forwarding the request to the request listener and then closes the connection. Both timeouts must be set to a non-zero value to protect against potential Denial-of-Service attacks in case the server is deployed without a reverse proxy in front. Contributed by Paolo Insogna in https://github.com/nodejs/node/pull/41263. Test Runner module (experimental): The `node:test` module facilitates the creation of JavaScript tests that report results in TAP format. This module is only available under the `node:` scheme. Contributed by Colin Ihrig in https://github.com/nodejs/node/pull/42325. Toolchain and Compiler Upgrades: - Prebuilt binaries for Linux are now built on Red Hat Enterprise Linux (RHEL) 8 and are compatible with Linux distributions based on glibc 2.28 or later, for example, Debian 10, RHEL 8, Ubuntu 20.04. - Prebuilt binaries for macOS now require macOS 10.15 or later. - For AIX the minimum supported architecture has been raised from Power 7 to Power 8. Prebuilt binaries for 32-bit Windows will initially not be available due to issues building the V8 dependency in Node.js. We hope to restore 32-bit Windows binaries for Node.js 18 with a future V8 update. Node.js does not support running on operating systems that are no longer supported by their vendor. For operating systems where their vendor has planned to end support earlier than April 2025, such as Windows 8.1 (January 2023) and Windows Server 2012 R2 (October 2023), support for Node.js 18 will end at the earlier date. Full details about the supported toolchains and compilers are documented in the Node.js `BUILDING.md` file. Contributed by Richard Lau in https://github.com/nodejs/node/pull/42292, https://github.com/nodejs/node/pull/42604 and https://github.com/nodejs/node/pull/42659 , and Michaël Zasso in https://github.com/nodejs/node/pull/42105 and https://github.com/nodejs/node/pull/42666. V8 10.1: The V8 engine is updated to version 10.1, which is part of Chromium 101. Compared to the version included in Node.js 17.9.0, the following new features are included: - The `findLast` and `findLastIndex` array methods. - Improvements to the `Intl.Locale` API. - The `Intl.supportedValuesOf` function. - Improved performance of class fields and private class methods (the initialization of them is now as fast as ordinary property stores). The data format returned by the serialization API (`v8.serialize(value)`) has changed, and cannot be deserialized by earlier versions of Node.js. On the other hand, it is still possible to deserialize the previous format, as the API is backwards-compatible. Contributed by Michaël Zasso in https://github.com/nodejs/node/pull/42657. Web Streams API (experimental): Node.js now exposes the experimental implementation of the Web Streams API on the global scope. This means the following APIs are now globally available: - `ReadableStream`, `ReadableStreamDefaultReader`, `ReadableStreamBYOBReader`, `ReadableStreamBYOBRequest`, `ReadableByteStreamController`, `ReadableStreamDefaultController`, `TransformStream`, `TransformStreamDefaultController`, `WritableStream`, `WritableStreamDefaultWriter`, `WritableStreamDefaultController`, `ByteLengthQueuingStrategy`, `CountQueuingStrategy`, `TextEncoderStream`, `TextDecoderStream`, `CompressionStream`, `DecompressionStream`. Contributed James Snell in https://github.com/nodejs/node/pull/39062, and Antoine du Hamel in https://github.com/nodejs/node/pull/42225. Other Notable Changes: - (SEMVER-MAJOR) buffer: expose Blob as a global (James M Snell) (https://github.com/nodejs/node/pull/41270) - (SEMVER-MAJOR) child\_process: improve argument validation (Rich Trott) (https://github.com/nodejs/node/pull/41305) - doc: add RafaelGSS to collaborators (RafaelGSS) (https://github.com/nodejs/node/pull/42718) - (SEMVER-MAJOR) http: make TCP noDelay enabled by default (Paolo Insogna) (https://github.com/nodejs/node/pull/42163) - (SEMVER-MAJOR) net: make `server.address()` return an integer for `family` (Antoine du Hamel) (https://github.com/nodejs/node/pull/41431) - (SEMVER-MAJOR) worker: expose BroadcastChannel as a global (James M Snell) (https://github.com/nodejs/node/pull/41271) - (SEMVER-MAJOR) worker: graduate BroadcastChannel to supported (James M Snell) (https://github.com/nodejs/node/pull/41271) Semver-Major Commits: - (SEMVER-MAJOR) assert,util: compare RegExp.lastIndex while using deep equal checks (Ruben Bridgewater) (https://github.com/nodejs/node/pull/41020) - (SEMVER-MAJOR) buffer: refactor `byteLength` to remove outdated optimizations (Rongjian Zhang) (https://github.com/nodejs/node/pull/38545) - (SEMVER-MAJOR) buffer: expose Blob as a global (James M Snell) (https://github.com/nodejs/node/pull/41270) - (SEMVER-MAJOR) buffer: graduate Blob from experimental (James M Snell) (https://github.com/nodejs/node/pull/41270) - (SEMVER-MAJOR) build: make x86 Windows support temporarily experimental (Michaël Zasso) (https://github.com/nodejs/node/pull/42666) - (SEMVER-MAJOR) build: bump macOS deployment target to 10.15 (Richard Lau) (https://github.com/nodejs/node/pull/42292) - (SEMVER-MAJOR) build: downgrade Windows 8.1 and server 2012 R2 to experimental (Michaël Zasso) (https://github.com/nodejs/node/pull/42105) - (SEMVER-MAJOR) child\_process: improve argument validation (Rich Trott) (https://github.com/nodejs/node/pull/41305) - (SEMVER-MAJOR) cluster: make `kill` to be just `process.kill` (Bar Admoni) (https://github.com/nodejs/node/pull/34312) - (SEMVER-MAJOR) crypto: cleanup validation (Mohammed Keyvanzadeh) (https://github.com/nodejs/node/pull/39841) - (SEMVER-MAJOR) crypto: prettify othername in PrintGeneralName (Tobias Nießen) (https://github.com/nodejs/node/pull/42123) - (SEMVER-MAJOR) crypto: fix X509Certificate toLegacyObject (Tobias Nießen) (https://github.com/nodejs/node/pull/42124) - (SEMVER-MAJOR) crypto: use RFC2253 format in PrintGeneralName (Tobias Nießen) (https://github.com/nodejs/node/pull/42002) - (SEMVER-MAJOR) crypto: change default check(Host|Email) behavior (Tobias Nießen) (https://github.com/nodejs/node/pull/41600) - (SEMVER-MAJOR) deps: V8: cherry-pick semver-major commits from 10.2 (Michaël Zasso) (https://github.com/nodejs/node/pull/42657) - (SEMVER-MAJOR) deps: update V8 to 10.1.124.6 (Michaël Zasso) (https://github.com/nodejs/node/pull/42657) - (SEMVER-MAJOR) deps: update V8 to 9.8.177.9 (Michaël Zasso) (https://github.com/nodejs/node/pull/41610) - (SEMVER-MAJOR) deps: update V8 to 9.7.106.18 (Michaël Zasso) (https://github.com/nodejs/node/pull/40907) - (SEMVER-MAJOR) dns: remove `dns.lookup` and `dnsPromises.lookup` options type coercion (Antoine du Hamel) (https://github.com/nodejs/node/pull/41431) - (SEMVER-MAJOR) doc: update minimum glibc requirements for Linux (Richard Lau) (https://github.com/nodejs/node/pull/42659) - (SEMVER-MAJOR) doc: update AIX minimum supported arch (Richard Lau) (https://github.com/nodejs/node/pull/42604) - (SEMVER-MAJOR) fs: runtime deprecate string coercion in `fs.write`, `fs.writeFileSync` (Livia Medeiros) (https://github.com/nodejs/node/pull/42607) - (SEMVER-MAJOR) http: refactor headersTimeout and requestTimeout logic (Paolo Insogna) (https://github.com/nodejs/node/pull/41263) - (SEMVER-MAJOR) http: make TCP noDelay enabled by default (Paolo Insogna) (https://github.com/nodejs/node/pull/42163) - (SEMVER-MAJOR) lib: enable fetch by default (Michaël Zasso) (https://github.com/nodejs/node/pull/41811) - (SEMVER-MAJOR) lib: replace validator and error (Mohammed Keyvanzadeh) (https://github.com/nodejs/node/pull/41678) - (SEMVER-MAJOR) module,repl: support 'node:'-only core modules (Colin Ihrig) (https://github.com/nodejs/node/pull/42325) - (SEMVER-MAJOR) net: make `server.address()` return an integer for `family` (Antoine du Hamel) (https://github.com/nodejs/node/pull/41431) - (SEMVER-MAJOR) process: disallow some uses of Object.defineProperty() on process.env (Himself65) (https://github.com/nodejs/node/pull/28006) - (SEMVER-MAJOR) process: runtime deprecate multipleResolves (Benjamin Gruenbaum) (https://github.com/nodejs/node/pull/41896) - (SEMVER-MAJOR) readline: fix question still called after closed (Xuguang Mei) (https://github.com/nodejs/node/pull/42464) - (SEMVER-MAJOR) stream: remove thenable support (Robert Nagy) (https://github.com/nodejs/node/pull/40773) - (SEMVER-MAJOR) stream: expose web streams globals, remove runtime experimental warning (Antoine du Hamel) (https://github.com/nodejs/node/pull/42225) - (SEMVER-MAJOR) stream: need to cleanup event listeners if last stream is readable (Xuguang Mei) (https://github.com/nodejs/node/pull/41954) - (SEMVER-MAJOR) stream: revert revert `map` spec compliance (Benjamin Gruenbaum) (https://github.com/nodejs/node/pull/41933) - (SEMVER-MAJOR) stream: throw invalid arg type from End Of Stream (Jithil P Ponnan) (https://github.com/nodejs/node/pull/41766) - (SEMVER-MAJOR) stream: don't emit finish after destroy (Robert Nagy) (https://github.com/nodejs/node/pull/40852) - (SEMVER-MAJOR) stream: add errored and closed props (Robert Nagy) (https://github.com/nodejs/node/pull/40696) - (SEMVER-MAJOR) test: add initial test module (Colin Ihrig) (https://github.com/nodejs/node/pull/42325) - (SEMVER-MAJOR) timers: refactor internal classes to ES2015 syntax (Rabbit) (https://github.com/nodejs/node/pull/37408) - (SEMVER-MAJOR) tls: represent registeredID numerically always (Tobias Nießen) (https://github.com/nodejs/node/pull/41561) - (SEMVER-MAJOR) tls: move tls.parseCertString to end-of-life (Tobias Nießen) (https://github.com/nodejs/node/pull/41479) - (SEMVER-MAJOR) url: throw on NULL in IPv6 hostname (Rich Trott) (https://github.com/nodejs/node/pull/42313) - (SEMVER-MAJOR) v8: make v8.writeHeapSnapshot() error codes consistent (Darshan Sen) (https://github.com/nodejs/node/pull/42577) - (SEMVER-MAJOR) v8: make writeHeapSnapshot throw if fopen fails (Antonio Román) (https://github.com/nodejs/node/pull/41373) - (SEMVER-MAJOR) worker: expose BroadcastChannel as a global (James M Snell) (https://github.com/nodejs/node/pull/41271) - (SEMVER-MAJOR) worker: graduate BroadcastChannel to supported (James M Snell) (https://github.com/nodejs/node/pull/41271) PR-URL: https://github.com/nodejs/node/pull/42262
2022-03-08 01:39:47 +00:00
- version: v18.0.0
pr-url: https://github.com/nodejs/node/pull/41271
description: No longer experimental.
-->
Instances of `BroadcastChannel` allow asynchronous one-to-many communication
with all other `BroadcastChannel` instances bound to the same channel name.
```mjs
import {
isMainThread,
BroadcastChannel,
Worker,
} from 'node:worker_threads';
const bc = new BroadcastChannel('hello');
if (isMainThread) {
let c = 0;
bc.onmessage = (event) => {
console.log(event.data);
if (++c === 10) bc.close();
};
for (let n = 0; n < 10; n++)
new Worker(new URL(import.meta.url));
} else {
bc.postMessage('hello from every worker');
bc.close();
}
```
```cjs
'use strict';
const {
isMainThread,
BroadcastChannel,
Worker,
} = require('node:worker_threads');
const bc = new BroadcastChannel('hello');
if (isMainThread) {
let c = 0;
bc.onmessage = (event) => {
console.log(event.data);
if (++c === 10) bc.close();
};
for (let n = 0; n < 10; n++)
new Worker(__filename);
} else {
bc.postMessage('hello from every worker');
bc.close();
}
```
### `new BroadcastChannel(name)`
<!-- YAML
added: v15.4.0
-->
* `name` {any} The name of the channel to connect to. Any JavaScript value
that can be converted to a string using `` `${name}` `` is permitted.
### `broadcastChannel.close()`
<!-- YAML
added: v15.4.0
-->
Closes the `BroadcastChannel` connection.
### `broadcastChannel.onmessage`
<!-- YAML
added: v15.4.0
-->
* Type: {Function} Invoked with a single `MessageEvent` argument
when a message is received.
### `broadcastChannel.onmessageerror`
<!-- YAML
added: v15.4.0
-->
* Type: {Function} Invoked with a received message cannot be
deserialized.
### `broadcastChannel.postMessage(message)`
<!-- YAML
added: v15.4.0
-->
* `message` {any} Any cloneable JavaScript value.
### `broadcastChannel.ref()`
<!-- YAML
added: v15.4.0
-->
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.
### `broadcastChannel.unref()`
<!-- YAML
added: v15.4.0
-->
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.
## Class: `MessageChannel`
<!-- YAML
added: v10.5.0
-->
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.
```mjs
import { MessageChannel } from 'node:worker_threads';
const { port1, port2 } = new MessageChannel();
port1.on('message', (message) => console.log('received', message));
port2.postMessage({ foo: 'bar' });
// Prints: received { foo: 'bar' } from the `port1.on('message')` listener
```
```cjs
'use strict';
const { MessageChannel } = require('node:worker_threads');
const { port1, port2 } = new MessageChannel();
port1.on('message', (message) => console.log('received', message));
port2.postMessage({ foo: 'bar' });
// Prints: received { foo: 'bar' } from the `port1.on('message')` listener
```
## Class: `MessagePort`
<!-- YAML
added: v10.5.0
changes:
- version:
- v14.7.0
pr-url: https://github.com/nodejs/node/pull/34057
description: This class now inherits from `EventTarget` rather than
from `EventEmitter`.
-->
* Extends: {EventTarget}
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.
This implementation matches [browser `MessagePort`][]s.
### Event: `'close'`
<!-- YAML
added: v10.5.0
-->
The `'close'` event is emitted once either side of the channel has been
disconnected.
```mjs
import { MessageChannel } from 'node:worker_threads';
const { port1, port2 } = new MessageChannel();
// Prints:
// foobar
// closed!
port2.on('message', (message) => console.log(message));
port2.on('close', () => console.log('closed!'));
port1.postMessage('foobar');
port1.close();
```
```cjs
'use strict';
const { MessageChannel } = require('node:worker_threads');
const { port1, port2 } = new MessageChannel();
// Prints:
// foobar
// closed!
port2.on('message', (message) => console.log(message));
port2.on('close', () => console.log('closed!'));
port1.postMessage('foobar');
port1.close();
```
### Event: `'message'`
<!-- YAML
added: v10.5.0
-->
* `value` {any} The transmitted value
The `'message'` event is emitted for any incoming message, containing the cloned
input of [`port.postMessage()`][].
Listeners on this event receive a clone of the `value` parameter as passed
to `postMessage()` and no further arguments.
### Event: `'messageerror'`
<!-- YAML
2020-10-06, Version 12.19.0 'Erbium' (LTS) Notable changes: assert: * (SEMVER-MINOR) port common.mustCall() to assert (ConorDavenport) https://github.com/nodejs/node/pull/31982 async_hooks: * (SEMVER-MINOR) add AsyncResource.bind utility (James M Snell) https://github.com/nodejs/node/pull/34574 buffer: * (SEMVER-MINOR) also alias BigUInt methods (Anna Henningsen) https://github.com/nodejs/node/pull/34960 * (SEMVER-MINOR) alias UInt ➡️ Uint in buffer methods (Anna Henningsen) https://github.com/nodejs/node/pull/34729 build: * (SEMVER-MINOR) add build flag for OSS-Fuzz integration (davkor) https://github.com/nodejs/node/pull/34761 cli: * (SEMVER-MINOR) add alias for report-directory to make it consistent (Ash Cripps) https://github.com/nodejs/node/pull/33587 crypto: * (SEMVER-MINOR) allow KeyObjects in postMessage (Tobias Nießen) https://github.com/nodejs/node/pull/33360 * (SEMVER-MINOR) add randomInt function (Oli Lalonde) https://github.com/nodejs/node/pull/34600 deps: * upgrade to libuv 1.39.0 (Colin Ihrig) https://github.com/nodejs/node/pull/34915 * upgrade npm to 6.14.7 (claudiahdz) https://github.com/nodejs/node/pull/34468 * upgrade to libuv 1.38.1 (Colin Ihrig) https://github.com/nodejs/node/pull/34187 dgram: * (SEMVER-MINOR) add IPv6 scope id suffix to received udp6 dgrams (Pekka Nikander) https://github.com/nodejs/node/pull/14500 * (SEMVER-MINOR) allow typed arrays in .send() (Sarat Addepalli) https://github.com/nodejs/node/pull/22413 doc: * (SEMVER-MINOR) Add maxTotalSockets option to agent constructor (rickyes) https://github.com/nodejs/node/pull/33617 * (SEMVER-MINOR) add basic embedding example documentation (Anna Henningsen) https://github.com/nodejs/node/pull/30467 * add Ricky Zhou to collaborators (rickyes) https://github.com/nodejs/node/pull/34676 * add release key for Ruy Adorno (Ruy Adorno) https://github.com/nodejs/node/pull/34628 * add DerekNonGeneric to collaborators (Derek Lewis) https://github.com/nodejs/node/pull/34602 * add AshCripps to collaborators (Ash Cripps) https://github.com/nodejs/node/pull/34494 * add HarshithaKP to collaborators (Harshitha K P) https://github.com/nodejs/node/pull/34417 * add rexagod to collaborators (Pranshu Srivastava) https://github.com/nodejs/node/pull/34457 * add release key for Richard Lau (Richard Lau) https://github.com/nodejs/node/pull/34397 * add danielleadams to collaborators (Danielle Adams) https://github.com/nodejs/node/pull/34360 * add sxa as collaborator (Stewart X Addison) https://github.com/nodejs/node/pull/34338 * add ruyadorno to collaborators (Ruy Adorno) https://github.com/nodejs/node/pull/34297 * (SEMVER-MAJOR) deprecate process.umask() with no arguments (Colin Ihrig) https://github.com/nodejs/node/pull/32499 embedding: * (SEMVER-MINOR) make Stop() stop Workers (Anna Henningsen) https://github.com/nodejs/node/pull/32531 * (SEMVER-MINOR) provide hook for custom process.exit() behaviour (Anna Henningsen) https://github.com/nodejs/node/pull/32531 fs: * (SEMVER-MINOR) implement lutimes (Maël Nison) https://github.com/nodejs/node/pull/33399 http: * (SEMVER-MINOR) add maxTotalSockets to agent class (rickyes) https://github.com/nodejs/node/pull/33617 * (SEMVER-MINOR) return this from IncomingMessage#destroy() (Colin Ihrig) https://github.com/nodejs/node/pull/32789 * (SEMVER-MINOR) expose host and protocol on ClientRequest (wenningplus) https://github.com/nodejs/node/pull/33803 http2: * (SEMVER-MINOR) return this for Http2ServerRequest#setTimeout (Pranshu Srivastava) https://github.com/nodejs/node/pull/33994 * (SEMVER-MINOR) do not modify explicity set date headers (Pranshu Srivastava) https://github.com/nodejs/node/pull/33160 module: * (SEMVER-MINOR) named exports for CJS via static analysis (Guy Bedford) https://github.com/nodejs/node/pull/35249 * (SEMVER-MINOR) exports pattern support (Guy Bedford) https://github.com/nodejs/node/pull/34718 * (SEMVER-MINOR) package "imports" field (Guy Bedford) https://github.com/nodejs/node/pull/34117 * (SEMVER-MINOR) deprecate module.parent (Antoine du HAMEL) https://github.com/nodejs/node/pull/32217 n-api: * (SEMVER-MINOR) create N-API version 7 (Gabriel Schulhof) https://github.com/nodejs/node/pull/35199 * (SEMVER-MINOR) support type-tagging objects (Gabriel Schulhof) https://github.com/nodejs/node/pull/28237 n-api,src: * (SEMVER-MINOR) provide asynchronous cleanup hooks (Anna Henningsen) https://github.com/nodejs/node/pull/34572 perf_hooks: * (SEMVER-MINOR) add idleTime and event loop util (Trevor Norris) https://github.com/nodejs/node/pull/34938 timers: * (SEMVER-MINOR) allow timers to be used as primitives (Denys Otrishko) https://github.com/nodejs/node/pull/34017 tls: * (SEMVER-MINOR) make 'createSecureContext' honor more options (Mateusz Krawczuk) https://github.com/nodejs/node/pull/33974 worker: * (SEMVER-MINOR) add public method for marking objects as untransferable (Anna Henningsen) https://github.com/nodejs/node/pull/33979 * (SEMVER-MINOR) emit `'messagerror'` events for failed deserialization (Anna Henningsen) https://github.com/nodejs/node/pull/33772 * (SEMVER-MINOR) allow passing JS wrapper objects via postMessage (Anna Henningsen) https://github.com/nodejs/node/pull/33772 * (SEMVER-MINOR) allow transferring/cloning generic BaseObjects (Anna Henningsen) https://github.com/nodejs/node/pull/33772 * (SEMVER-MINOR) add option to track unmanaged file descriptors (Anna Henningsen) https://github.com/nodejs/node/pull/34303 * (SEMVER-MINOR) add stack size resource limit option (Anna Henningsen) https://github.com/nodejs/node/pull/33085 worker,fs: * (SEMVER-MINOR) make FileHandle transferable (Anna Henningsen) https://github.com/nodejs/node/pull/33772 zlib: * (SEMVER-MINOR) add `maxOutputLength` option (unknown) https://github.com/nodejs/node/pull/33516 * switch to lazy init for zlib streams (Andrey Pechkurov) https://github.com/nodejs/node/pull/34048 PR-URL: https://github.com/nodejs/node/pull/35401
2020-09-28 10:54:13 -07:00
added:
- v14.5.0
- v12.19.0
-->
* `error` {Error} An Error object
The `'messageerror'` event is emitted when deserializing a message failed.
Currently, this event is emitted when there is an error occurring while
instantiating the posted JS object on the receiving end. Such situations
are rare, but can happen, for instance, when certain Node.js API objects
are received in a `vm.Context` (where Node.js APIs are currently
unavailable).
### `port.close()`
<!-- YAML
added: v10.5.0
-->
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`.
The [`'close'` event][] is emitted on both `MessagePort` instances that
are part of the channel.
### `port.postMessage(value[, transferList])`
<!-- YAML
added: v10.5.0
changes:
2023-10-17, Version 21.0.0 (Current) Notable Changes: doc: * promote fetch/webstreams from experimental to stable (Steven) https://github.com/nodejs/node/pull/45684 esm: * use import attributes instead of import assertions (Antoine du Hamel) https://github.com/nodejs/node/pull/50140 * --experimental-default-type flag to flip module defaults (Geoffrey Booth) https://github.com/nodejs/node/pull/49869 * remove `globalPreload` hook (superseded by `initialize`) (Jacob Smith) https://github.com/nodejs/node/pull/49144 fs: * add flush option to writeFile() functions (Colin Ihrig) https://github.com/nodejs/node/pull/50009 * (SEMVER-MAJOR) add globSync implementation (Moshe Atlow) https://github.com/nodejs/node/pull/47653 http: * (SEMVER-MAJOR) reduce parts in chunked response when corking (Robert Nagy) https://github.com/nodejs/node/pull/50167 lib: * (SEMVER-MINOR) add WebSocket client (Matthew Aitken) https://github.com/nodejs/node/pull/49830 * (SEMVER-MAJOR) add `navigator.hardwareConcurrency` (Yagiz Nizipli) https://github.com/nodejs/node/pull/47769 stream: * optimize Writable (Robert Nagy) https://github.com/nodejs/node/pull/50012 test_runner: * (SEMVER-MAJOR) support passing globs (Moshe Atlow) https://github.com/nodejs/node/pull/47653 vm: * use default HDO when importModuleDynamically is not set (Joyee Cheung) https://github.com/nodejs/node/pull/49950 Semver-Major Commits: * (SEMVER-MAJOR) build: drop support for Visual Studio 2019 (Michaël Zasso) https://github.com/nodejs/node/pull/49051 * (SEMVER-MAJOR) build: bump supported macOS and Xcode versions (Michaël Zasso) https://github.com/nodejs/node/pull/49164 * (SEMVER-MAJOR) crypto: do not overwrite \_writableState.defaultEncoding (Tobias Nießen) https://github.com/nodejs/node/pull/49140 * (SEMVER-MAJOR) deps: bump minimum ICU version to 73 (Michaël Zasso) https://github.com/nodejs/node/pull/49639 * (SEMVER-MAJOR) deps: update V8 to 11.8.172.13 (Michaël Zasso) https://github.com/nodejs/node/pull/49639 * (SEMVER-MAJOR) deps: update llhttp to 9.1.2 (Paolo Insogna) https://github.com/nodejs/node/pull/48981 * (SEMVER-MAJOR) events: validate options of `on` and `once` (Deokjin Kim) https://github.com/nodejs/node/pull/46018 * (SEMVER-MAJOR) fs: adjust `position` validation in reading methods (Livia Medeiros) https://github.com/nodejs/node/pull/42835 * (SEMVER-MAJOR) fs: add globSync implementation (Moshe Atlow) https://github.com/nodejs/node/pull/47653 * (SEMVER-MAJOR) http: reduce parts in chunked response when corking (Robert Nagy) https://github.com/nodejs/node/pull/50167 * (SEMVER-MAJOR) lib: mark URL/URLSearchParams as uncloneable and untransferable (Chengzhong Wu) https://github.com/nodejs/node/pull/47497 * (SEMVER-MAJOR) lib: remove aix directory case for package reader (Yagiz Nizipli) https://github.com/nodejs/node/pull/48605 * (SEMVER-MAJOR) lib: add `navigator.hardwareConcurrency` (Yagiz Nizipli) https://github.com/nodejs/node/pull/47769 * (SEMVER-MAJOR) lib: runtime deprecate punycode (Yagiz Nizipli) https://github.com/nodejs/node/pull/47202 * (SEMVER-MAJOR) module: harmonize error code between ESM and CJS (Antoine du Hamel) https://github.com/nodejs/node/pull/48606 * (SEMVER-MAJOR) net: do not treat `server.maxConnections=0` as `Infinity` (ignoramous) https://github.com/nodejs/node/pull/48276 * (SEMVER-MAJOR) net: only defer \_final call when connecting (Jason Zhang) https://github.com/nodejs/node/pull/47385 * (SEMVER-MAJOR) node-api: rename internal NAPI\_VERSION definition (Chengzhong Wu) https://github.com/nodejs/node/pull/48501 * (SEMVER-MAJOR) src: update NODE\_MODULE\_VERSION to 120 (Michaël Zasso) https://github.com/nodejs/node/pull/49639 * (SEMVER-MAJOR) src: throw DOMException on cloning non-serializable objects (Chengzhong Wu) https://github.com/nodejs/node/pull/47839 * (SEMVER-MAJOR) src: throw DataCloneError on transfering untransferable objects (Chengzhong Wu) https://github.com/nodejs/node/pull/47604 * (SEMVER-MAJOR) stream: use private properties for strategies (Yagiz Nizipli) https://github.com/nodejs/node/pull/47218 * (SEMVER-MAJOR) stream: use private properties for encoding (Yagiz Nizipli) https://github.com/nodejs/node/pull/47218 * (SEMVER-MAJOR) stream: use private properties for compression (Yagiz Nizipli) https://github.com/nodejs/node/pull/47218 * (SEMVER-MAJOR) test\_runner: disallow array in `run` options (Raz Luvaton) https://github.com/nodejs/node/pull/49935 * (SEMVER-MAJOR) test\_runner: support passing globs (Moshe Atlow) https://github.com/nodejs/node/pull/47653 * (SEMVER-MAJOR) tls: use `validateNumber` for `options.minDHSize` (Deokjin Kim) https://github.com/nodejs/node/pull/49973 * (SEMVER-MAJOR) tls: use validateFunction for `options.checkServerIdentity` (Deokjin Kim) https://github.com/nodejs/node/pull/49896 * (SEMVER-MAJOR) util: runtime deprecate `promisify`-ing a function returning a `Promise` (Antoine du Hamel) https://github.com/nodejs/node/pull/49609 * (SEMVER-MAJOR) vm: freeze `dependencySpecifiers` array (Antoine du Hamel) https://github.com/nodejs/node/pull/49720 PR-URL: https://github.com/nodejs/node/pull/49870 Co-authored-by: Michaël Zasso <targos@protonmail.com>
2023-09-26 15:03:53 +08:00
- version: v21.0.0
pr-url: https://github.com/nodejs/node/pull/47604
description: An error is thrown when an untransferable object is in the
transfer list.
2021-09-28, Version 14.18.0 'Fermium' (LTS) Notable changes: assert: * change status of legacy asserts (James M Snell) https://github.com/nodejs/node/pull/38113 buffer: * (SEMVER-MINOR) introduce Blob (James M Snell) https://github.com/nodejs/node/pull/36811 * (SEMVER-MINOR) add base64url encoding option (Filip Skokan) https://github.com/nodejs/node/pull/36952 child_process: * (SEMVER-MINOR) allow `options.cwd` receive a URL (Khaidi Chu) https://github.com/nodejs/node/pull/38862 * (SEMVER-MINOR) add timeout to spawn and fork (Nitzan Uziely) https://github.com/nodejs/node/pull/37256 * (SEMVER-MINOR) allow promisified exec to be cancel (Carlos Fuentes) https://github.com/nodejs/node/pull/34249 * (SEMVER-MINOR) add 'overlapped' stdio flag (Thiago Padilha) https://github.com/nodejs/node/pull/29412 cli: * (SEMVER-MINOR) add -C alias for --conditions flag (Guy Bedford) https://github.com/nodejs/node/pull/38755 * (SEMVER-MINOR) add --node-memory-debug option (Anna Henningsen) https://github.com/nodejs/node/pull/35537 dns: * (SEMVER-MINOR) add "tries" option to Resolve options (Luan Devecchi) https://github.com/nodejs/node/pull/39610 * (SEMVER-MINOR) allow `--dns-result-order` to change default dns verbatim (Ouyang Yadong) https://github.com/nodejs/node/pull/38099 doc: * (SEMVER-MINOR) add missing change to resolver ctor (Luan Devecchi) https://github.com/nodejs/node/pull/39610 * refactor fs docs structure (James M Snell) https://github.com/nodejs/node/pull/37170 errors: * (SEMVER-MINOR) remove experimental from --enable-source-maps (Benjamin Coe) https://github.com/nodejs/node/pull/37362 esm: * deprecate legacy main lookup for modules (Guy Bedford) https://github.com/nodejs/node/pull/36918 fs: * (SEMVER-MINOR) allow empty string for temp directory prefix (Voltrex) https://github.com/nodejs/node/pull/39028 * (SEMVER-MINOR) allow no-params fsPromises fileHandle read (Nitzan Uziely) https://github.com/nodejs/node/pull/38287 * (SEMVER-MINOR) add support for async iterators to `fsPromises.writeFile` (HiroyukiYagihashi) https://github.com/nodejs/node/pull/37490 * improve fsPromises readFile performance (Nitzan Uziely) https://github.com/nodejs/node/pull/37608 * (SEMVER-MINOR) add fsPromises.watch() (James M Snell) https://github.com/nodejs/node/pull/37179 * (SEMVER-MINOR) allow `position` parameter to be a `BigInt` in read and readSync (Darshan Sen) https://github.com/nodejs/node/pull/36190 http2: * (SEMVER-MINOR) add support for sensitive headers (Anna Henningsen) https://github.com/nodejs/node/pull/34145 * (SEMVER-MINOR) allow setting the local window size of a session (Yongsheng Zhang) https://github.com/nodejs/node/pull/35978 inspector: * mark as stable (Gireesh Punathil) https://github.com/nodejs/node/pull/37748 module: * (SEMVER-MINOR) add support for `URL` to `import.meta.resolve` (Antoine du Hamel) https://github.com/nodejs/node/pull/38587 * (SEMVER-MINOR) add support for `node:`‑prefixed `require(…)` calls (ExE Boss) https://github.com/nodejs/node/pull/37246 net: * (SEMVER-MINOR) introduce net.BlockList (James M Snell) https://github.com/nodejs/node/pull/34625 node-api: * (SEMVER-MINOR) allow retrieval of add-on file name (Gabriel Schulhof) https://github.com/nodejs/node/pull/37195 os: * (SEMVER-MINOR) add os.devNull (Luigi Pinca) https://github.com/nodejs/node/pull/38569 perf_hooks: * (SEMVER-MINOR) introduce createHistogram (James M Snell) https://github.com/nodejs/node/pull/37155 process: * (SEMVER-MINOR) add api to enable source-maps programmatically (legendecas) https://github.com/nodejs/node/pull/39085 * (SEMVER-MINOR) add `'worker'` event (James M Snell) https://github.com/nodejs/node/pull/38659 * (SEMVER-MINOR) add direct access to rss without iterating pages (Adrien Maret) https://github.com/nodejs/node/pull/34291 readline: * (SEMVER-MINOR) add AbortSignal support to interface (Nitzan Uziely) https://github.com/nodejs/node/pull/37932 * (SEMVER-MINOR) add support for the AbortController to the question method (Mattias Runge-Broberg) https://github.com/nodejs/node/pull/33676 * (SEMVER-MINOR) add history event and option to set initial history (Mattias Runge-Broberg) https://github.com/nodejs/node/pull/33662 repl: * (SEMVER-MINOR) add auto‑completion for `node:`‑prefixed `require(…)` calls (ExE Boss) https://github.com/nodejs/node/pull/37246 src: * (SEMVER-MINOR) call overload ctor from the original ctor (Darshan Sen) https://github.com/nodejs/node/pull/39768 * (SEMVER-MINOR) add a constructor overload for CallbackScope (Darshan Sen) https://github.com/nodejs/node/pull/39768 * (SEMVER-MINOR) allow to negate boolean CLI flags (Michaël Zasso) https://github.com/nodejs/node/pull/39023 * (SEMVER-MINOR) add --heapsnapshot-near-heap-limit option (Joyee Cheung) https://github.com/nodejs/node/pull/33010 * (SEMVER-MINOR) add way to get IsolateData and allocator from Environment (Anna Henningsen) https://github.com/nodejs/node/pull/36441 * (SEMVER-MINOR) allow preventing SetPrepareStackTraceCallback (Shelley Vohr) https://github.com/nodejs/node/pull/36447 * (SEMVER-MINOR) add maybe versions of EmitExit and EmitBeforeExit (Anna Henningsen) https://github.com/nodejs/node/pull/35486 stream: * (SEMVER-MINOR) add readableDidRead if has been read from (Robert Nagy) https://github.com/nodejs/node/pull/39589 * (SEMVER-MINOR) pipeline accept Buffer as a valid first argument (Nitzan Uziely) https://github.com/nodejs/node/pull/37739 tls: * (SEMVER-MINOR) allow reading data into a static buffer (Andrey Pechkurov) https://github.com/nodejs/node/pull/35753 tools: * (SEMVER-MINOR) add `Worker` to type-parser (James M Snell) https://github.com/nodejs/node/pull/38659 url: * (SEMVER-MINOR) expose urlToHttpOptions utility (Yongsheng Zhang) https://github.com/nodejs/node/pull/35960 util: * (SEMVER-MINOR) expose toUSVString (Robert Nagy) https://github.com/nodejs/node/pull/39814 v8: * (SEMVER-MINOR) implement v8.stopCoverage() (Joyee Cheung) https://github.com/nodejs/node/pull/33807 * (SEMVER-MINOR) implement v8.takeCoverage() (Joyee Cheung) https://github.com/nodejs/node/pull/33807 worker: * (SEMVER-MINOR) add setEnvironmentData/getEnvironmentData (James M Snell) https://github.com/nodejs/node/pull/37486 PR-URL: https://github.com/nodejs/node/pull/39990
2021-09-04 15:29:35 +02:00
- version:
- v15.14.0
- v14.18.0
pr-url: https://github.com/nodejs/node/pull/37917
description: Add 'BlockList' to the list of cloneable types.
2021-09-28, Version 14.18.0 'Fermium' (LTS) Notable changes: assert: * change status of legacy asserts (James M Snell) https://github.com/nodejs/node/pull/38113 buffer: * (SEMVER-MINOR) introduce Blob (James M Snell) https://github.com/nodejs/node/pull/36811 * (SEMVER-MINOR) add base64url encoding option (Filip Skokan) https://github.com/nodejs/node/pull/36952 child_process: * (SEMVER-MINOR) allow `options.cwd` receive a URL (Khaidi Chu) https://github.com/nodejs/node/pull/38862 * (SEMVER-MINOR) add timeout to spawn and fork (Nitzan Uziely) https://github.com/nodejs/node/pull/37256 * (SEMVER-MINOR) allow promisified exec to be cancel (Carlos Fuentes) https://github.com/nodejs/node/pull/34249 * (SEMVER-MINOR) add 'overlapped' stdio flag (Thiago Padilha) https://github.com/nodejs/node/pull/29412 cli: * (SEMVER-MINOR) add -C alias for --conditions flag (Guy Bedford) https://github.com/nodejs/node/pull/38755 * (SEMVER-MINOR) add --node-memory-debug option (Anna Henningsen) https://github.com/nodejs/node/pull/35537 dns: * (SEMVER-MINOR) add "tries" option to Resolve options (Luan Devecchi) https://github.com/nodejs/node/pull/39610 * (SEMVER-MINOR) allow `--dns-result-order` to change default dns verbatim (Ouyang Yadong) https://github.com/nodejs/node/pull/38099 doc: * (SEMVER-MINOR) add missing change to resolver ctor (Luan Devecchi) https://github.com/nodejs/node/pull/39610 * refactor fs docs structure (James M Snell) https://github.com/nodejs/node/pull/37170 errors: * (SEMVER-MINOR) remove experimental from --enable-source-maps (Benjamin Coe) https://github.com/nodejs/node/pull/37362 esm: * deprecate legacy main lookup for modules (Guy Bedford) https://github.com/nodejs/node/pull/36918 fs: * (SEMVER-MINOR) allow empty string for temp directory prefix (Voltrex) https://github.com/nodejs/node/pull/39028 * (SEMVER-MINOR) allow no-params fsPromises fileHandle read (Nitzan Uziely) https://github.com/nodejs/node/pull/38287 * (SEMVER-MINOR) add support for async iterators to `fsPromises.writeFile` (HiroyukiYagihashi) https://github.com/nodejs/node/pull/37490 * improve fsPromises readFile performance (Nitzan Uziely) https://github.com/nodejs/node/pull/37608 * (SEMVER-MINOR) add fsPromises.watch() (James M Snell) https://github.com/nodejs/node/pull/37179 * (SEMVER-MINOR) allow `position` parameter to be a `BigInt` in read and readSync (Darshan Sen) https://github.com/nodejs/node/pull/36190 http2: * (SEMVER-MINOR) add support for sensitive headers (Anna Henningsen) https://github.com/nodejs/node/pull/34145 * (SEMVER-MINOR) allow setting the local window size of a session (Yongsheng Zhang) https://github.com/nodejs/node/pull/35978 inspector: * mark as stable (Gireesh Punathil) https://github.com/nodejs/node/pull/37748 module: * (SEMVER-MINOR) add support for `URL` to `import.meta.resolve` (Antoine du Hamel) https://github.com/nodejs/node/pull/38587 * (SEMVER-MINOR) add support for `node:`‑prefixed `require(…)` calls (ExE Boss) https://github.com/nodejs/node/pull/37246 net: * (SEMVER-MINOR) introduce net.BlockList (James M Snell) https://github.com/nodejs/node/pull/34625 node-api: * (SEMVER-MINOR) allow retrieval of add-on file name (Gabriel Schulhof) https://github.com/nodejs/node/pull/37195 os: * (SEMVER-MINOR) add os.devNull (Luigi Pinca) https://github.com/nodejs/node/pull/38569 perf_hooks: * (SEMVER-MINOR) introduce createHistogram (James M Snell) https://github.com/nodejs/node/pull/37155 process: * (SEMVER-MINOR) add api to enable source-maps programmatically (legendecas) https://github.com/nodejs/node/pull/39085 * (SEMVER-MINOR) add `'worker'` event (James M Snell) https://github.com/nodejs/node/pull/38659 * (SEMVER-MINOR) add direct access to rss without iterating pages (Adrien Maret) https://github.com/nodejs/node/pull/34291 readline: * (SEMVER-MINOR) add AbortSignal support to interface (Nitzan Uziely) https://github.com/nodejs/node/pull/37932 * (SEMVER-MINOR) add support for the AbortController to the question method (Mattias Runge-Broberg) https://github.com/nodejs/node/pull/33676 * (SEMVER-MINOR) add history event and option to set initial history (Mattias Runge-Broberg) https://github.com/nodejs/node/pull/33662 repl: * (SEMVER-MINOR) add auto‑completion for `node:`‑prefixed `require(…)` calls (ExE Boss) https://github.com/nodejs/node/pull/37246 src: * (SEMVER-MINOR) call overload ctor from the original ctor (Darshan Sen) https://github.com/nodejs/node/pull/39768 * (SEMVER-MINOR) add a constructor overload for CallbackScope (Darshan Sen) https://github.com/nodejs/node/pull/39768 * (SEMVER-MINOR) allow to negate boolean CLI flags (Michaël Zasso) https://github.com/nodejs/node/pull/39023 * (SEMVER-MINOR) add --heapsnapshot-near-heap-limit option (Joyee Cheung) https://github.com/nodejs/node/pull/33010 * (SEMVER-MINOR) add way to get IsolateData and allocator from Environment (Anna Henningsen) https://github.com/nodejs/node/pull/36441 * (SEMVER-MINOR) allow preventing SetPrepareStackTraceCallback (Shelley Vohr) https://github.com/nodejs/node/pull/36447 * (SEMVER-MINOR) add maybe versions of EmitExit and EmitBeforeExit (Anna Henningsen) https://github.com/nodejs/node/pull/35486 stream: * (SEMVER-MINOR) add readableDidRead if has been read from (Robert Nagy) https://github.com/nodejs/node/pull/39589 * (SEMVER-MINOR) pipeline accept Buffer as a valid first argument (Nitzan Uziely) https://github.com/nodejs/node/pull/37739 tls: * (SEMVER-MINOR) allow reading data into a static buffer (Andrey Pechkurov) https://github.com/nodejs/node/pull/35753 tools: * (SEMVER-MINOR) add `Worker` to type-parser (James M Snell) https://github.com/nodejs/node/pull/38659 url: * (SEMVER-MINOR) expose urlToHttpOptions utility (Yongsheng Zhang) https://github.com/nodejs/node/pull/35960 util: * (SEMVER-MINOR) expose toUSVString (Robert Nagy) https://github.com/nodejs/node/pull/39814 v8: * (SEMVER-MINOR) implement v8.stopCoverage() (Joyee Cheung) https://github.com/nodejs/node/pull/33807 * (SEMVER-MINOR) implement v8.takeCoverage() (Joyee Cheung) https://github.com/nodejs/node/pull/33807 worker: * (SEMVER-MINOR) add setEnvironmentData/getEnvironmentData (James M Snell) https://github.com/nodejs/node/pull/37486 PR-URL: https://github.com/nodejs/node/pull/39990
2021-09-04 15:29:35 +02:00
- version:
- v15.9.0
- v14.18.0
pr-url: https://github.com/nodejs/node/pull/37155
description: Add 'Histogram' types to the list of cloneable types.
2021-01-14, Version 15.6.0 (Current) PR-URL: https://github.com/nodejs/node/pull/36889 Notable changes: * child_process: * add 'overlapped' stdio flag (Thiago Padilha) (https://github.com/nodejs/node/pull/29412) * support AbortSignal in fork (Benjamin Gruenbaum) (https://github.com/nodejs/node/pull/36603) * crypto: * implement basic secure heap support (James M Snell) (https://github.com/nodejs/node/pull/36779) * fixup bug in keygen error handling (James M Snell) (https://github.com/nodejs/node/pull/36779) * introduce X509Certificate API (James M Snell) (https://github.com/nodejs/node/pull/36804) * implement randomuuid (James M Snell) (https://github.com/nodejs/node/pull/36729) * doc: * update release key for Danielle Adams (Danielle Adams) (https://github.com/nodejs/node/pull/36793) * add dnlup to collaborators (Daniele Belardi) (https://github.com/nodejs/node/pull/36849) * add panva to collaborators (Filip Skokan) (https://github.com/nodejs/node/pull/36802) * add yashLadha to collaborator (Yash Ladha) (https://github.com/nodejs/node/pull/36666) * http: * set lifo as the default scheduling strategy in Agent (Matteo Collina) (https://github.com/nodejs/node/pull/36685) * net: * support abortSignal in server.listen (Nitzan Uziely) (https://github.com/nodejs/node/pull/36623) * process: * add direct access to rss without iterating pages (Adrien Maret) (https://github.com/nodejs/node/pull/34291) * v8: * fix native  constructors (ExE Boss) (https://github.com/nodejs/node/pull/36549)
2021-01-12 08:54:01 -05:00
- version: v15.6.0
pr-url: https://github.com/nodejs/node/pull/36804
description: Added `X509Certificate` to the list of cloneable types.
- version: v15.0.0
pr-url: https://github.com/nodejs/node/pull/35093
description: Added `CryptoKey` to the list of cloneable types.
2020-10-06, Version 12.19.0 'Erbium' (LTS) Notable changes: assert: * (SEMVER-MINOR) port common.mustCall() to assert (ConorDavenport) https://github.com/nodejs/node/pull/31982 async_hooks: * (SEMVER-MINOR) add AsyncResource.bind utility (James M Snell) https://github.com/nodejs/node/pull/34574 buffer: * (SEMVER-MINOR) also alias BigUInt methods (Anna Henningsen) https://github.com/nodejs/node/pull/34960 * (SEMVER-MINOR) alias UInt ➡️ Uint in buffer methods (Anna Henningsen) https://github.com/nodejs/node/pull/34729 build: * (SEMVER-MINOR) add build flag for OSS-Fuzz integration (davkor) https://github.com/nodejs/node/pull/34761 cli: * (SEMVER-MINOR) add alias for report-directory to make it consistent (Ash Cripps) https://github.com/nodejs/node/pull/33587 crypto: * (SEMVER-MINOR) allow KeyObjects in postMessage (Tobias Nießen) https://github.com/nodejs/node/pull/33360 * (SEMVER-MINOR) add randomInt function (Oli Lalonde) https://github.com/nodejs/node/pull/34600 deps: * upgrade to libuv 1.39.0 (Colin Ihrig) https://github.com/nodejs/node/pull/34915 * upgrade npm to 6.14.7 (claudiahdz) https://github.com/nodejs/node/pull/34468 * upgrade to libuv 1.38.1 (Colin Ihrig) https://github.com/nodejs/node/pull/34187 dgram: * (SEMVER-MINOR) add IPv6 scope id suffix to received udp6 dgrams (Pekka Nikander) https://github.com/nodejs/node/pull/14500 * (SEMVER-MINOR) allow typed arrays in .send() (Sarat Addepalli) https://github.com/nodejs/node/pull/22413 doc: * (SEMVER-MINOR) Add maxTotalSockets option to agent constructor (rickyes) https://github.com/nodejs/node/pull/33617 * (SEMVER-MINOR) add basic embedding example documentation (Anna Henningsen) https://github.com/nodejs/node/pull/30467 * add Ricky Zhou to collaborators (rickyes) https://github.com/nodejs/node/pull/34676 * add release key for Ruy Adorno (Ruy Adorno) https://github.com/nodejs/node/pull/34628 * add DerekNonGeneric to collaborators (Derek Lewis) https://github.com/nodejs/node/pull/34602 * add AshCripps to collaborators (Ash Cripps) https://github.com/nodejs/node/pull/34494 * add HarshithaKP to collaborators (Harshitha K P) https://github.com/nodejs/node/pull/34417 * add rexagod to collaborators (Pranshu Srivastava) https://github.com/nodejs/node/pull/34457 * add release key for Richard Lau (Richard Lau) https://github.com/nodejs/node/pull/34397 * add danielleadams to collaborators (Danielle Adams) https://github.com/nodejs/node/pull/34360 * add sxa as collaborator (Stewart X Addison) https://github.com/nodejs/node/pull/34338 * add ruyadorno to collaborators (Ruy Adorno) https://github.com/nodejs/node/pull/34297 * (SEMVER-MAJOR) deprecate process.umask() with no arguments (Colin Ihrig) https://github.com/nodejs/node/pull/32499 embedding: * (SEMVER-MINOR) make Stop() stop Workers (Anna Henningsen) https://github.com/nodejs/node/pull/32531 * (SEMVER-MINOR) provide hook for custom process.exit() behaviour (Anna Henningsen) https://github.com/nodejs/node/pull/32531 fs: * (SEMVER-MINOR) implement lutimes (Maël Nison) https://github.com/nodejs/node/pull/33399 http: * (SEMVER-MINOR) add maxTotalSockets to agent class (rickyes) https://github.com/nodejs/node/pull/33617 * (SEMVER-MINOR) return this from IncomingMessage#destroy() (Colin Ihrig) https://github.com/nodejs/node/pull/32789 * (SEMVER-MINOR) expose host and protocol on ClientRequest (wenningplus) https://github.com/nodejs/node/pull/33803 http2: * (SEMVER-MINOR) return this for Http2ServerRequest#setTimeout (Pranshu Srivastava) https://github.com/nodejs/node/pull/33994 * (SEMVER-MINOR) do not modify explicity set date headers (Pranshu Srivastava) https://github.com/nodejs/node/pull/33160 module: * (SEMVER-MINOR) named exports for CJS via static analysis (Guy Bedford) https://github.com/nodejs/node/pull/35249 * (SEMVER-MINOR) exports pattern support (Guy Bedford) https://github.com/nodejs/node/pull/34718 * (SEMVER-MINOR) package "imports" field (Guy Bedford) https://github.com/nodejs/node/pull/34117 * (SEMVER-MINOR) deprecate module.parent (Antoine du HAMEL) https://github.com/nodejs/node/pull/32217 n-api: * (SEMVER-MINOR) create N-API version 7 (Gabriel Schulhof) https://github.com/nodejs/node/pull/35199 * (SEMVER-MINOR) support type-tagging objects (Gabriel Schulhof) https://github.com/nodejs/node/pull/28237 n-api,src: * (SEMVER-MINOR) provide asynchronous cleanup hooks (Anna Henningsen) https://github.com/nodejs/node/pull/34572 perf_hooks: * (SEMVER-MINOR) add idleTime and event loop util (Trevor Norris) https://github.com/nodejs/node/pull/34938 timers: * (SEMVER-MINOR) allow timers to be used as primitives (Denys Otrishko) https://github.com/nodejs/node/pull/34017 tls: * (SEMVER-MINOR) make 'createSecureContext' honor more options (Mateusz Krawczuk) https://github.com/nodejs/node/pull/33974 worker: * (SEMVER-MINOR) add public method for marking objects as untransferable (Anna Henningsen) https://github.com/nodejs/node/pull/33979 * (SEMVER-MINOR) emit `'messagerror'` events for failed deserialization (Anna Henningsen) https://github.com/nodejs/node/pull/33772 * (SEMVER-MINOR) allow passing JS wrapper objects via postMessage (Anna Henningsen) https://github.com/nodejs/node/pull/33772 * (SEMVER-MINOR) allow transferring/cloning generic BaseObjects (Anna Henningsen) https://github.com/nodejs/node/pull/33772 * (SEMVER-MINOR) add option to track unmanaged file descriptors (Anna Henningsen) https://github.com/nodejs/node/pull/34303 * (SEMVER-MINOR) add stack size resource limit option (Anna Henningsen) https://github.com/nodejs/node/pull/33085 worker,fs: * (SEMVER-MINOR) make FileHandle transferable (Anna Henningsen) https://github.com/nodejs/node/pull/33772 zlib: * (SEMVER-MINOR) add `maxOutputLength` option (unknown) https://github.com/nodejs/node/pull/33516 * switch to lazy init for zlib streams (Andrey Pechkurov) https://github.com/nodejs/node/pull/34048 PR-URL: https://github.com/nodejs/node/pull/35401
2020-09-28 10:54:13 -07:00
- version:
- v14.5.0
- v12.19.0
pr-url: https://github.com/nodejs/node/pull/33360
description: Added `KeyObject` to the list of cloneable types.
2020-10-06, Version 12.19.0 'Erbium' (LTS) Notable changes: assert: * (SEMVER-MINOR) port common.mustCall() to assert (ConorDavenport) https://github.com/nodejs/node/pull/31982 async_hooks: * (SEMVER-MINOR) add AsyncResource.bind utility (James M Snell) https://github.com/nodejs/node/pull/34574 buffer: * (SEMVER-MINOR) also alias BigUInt methods (Anna Henningsen) https://github.com/nodejs/node/pull/34960 * (SEMVER-MINOR) alias UInt ➡️ Uint in buffer methods (Anna Henningsen) https://github.com/nodejs/node/pull/34729 build: * (SEMVER-MINOR) add build flag for OSS-Fuzz integration (davkor) https://github.com/nodejs/node/pull/34761 cli: * (SEMVER-MINOR) add alias for report-directory to make it consistent (Ash Cripps) https://github.com/nodejs/node/pull/33587 crypto: * (SEMVER-MINOR) allow KeyObjects in postMessage (Tobias Nießen) https://github.com/nodejs/node/pull/33360 * (SEMVER-MINOR) add randomInt function (Oli Lalonde) https://github.com/nodejs/node/pull/34600 deps: * upgrade to libuv 1.39.0 (Colin Ihrig) https://github.com/nodejs/node/pull/34915 * upgrade npm to 6.14.7 (claudiahdz) https://github.com/nodejs/node/pull/34468 * upgrade to libuv 1.38.1 (Colin Ihrig) https://github.com/nodejs/node/pull/34187 dgram: * (SEMVER-MINOR) add IPv6 scope id suffix to received udp6 dgrams (Pekka Nikander) https://github.com/nodejs/node/pull/14500 * (SEMVER-MINOR) allow typed arrays in .send() (Sarat Addepalli) https://github.com/nodejs/node/pull/22413 doc: * (SEMVER-MINOR) Add maxTotalSockets option to agent constructor (rickyes) https://github.com/nodejs/node/pull/33617 * (SEMVER-MINOR) add basic embedding example documentation (Anna Henningsen) https://github.com/nodejs/node/pull/30467 * add Ricky Zhou to collaborators (rickyes) https://github.com/nodejs/node/pull/34676 * add release key for Ruy Adorno (Ruy Adorno) https://github.com/nodejs/node/pull/34628 * add DerekNonGeneric to collaborators (Derek Lewis) https://github.com/nodejs/node/pull/34602 * add AshCripps to collaborators (Ash Cripps) https://github.com/nodejs/node/pull/34494 * add HarshithaKP to collaborators (Harshitha K P) https://github.com/nodejs/node/pull/34417 * add rexagod to collaborators (Pranshu Srivastava) https://github.com/nodejs/node/pull/34457 * add release key for Richard Lau (Richard Lau) https://github.com/nodejs/node/pull/34397 * add danielleadams to collaborators (Danielle Adams) https://github.com/nodejs/node/pull/34360 * add sxa as collaborator (Stewart X Addison) https://github.com/nodejs/node/pull/34338 * add ruyadorno to collaborators (Ruy Adorno) https://github.com/nodejs/node/pull/34297 * (SEMVER-MAJOR) deprecate process.umask() with no arguments (Colin Ihrig) https://github.com/nodejs/node/pull/32499 embedding: * (SEMVER-MINOR) make Stop() stop Workers (Anna Henningsen) https://github.com/nodejs/node/pull/32531 * (SEMVER-MINOR) provide hook for custom process.exit() behaviour (Anna Henningsen) https://github.com/nodejs/node/pull/32531 fs: * (SEMVER-MINOR) implement lutimes (Maël Nison) https://github.com/nodejs/node/pull/33399 http: * (SEMVER-MINOR) add maxTotalSockets to agent class (rickyes) https://github.com/nodejs/node/pull/33617 * (SEMVER-MINOR) return this from IncomingMessage#destroy() (Colin Ihrig) https://github.com/nodejs/node/pull/32789 * (SEMVER-MINOR) expose host and protocol on ClientRequest (wenningplus) https://github.com/nodejs/node/pull/33803 http2: * (SEMVER-MINOR) return this for Http2ServerRequest#setTimeout (Pranshu Srivastava) https://github.com/nodejs/node/pull/33994 * (SEMVER-MINOR) do not modify explicity set date headers (Pranshu Srivastava) https://github.com/nodejs/node/pull/33160 module: * (SEMVER-MINOR) named exports for CJS via static analysis (Guy Bedford) https://github.com/nodejs/node/pull/35249 * (SEMVER-MINOR) exports pattern support (Guy Bedford) https://github.com/nodejs/node/pull/34718 * (SEMVER-MINOR) package "imports" field (Guy Bedford) https://github.com/nodejs/node/pull/34117 * (SEMVER-MINOR) deprecate module.parent (Antoine du HAMEL) https://github.com/nodejs/node/pull/32217 n-api: * (SEMVER-MINOR) create N-API version 7 (Gabriel Schulhof) https://github.com/nodejs/node/pull/35199 * (SEMVER-MINOR) support type-tagging objects (Gabriel Schulhof) https://github.com/nodejs/node/pull/28237 n-api,src: * (SEMVER-MINOR) provide asynchronous cleanup hooks (Anna Henningsen) https://github.com/nodejs/node/pull/34572 perf_hooks: * (SEMVER-MINOR) add idleTime and event loop util (Trevor Norris) https://github.com/nodejs/node/pull/34938 timers: * (SEMVER-MINOR) allow timers to be used as primitives (Denys Otrishko) https://github.com/nodejs/node/pull/34017 tls: * (SEMVER-MINOR) make 'createSecureContext' honor more options (Mateusz Krawczuk) https://github.com/nodejs/node/pull/33974 worker: * (SEMVER-MINOR) add public method for marking objects as untransferable (Anna Henningsen) https://github.com/nodejs/node/pull/33979 * (SEMVER-MINOR) emit `'messagerror'` events for failed deserialization (Anna Henningsen) https://github.com/nodejs/node/pull/33772 * (SEMVER-MINOR) allow passing JS wrapper objects via postMessage (Anna Henningsen) https://github.com/nodejs/node/pull/33772 * (SEMVER-MINOR) allow transferring/cloning generic BaseObjects (Anna Henningsen) https://github.com/nodejs/node/pull/33772 * (SEMVER-MINOR) add option to track unmanaged file descriptors (Anna Henningsen) https://github.com/nodejs/node/pull/34303 * (SEMVER-MINOR) add stack size resource limit option (Anna Henningsen) https://github.com/nodejs/node/pull/33085 worker,fs: * (SEMVER-MINOR) make FileHandle transferable (Anna Henningsen) https://github.com/nodejs/node/pull/33772 zlib: * (SEMVER-MINOR) add `maxOutputLength` option (unknown) https://github.com/nodejs/node/pull/33516 * switch to lazy init for zlib streams (Andrey Pechkurov) https://github.com/nodejs/node/pull/34048 PR-URL: https://github.com/nodejs/node/pull/35401
2020-09-28 10:54:13 -07:00
- version:
- v14.5.0
- v12.19.0
pr-url: https://github.com/nodejs/node/pull/33772
description: Added `FileHandle` to the list of transferable types.
-->
* `value` {any}
* `transferList` {Object\[]}
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][].
In particular, the significant differences to `JSON` are:
* `value` may contain circular references.
* `value` may contain instances of builtin JS types such as `RegExp`s,
`BigInt`s, `Map`s, `Set`s, etc.
* `value` may contain typed arrays, both using `ArrayBuffer`s
and `SharedArrayBuffer`s.
* `value` may contain [`WebAssembly.Module`][] instances.
* `value` may not contain native (C++-backed) objects other than:
* {CryptoKey}s,
* {FileHandle}s,
* {Histogram}s,
* {KeyObject}s,
* {MessagePort}s,
* {net.BlockList}s,
* {net.SocketAddress}es,
* {X509Certificate}s.
```mjs
import { MessageChannel } from 'node:worker_threads';
const { port1, port2 } = new MessageChannel();
port1.on('message', (message) => console.log(message));
const circularData = {};
circularData.foo = circularData;
// Prints: { foo: [Circular] }
port2.postMessage(circularData);
```
```cjs
'use strict';
const { MessageChannel } = require('node:worker_threads');
const { port1, port2 } = new MessageChannel();
port1.on('message', (message) => console.log(message));
const circularData = {};
circularData.foo = circularData;
// Prints: { foo: [Circular] }
port2.postMessage(circularData);
```
`transferList` may be a list of {ArrayBuffer}, [`MessagePort`][], and
[`FileHandle`][] objects.
After transferring, they are not usable on the sending side of the channel
anymore (even if they are not contained in `value`). Unlike with
[child processes][], transferring handles such as network sockets is currently
not supported.
If `value` contains {SharedArrayBuffer} instances, those are accessible
from either thread. They cannot be listed in `transferList`.
`value` may still contain `ArrayBuffer` instances that are not in
`transferList`; in that case, the underlying memory is copied rather than moved.
```mjs
import { MessageChannel } from 'node:worker_threads';
const { port1, port2 } = new MessageChannel();
port1.on('message', (message) => console.log(message));
const uint8Array = new Uint8Array([ 1, 2, 3, 4 ]);
// This posts a copy of `uint8Array`:
port2.postMessage(uint8Array);
// This does not copy data, but renders `uint8Array` unusable:
port2.postMessage(uint8Array, [ uint8Array.buffer ]);
// The memory for the `sharedUint8Array` is accessible from both the
// original and the copy received by `.on('message')`:
const sharedUint8Array = new Uint8Array(new SharedArrayBuffer(4));
port2.postMessage(sharedUint8Array);
// This transfers a freshly created message port to the receiver.
// This can be used, for example, to create communication channels between
// multiple `Worker` threads that are children of the same parent thread.
const otherChannel = new MessageChannel();
port2.postMessage({ port: otherChannel.port1 }, [ otherChannel.port1 ]);
```
```cjs
'use strict';
const { MessageChannel } = require('node:worker_threads');
const { port1, port2 } = new MessageChannel();
port1.on('message', (message) => console.log(message));
const uint8Array = new Uint8Array([ 1, 2, 3, 4 ]);
// This posts a copy of `uint8Array`:
port2.postMessage(uint8Array);
// This does not copy data, but renders `uint8Array` unusable:
port2.postMessage(uint8Array, [ uint8Array.buffer ]);
// The memory for the `sharedUint8Array` is accessible from both the
// original and the copy received by `.on('message')`:
const sharedUint8Array = new Uint8Array(new SharedArrayBuffer(4));
port2.postMessage(sharedUint8Array);
// This transfers a freshly created message port to the receiver.
// This can be used, for example, to create communication channels between
// multiple `Worker` threads that are children of the same parent thread.
const otherChannel = new MessageChannel();
port2.postMessage({ port: otherChannel.port1 }, [ otherChannel.port1 ]);
```
The message object is cloned immediately, and can be modified after
posting without having side effects.
For more information on the serialization and deserialization mechanisms
behind this API, see the [serialization API of the `node:v8` module][v8.serdes].
#### Considerations when transferring TypedArrays and Buffers
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.
```js
const ab = new ArrayBuffer(10);
const u1 = new Uint8Array(ab);
const u2 = new Uint16Array(ab);
console.log(u2.length); // prints 5
port.postMessage(u1, [u1.buffer]);
console.log(u2.length); // prints 0
```
For `Buffer` instances, specifically, whether the underlying
`ArrayBuffer` can be transferred or cloned depends entirely on how
instances were created, which often cannot be reliably determined.
An `ArrayBuffer` can be marked with [`markAsUntransferable()`][] to indicate
that it should always be cloned and never transferred.
Depending on how a `Buffer` instance was created, it may or may
not own its underlying `ArrayBuffer`. An `ArrayBuffer` must not
be transferred unless it is known that the `Buffer` instance
owns it. In particular, for `Buffer`s created from the internal
`Buffer` pool (using, for instance `Buffer.from()` or `Buffer.allocUnsafe()`),
transferring them is not possible and they are always cloned,
which sends a copy of the entire `Buffer` pool.
This behavior may come with unintended higher memory
usage and possible security concerns.
See [`Buffer.allocUnsafe()`][] for more details on `Buffer` pooling.
The `ArrayBuffer`s for `Buffer` instances created using
`Buffer.alloc()` or `Buffer.allocUnsafeSlow()` can always be
transferred but doing so renders all other existing views of
those `ArrayBuffer`s unusable.
#### Considerations when cloning objects with prototypes, classes, and accessors
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.
<!-- eslint-disable no-unused-private-class-members -->
```js
const b = Symbol('b');
class Foo {
#a = 1;
constructor() {
this[b] = 2;
this.c = 3;
}
get d() { return 4; }
}
const { port1, port2 } = new MessageChannel();
port1.onmessage = ({ data }) => console.log(data);
port2.postMessage(new Foo());
// Prints: { c: 3 }
```
This limitation extends to many built-in objects, such as the global `URL`
object:
```js
const { port1, port2 } = new MessageChannel();
port1.onmessage = ({ data }) => console.log(data);
port2.postMessage(new URL('https://example.org'));
// Prints: { }
```
### `port.hasRef()`
<!-- YAML
2022-08-16, Version 16.17.0 'Gallium' (LTS) Notable changes: Adds `util.parseArgs` helper for higher level command-line argument parsing. Contributed by Benjamin Coe, John Gee, Darcy Clarke, Joe Sepi, Kevin Gibbons, Aaron Casanova, Jessica Nahulan, and Jordan Harband. https://github.com/nodejs/node/pull/42675 Node.js ESM Loader hooks now support multiple custom loaders, and composition is achieved via "chaining": `foo-loader` calls `bar-loader` calls `qux-loader` (a custom loader _must_ now signal a short circuit when intentionally not calling the next). See the ESM docs (https://nodejs.org/dist/latest-v16.x/docs/api/esm.html) for details. Contributed by Jacob Smith, Geoffrey Booth, and Bradley Farias. https://github.com/nodejs/node/pull/42623 The `node:test` module, which was initially introduced in Node.js v18.0.0, is now available with all the changes done to it up to Node.js v18.7.0. To better align Node.js' experimental implementation of the Web Crypto API with other runtimes, several changes were made: * Support for CFRG curves was added, with the `'Ed25519'`, `'Ed448'`, `'X25519'`, and `'X448'` algorithms. * The proprietary `'NODE-DSA'`, `'NODE-DH'`, `'NODE-SCRYPT'`, `'NODE-ED25519'`, `'NODE-ED448'`, `'NODE-X25519'`, and `'NODE-X448'` algorithms were removed. * The proprietary `'node.keyObject'` import/export format was removed. Contributed by Filip Skokan. https://github.com/nodejs/node/pull/42507 https://github.com/nodejs/node/pull/43310 Updated Corepack to 0.12.1 - https://github.com/nodejs/node/pull/43965 Updated ICU to 71.1 - https://github.com/nodejs/node/pull/42655 Updated npm to 8.15.0 - https://github.com/nodejs/node/pull/43917 Updated Undici to 5.8.0 - https://github.com/nodejs/node/pull/43886 (SEMVER-MINOR) crypto: make authTagLength optional for CC20P1305 (Tobias Nießen) https://github.com/nodejs/node/pull/42427 (SEMVER-MINOR) crypto: align webcrypto RSA key import/export with other implementations (Filip Skokan) https://github.com/nodejs/node/pull/42816 (SEMVER-MINOR) dns: export error code constants from `dns/promises` (Feng Yu) https://github.com/nodejs/node/pull/43176 doc: deprecate coercion to integer in process.exit (Daeyeon Jeong) https://github.com/nodejs/node/pull/43738 (SEMVER-MINOR) doc: deprecate diagnostics_channel object subscribe method (Stephen Belanger) https://github.com/nodejs/node/pull/42714 (SEMVER-MINOR) errors: add support for cause in aborterror (James M Snell) https://github.com/nodejs/node/pull/41008 (SEMVER-MINOR) events: expose CustomEvent on global with CLI flag (Daeyeon Jeong) https://github.com/nodejs/node/pull/43885 (SEMVER-MINOR) events: add `CustomEvent` (Daeyeon Jeong) https://github.com/nodejs/node/pull/43514 (SEMVER-MINOR) events: propagate abortsignal reason in new AbortError ctor in events (James M Snell) https://github.com/nodejs/node/pull/41008 (SEMVER-MINOR) fs: propagate abortsignal reason in new AbortSignal constructors (James M Snell) https://github.com/nodejs/node/pull/41008 (SEMVER-MINOR) fs: make params in writing methods optional (LiviaMedeiros) https://github.com/nodejs/node/pull/42601 (SEMVER-MINOR) fs: add `read(buffer[, options])` versions (LiviaMedeiros) https://github.com/nodejs/node/pull/42768 (SEMVER-MINOR) http: add drop request event for http server (theanarkh) https://github.com/nodejs/node/pull/43806 (SEMVER-MINOR) http: add diagnostics channel for http client (theanarkh) https://github.com/nodejs/node/pull/43580 (SEMVER-MINOR) http: add perf_hooks detail for http request and client (theanarkh) https://github.com/nodejs/node/pull/43361 (SEMVER-MINOR) http: add uniqueHeaders option to request and createServer (Paolo Insogna) https://github.com/nodejs/node/pull/41397 (SEMVER-MINOR) http2: propagate abortsignal reason in new AbortError constructor (James M Snell) https://github.com/nodejs/node/pull/41008 (SEMVER-MINOR) http2: compat support for array headers (OneNail) https://github.com/nodejs/node/pull/42901 (SEMVER-MINOR) lib: propagate abortsignal reason in new AbortError constructor in blob (James M Snell) https://github.com/nodejs/node/pull/41008 (SEMVER-MINOR) lib: add abortSignal.throwIfAborted() (James M Snell) https://github.com/nodejs/node/pull/40951 (SEMVER-MINOR) lib: improved diagnostics_channel subscribe/unsubscribe (Stephen Belanger) https://github.com/nodejs/node/pull/42714 (SEMVER-MINOR) module: add isBuiltIn method (hemanth.hm) https://github.com/nodejs/node/pull/43396 (SEMVER-MINOR) module,repl: support 'node:'-only core modules (Colin Ihrig) https://github.com/nodejs/node/pull/42325 (SEMVER-MINOR) net: add drop event for net server (theanarkh) https://github.com/nodejs/node/pull/43582 (SEMVER-MINOR) net: add ability to reset a tcp socket (pupilTong) https://github.com/nodejs/node/pull/43112 (SEMVER-MINOR) node-api: emit uncaught-exception on unhandled tsfn callbacks (Chengzhong Wu) https://github.com/nodejs/node/pull/36510 (SEMVER-MINOR) perf_hooks: add PerformanceResourceTiming (RafaelGSS) https://github.com/nodejs/node/pull/42725 (SEMVER-MINOR) report: add more heap infos in process report (theanarkh) https://github.com/nodejs/node/pull/43116 (SEMVER-MINOR) src: add --openssl-legacy-provider option (Daniel Bevenius) https://github.com/nodejs/node/pull/40478 (SEMVER-MINOR) src: define fs.constants.S_IWUSR & S_IRUSR for Win (Liviu Ionescu) https://github.com/nodejs/node/pull/42757 (SEMVER-MINOR) src,doc,test: add --openssl-shared-config option (Daniel Bevenius) https://github.com/nodejs/node/pull/43124 (SEMVER-MINOR) stream: use cause options in AbortError constructors (James M Snell) https://github.com/nodejs/node/pull/41008 (SEMVER-MINOR) stream: add iterator helper find (Nitzan Uziely) https://github.com/nodejs/node/pull/41849 (SEMVER-MINOR) stream: add writableAborted (Robert Nagy) https://github.com/nodejs/node/pull/40802 (SEMVER-MINOR) timers: propagate signal.reason in awaitable timers (James M Snell) https://github.com/nodejs/node/pull/41008 (SEMVER-MINOR) v8: add v8.startupSnapshot utils (Joyee Cheung) https://github.com/nodejs/node/pull/43329 (SEMVER-MINOR) v8: export more fields in getHeapStatistics (theanarkh) https://github.com/nodejs/node/pull/42784 (SEMVER-MINOR) worker: add hasRef() to MessagePort (Darshan Sen) https://github.com/nodejs/node/pull/42849 PR-URL: https://github.com/nodejs/node/pull/44098
2022-08-02 14:34:18 +02:00
added:
- v18.1.0
- v16.17.0
changes:
2025-05-06, Version 24.0.0 (Current) Semver-Major Commits: assert,util: * (SEMVER-MAJOR) Revert "assert,util: revert recursive breaking change (Ruben Bridgewater) https://github.com/nodejs/node/pull/57622 buffer: * (SEMVER-MAJOR) move SlowBuffer to EOL (James M Snell) https://github.com/nodejs/node/pull/58008 * (SEMVER-MAJOR) make `buflen` in integer range (zhenweijin) https://github.com/nodejs/node/pull/51821 build: * (SEMVER-MAJOR) update list of installed cppgc headers (Michaël Zasso) https://github.com/nodejs/node/pull/58070 * (SEMVER-MAJOR) fix V8 TLS config for shared lib builds (Michaël Zasso) https://github.com/nodejs/node/pull/58070 * (SEMVER-MAJOR) pass `-fPIC` to linker as well for shared builds (Michaël Zasso) https://github.com/nodejs/node/pull/58070 * (SEMVER-MAJOR) add `/bigobj` to compile V8 on Windows (Michaël Zasso) https://github.com/nodejs/node/pull/58070 * (SEMVER-MAJOR) enable shared RO heap with ptr compression (Michaël Zasso) https://github.com/nodejs/node/pull/58070 * (SEMVER-MAJOR) remove support for s390 32-bit (Richard Lau) https://github.com/nodejs/node/pull/58070 * (SEMVER-MAJOR) reset embedder string to "-node.0" (Michaël Zasso) https://github.com/nodejs/node/pull/58070 * (SEMVER-MAJOR) downgrade armv7 support to experimental (Michaël Zasso) https://github.com/nodejs/node/pull/58071 * (SEMVER-MAJOR) bump supported macOS version to 13.5 (Michaël Zasso) https://github.com/nodejs/node/pull/57115 * (SEMVER-MAJOR) increase minimum Xcode version to 16.1 (Michaël Zasso) https://github.com/nodejs/node/pull/56824 * (SEMVER-MAJOR) link V8 with atomic library (Michaël Zasso) https://github.com/nodejs/node/pull/55014 * (SEMVER-MAJOR) remove support for ppc 32-bit (Michaël Zasso) https://github.com/nodejs/node/pull/55014 * (SEMVER-MAJOR) reset embedder string to "-node.0" (Michaël Zasso) https://github.com/nodejs/node/pull/55014 build,src,tools: * (SEMVER-MAJOR) adapt build config for V8 13.3 (Michaël Zasso) https://github.com/nodejs/node/pull/58070 child_process: * (SEMVER-MAJOR) deprecate passing `args` to `spawn` and `execFile` (Daniel Venable) https://github.com/nodejs/node/pull/57199 deps: * (SEMVER-MAJOR) remove deps/simdutf (Michaël Zasso) https://github.com/nodejs/node/pull/58070 * (SEMVER-MAJOR) V8: backport 954187bb1b87 (Joyee Cheung) https://github.com/nodejs/node/pull/58070 * (SEMVER-MAJOR) patch V8 to support compilation with MSVC (StefanStojanovic) https://github.com/nodejs/node/pull/58070 * (SEMVER-MAJOR) always define V8_EXPORT_PRIVATE as no-op (Michaël Zasso) https://github.com/nodejs/node/pull/58070 * (SEMVER-MAJOR) disable V8 concurrent sparkplug compilation (Michaël Zasso) https://github.com/nodejs/node/pull/58070 * (SEMVER-MAJOR) use std::map in MSVC STL for EphemeronRememberedSet (Joyee Cheung) https://github.com/nodejs/node/pull/58070 * (SEMVER-MAJOR) patch V8 for illumos (Dan McDonald) https://github.com/nodejs/node/pull/58070 * (SEMVER-MAJOR) remove problematic comment from v8-internal (Michaël Zasso) https://github.com/nodejs/node/pull/58070 * (SEMVER-MAJOR) define V8_PRESERVE_MOST as no-op on Windows (Stefan Stojanovic) https://github.com/nodejs/node/pull/58070 * (SEMVER-MAJOR) fix FP16 bitcasts.h (Stefan Stojanovic) https://github.com/nodejs/node/pull/58070 * (SEMVER-MAJOR) patch V8 to avoid duplicated zlib symbol (Michaël Zasso) https://github.com/nodejs/node/pull/58070 * (SEMVER-MAJOR) update V8 to 13.6.233.8 (Michaël Zasso) https://github.com/nodejs/node/pull/58070 * (SEMVER-MAJOR) V8: cherry-pick f915fa4c9f41 (Olivier Flückiger) https://github.com/nodejs/node/pull/55014 * (SEMVER-MAJOR) V8: cherry-pick 0d5d6e71bbb0 (Yagiz Nizipli) https://github.com/nodejs/node/pull/55014 * (SEMVER-MAJOR) V8: cherry-pick 0c11feeeca4a (Michaël Zasso) https://github.com/nodejs/node/pull/55014 * (SEMVER-MAJOR) define V8_PRESERVE_MOST as no-op on Windows (Stefan Stojanovic) https://github.com/nodejs/node/pull/55014 * (SEMVER-MAJOR) always define V8_NODISCARD as no-op (Michaël Zasso) https://github.com/nodejs/node/pull/55014 * (SEMVER-MAJOR) fix FP16 bitcasts.h (Stefan Stojanovic) https://github.com/nodejs/node/pull/55014 * (SEMVER-MAJOR) patch V8 to support compilation with MSVC (StefanStojanovic) https://github.com/nodejs/node/pull/55014 * (SEMVER-MAJOR) patch V8 to avoid duplicated zlib symbol (Michaël Zasso) https://github.com/nodejs/node/pull/55014 * (SEMVER-MAJOR) disable V8 concurrent sparkplug compilation (Michaël Zasso) https://github.com/nodejs/node/pull/55014 * (SEMVER-MAJOR) always define V8_EXPORT_PRIVATE as no-op (Michaël Zasso) https://github.com/nodejs/node/pull/55014 * (SEMVER-MAJOR) update V8 to 13.0.245.25 (Michaël Zasso) https://github.com/nodejs/node/pull/55014 * (SEMVER-MAJOR) upgrade npm to 11.0.0 (npm team) https://github.com/nodejs/node/pull/56274 * (SEMVER-MAJOR) update undici to 7.0.0 (Node.js GitHub Bot) https://github.com/nodejs/node/pull/56070 fs: * (SEMVER-MAJOR) remove ability to call truncate with fd (Yagiz Nizipli) https://github.com/nodejs/node/pull/57567 * (SEMVER-MAJOR) deprecate passing invalid types in `fs.existsSync` (Carlos Espa) https://github.com/nodejs/node/pull/55753 * (SEMVER-MAJOR) runtime deprecate `fs.F_OK`, `fs.R_OK`, `fs.W_OK`, `fs.X_OK` (Livia Medeiros) https://github.com/nodejs/node/pull/49686 * (SEMVER-MAJOR) remove `dirent.path` (Antoine du Hamel) https://github.com/nodejs/node/pull/55548 http: * (SEMVER-MAJOR) remove outgoingmessage _headers and _headersList (Yagiz Nizipli) https://github.com/nodejs/node/pull/57551 http2: * (SEMVER-MAJOR) session tracking and graceful server close (Kushagra Pandey) https://github.com/nodejs/node/pull/57586 lib: * (SEMVER-MAJOR) remove obsolete Cipher export (James M Snell) https://github.com/nodejs/node/pull/57266 * (SEMVER-MAJOR) unexpose six process bindings (Michaël Zasso) https://github.com/nodejs/node/pull/57149 * (SEMVER-MAJOR) make ALS default to AsyncContextFrame (Stephen Belanger) https://github.com/nodejs/node/pull/55552 * (SEMVER-MAJOR) runtime deprecate SlowBuffer (Rafael Gonzaga) https://github.com/nodejs/node/pull/55175 net: * (SEMVER-MAJOR) make _setSimultaneousAccepts() end-of-life deprecated (Yagiz Nizipli) https://github.com/nodejs/node/pull/57550 readline: * (SEMVER-MAJOR) add stricter validation for functions called after closed (Dario Piotrowicz) https://github.com/nodejs/node/pull/57680 * (SEMVER-MAJOR) fix unicode line separators being ignored (Dario Piotrowicz) https://github.com/nodejs/node/pull/57591 repl: * (SEMVER-MAJOR) runtime deprecate instantiating without new (Aviv Keller) https://github.com/nodejs/node/pull/54869 src: * (SEMVER-MAJOR) enable `Float16Array` on global object (Michaël Zasso) https://github.com/nodejs/node/pull/58154 * (SEMVER-MAJOR) enable explicit resource management (Michaël Zasso) https://github.com/nodejs/node/pull/58154 * (SEMVER-MAJOR) use non-deprecated WriteUtf8V2() method (Yagiz Nizipli) https://github.com/nodejs/node/pull/58070 * (SEMVER-MAJOR) use non-deprecated Utf8LengthV2() method (Yagiz Nizipli) https://github.com/nodejs/node/pull/58070 * (SEMVER-MAJOR) use V8-owned CppHeap (Joyee Cheung) https://github.com/nodejs/node/pull/58070 * (SEMVER-MAJOR) use `v8::ExternalMemoryAccounter` (Michaël Zasso) https://github.com/nodejs/node/pull/58070 * (SEMVER-MAJOR) replace uses of FastApiTypedArray (Michaël Zasso) https://github.com/nodejs/node/pull/58070 * (SEMVER-MAJOR) update NODE_MODULE_VERSION to 137 (Michaël Zasso) https://github.com/nodejs/node/pull/58070 * (SEMVER-MAJOR) update GetForegroundTaskRunner override (Etienne Pierre-doray) https://github.com/nodejs/node/pull/55014 * (SEMVER-MAJOR) update NODE_MODULE_VERSION to 134 (Michaël Zasso) https://github.com/nodejs/node/pull/55014 * (SEMVER-MAJOR) drop --experimental-permission in favour of --permission (Rafael Gonzaga) https://github.com/nodejs/node/pull/56240 * (SEMVER-MAJOR) add async context frame to AsyncResource (Gerhard Stöbich) https://github.com/nodejs/node/pull/56082 * (SEMVER-MAJOR) nuke deprecated and un-used enum members in `OptionEnvvarSettings` (Juan José) https://github.com/nodejs/node/pull/53079 src,test: * (SEMVER-MAJOR) unregister the isolate after disposal and before freeing (Joyee Cheung) https://github.com/nodejs/node/pull/58070 * (SEMVER-MAJOR) add V8 API to test the hash seed (Michaël Zasso) https://github.com/nodejs/node/pull/58070 stream: * (SEMVER-MAJOR) catch and forward error from dest.write (jakecastelli) https://github.com/nodejs/node/pull/55270 test: * (SEMVER-MAJOR) fix test-fs-write for V8 13.6 (Michaël Zasso) https://github.com/nodejs/node/pull/58070 * (SEMVER-MAJOR) handle explicit resource management globals (Michaël Zasso) https://github.com/nodejs/node/pull/58070 * (SEMVER-MAJOR) adapt assert tests to stack trace changes (Michaël Zasso) https://github.com/nodejs/node/pull/58070 * (SEMVER-MAJOR) update test-linux-perf-logger (Michaël Zasso) https://github.com/nodejs/node/pull/58070 * (SEMVER-MAJOR) Revert "test: disable fast API call count checks (Michaël Zasso) https://github.com/nodejs/node/pull/58070 * (SEMVER-MAJOR) disable fast API call count checks (Michaël Zasso) https://github.com/nodejs/node/pull/55014 test_runner: * (SEMVER-MAJOR) remove promises returned by t.test() (Colin Ihrig) https://github.com/nodejs/node/pull/56664 * (SEMVER-MAJOR) remove promises returned by test() (Colin Ihrig) https://github.com/nodejs/node/pull/56664 * (SEMVER-MAJOR) automatically wait for subtests to finish (Colin Ihrig) https://github.com/nodejs/node/pull/56664 timers: * (SEMVER-MAJOR) check for immediate instance in clearImmediate (Gürgün Dayıoğlu) https://github.com/nodejs/node/pull/57069 * (SEMVER-MAJOR) set several methods EOL (Yagiz Nizipli) https://github.com/nodejs/node/pull/56966 tls: * (SEMVER-MAJOR) remove deprecated tls.createSecurePair (Jonas) https://github.com/nodejs/node/pull/57361 * (SEMVER-MAJOR) make server.prototype.setOptions end-of-life (Yagiz Nizipli) https://github.com/nodejs/node/pull/57339 tools: * (SEMVER-MAJOR) update V8 gypfiles for 13.6 (Michaël Zasso) https://github.com/nodejs/node/pull/58070 * (SEMVER-MAJOR) update V8 gypfiles for 13.5 (Michaël Zasso) https://github.com/nodejs/node/pull/58070 * (SEMVER-MAJOR) update license-builder and LICENSE for V8 deps (Michaël Zasso) https://github.com/nodejs/node/pull/58070 * (SEMVER-MAJOR) update V8 gypfiles for 13.4 (Michaël Zasso) https://github.com/nodejs/node/pull/58070 * (SEMVER-MAJOR) update V8 gypfiles for 13.2 (Michaël Zasso) https://github.com/nodejs/node/pull/58070 * (SEMVER-MAJOR) update V8 gypfiles for 13.1 (Michaël Zasso) https://github.com/nodejs/node/pull/58070 * (SEMVER-MAJOR) update V8 gypfiles for 13.0 (Michaël Zasso) https://github.com/nodejs/node/pull/55014 url: * (SEMVER-MAJOR) expose urlpattern as global (Jonas) https://github.com/nodejs/node/pull/56950 * (SEMVER-MAJOR) runtime deprecate url.parse (Yagiz Nizipli) https://github.com/nodejs/node/pull/55017 zlib: * (SEMVER-MAJOR) deprecate classes usage without `new` (Yagiz Nizipli) https://github.com/nodejs/node/pull/55718 PR-URL: https://github.com/nodejs/node/pull/57609 Signed-off-by: RafaelGSS <rafael.nunu@hotmail.com>
2025-03-24 16:29:01 -03:00
- version: v24.0.0
pr-url: https://github.com/nodejs/node/pull/57513
description: Marking the API stable.
-->
* Returns: {boolean}
If true, the `MessagePort` object will keep the Node.js event loop active.
### `port.ref()`
<!-- YAML
added: v10.5.0
-->
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.
If listeners are attached or removed using `.on('message')`, the port
is `ref()`ed and `unref()`ed automatically depending on whether
listeners for the event exist.
### `port.start()`
<!-- YAML
added: v10.5.0
-->
Starts receiving messages on this `MessagePort`. When using this port
as an event emitter, this is called automatically once `'message'`
listeners are attached.
This method exists for parity with the Web `MessagePort` API. In Node.js,
it is only useful for ignoring messages when no event listener is present.
Node.js also diverges in its handling of `.onmessage`. Setting it
automatically calls `.start()`, but unsetting it lets messages queue up
until a new handler is set or the port is discarded.
### `port.unref()`
<!-- YAML
added: v10.5.0
-->
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.
If listeners are attached or removed using `.on('message')`, the port is
`ref()`ed and `unref()`ed automatically depending on whether
listeners for the event exist.
## Class: `Worker`
<!-- YAML
added: v10.5.0
-->
* Extends: {EventEmitter}
The `Worker` class represents an independent JavaScript execution thread.
Most Node.js APIs are available inside of it.
Notable differences inside a Worker environment are:
* The [`process.stdin`][], [`process.stdout`][], and [`process.stderr`][]
streams may be redirected by the parent thread.
* The [`require('node:worker_threads').isMainThread`][] property is set to `false`.
* The [`require('node:worker_threads').parentPort`][] message port is available.
* [`process.exit()`][] does not stop the whole program, just the single thread,
and [`process.abort()`][] is not available.
* [`process.chdir()`][] and `process` methods that set group or user ids
are not available.
* [`process.env`][] is a copy of the parent thread's environment variables,
unless otherwise specified. Changes to one copy are not visible in other
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
environment variables operates in a case-sensitive manner.
* [`process.title`][] cannot be modified.
* Signals are not delivered through [`process.on('...')`][Signals events].
* Execution may stop at any point as a result of [`worker.terminate()`][]
being invoked.
* IPC channels from parent processes are not accessible.
* The [`trace_events`][] module is not supported.
* Native add-ons can only be loaded from multiple threads if they fulfill
[certain conditions][Addons worker support].
Creating `Worker` instances inside of other `Worker`s is possible.
Like [Web Workers][] and the [`node:cluster` module][], two-way communication
can be achieved through inter-thread message passing. Internally, a `Worker` has
a built-in pair of [`MessagePort`][]s that are already associated with each
other when the `Worker` is created. While the `MessagePort` object on the parent
side is not directly exposed, its functionalities are exposed through
[`worker.postMessage()`][] and the [`worker.on('message')`][] event
on the `Worker` object for the parent thread.
To create custom messaging channels (which is encouraged over using the default
global channel because it facilitates separation of concerns), users can create
a `MessageChannel` object on either thread and pass one of the
`MessagePort`s on that `MessageChannel` to the other thread through a
pre-existing channel, such as the global one.
See [`port.postMessage()`][] for more information on how messages are passed,
and what kind of JavaScript values can be successfully transported through
the thread barrier.
```mjs
import assert from 'node:assert';
import {
Worker, MessageChannel, MessagePort, isMainThread, parentPort,
} from 'node:worker_threads';
if (isMainThread) {
const worker = new Worker(new URL(import.meta.url));
const subChannel = new MessageChannel();
worker.postMessage({ hereIsYourPort: subChannel.port1 }, [subChannel.port1]);
subChannel.port2.on('message', (value) => {
console.log('received:', value);
});
} else {
parentPort.once('message', (value) => {
assert(value.hereIsYourPort instanceof MessagePort);
value.hereIsYourPort.postMessage('the worker is sending this');
value.hereIsYourPort.close();
});
}
```
```cjs
'use strict';
const assert = require('node:assert');
const {
Worker, MessageChannel, MessagePort, isMainThread, parentPort,
} = require('node:worker_threads');
if (isMainThread) {
const worker = new Worker(__filename);
const subChannel = new MessageChannel();
worker.postMessage({ hereIsYourPort: subChannel.port1 }, [subChannel.port1]);
subChannel.port2.on('message', (value) => {
console.log('received:', value);
});
} else {
parentPort.once('message', (value) => {
assert(value.hereIsYourPort instanceof MessagePort);
value.hereIsYourPort.postMessage('the worker is sending this');
value.hereIsYourPort.close();
});
}
```
### `new Worker(filename[, options])`
<!-- YAML
added: v10.5.0
changes:
2023-04-12, Version 18.16.0 'Hydrogen' (LTS) Notable changes: Add initial support for single executable applications Compile a JavaScript file into a single executable application: ```console $ echo 'console.log(`Hello, ${process.argv[2]}!`);' > hello.js $ cp $(command -v node) hello $ npx postject hello NODE_JS_CODE hello.js \ --sentinel-fuse NODE_JS_FUSE_fce680ab2cc467b6e072b8b5df1996b2 $ npx postject hello NODE_JS_CODE hello.js \ --sentinel-fuse NODE_JS_FUSE_fce680ab2cc467b6e072b8b5df1996b2 \ --macho-segment-name NODE_JS $ ./hello world Hello, world! ``` Contributed by Darshan Sen in https://github.com/nodejs/node/pull/45038 Replace url parser with Ada Node.js gets a new URL parser called Ada that is compliant with the WHATWG URL Specification and provides more than 100% performance improvement to the existing implementation. Contributed by Yagiz Nizipli in https://github.com/nodejs/node/pull/46410 Other notable changes: * buffer: * (SEMVER-MINOR) add Buffer.copyBytesFrom(...) (James M Snell) https://github.com/nodejs/node/pull/46500 * doc: * add marco-ippolito to collaborators (Marco Ippolito) https://github.com/nodejs/node/pull/46816 * add debadree25 to collaborators (Debadree Chatterjee) https://github.com/nodejs/node/pull/46716 * add deokjinkim to collaborators (Deokjin Kim) https://github.com/nodejs/node/pull/46444 * events: * (SEMVER-MINOR) add listener argument to listenerCount (Paolo Insogna) https://github.com/nodejs/node/pull/46523 * lib: * (SEMVER-MINOR) add AsyncLocalStorage.bind() and .snapshot() (flakey5) https://github.com/nodejs/node/pull/46387 * (SEMVER-MINOR) add aborted() utility function (Debadree Chatterjee) https://github.com/nodejs/node/pull/46494 * src: * (SEMVER-MINOR) allow optional Isolate termination in node::Stop() (Shelley Vohr) https://github.com/nodejs/node/pull/46583 * (SEMVER-MINOR) allow embedder control of code generation policy (Shelley Vohr) https://github.com/nodejs/node/pull/46368 * stream: * (SEMVER-MINOR) add abort signal for ReadableStream and WritableStream (Debadree Chatterjee) https://github.com/nodejs/node/pull/46273 * tls: * (SEMVER-MINOR) support automatic DHE (Tobias Nießen) https://github.com/nodejs/node/pull/46978 * url: * (SEMVER-MINOR) implement URLSearchParams size getter (James M Snell) https://github.com/nodejs/node/pull/46308 * worker: * (SEMVER-MINOR) add support for worker name in inspector and trace_events (Debadree Chatterjee) https://github.com/nodejs/node/pull/46832 PR-URL: https://github.com/nodejs/node/pull/47502
2023-04-10 23:02:28 -04:00
- version:
- v19.8.0
- v18.16.0
pr-url: https://github.com/nodejs/node/pull/46832
description: Added support for a `name` option, which allows
adding a name to worker title for debugging.
- version: v14.9.0
pr-url: https://github.com/nodejs/node/pull/34584
description: The `filename` parameter can be a WHATWG `URL` object using
`data:` protocol.
- version: v14.9.0
pr-url: https://github.com/nodejs/node/pull/34394
description: The `trackUnmanagedFds` option was set to `true` by default.
- version:
2020-07-21, Version 14.6.0 (Current) Notable changes: deps: * upgrade npm to 6.14.6 (claudiahdz) https://github.com/nodejs/node/pull/34246 * upgrade to libuv 1.38.1 (Colin Ihrig) https://github.com/nodejs/node/pull/34187 * (SEMVER-MINOR) update V8 to 8.4.371.19 (Michaël Zasso) [#33579](https://github.com/nodejs/node/pull/33579) module: * (SEMVER-MINOR) deprecate module.parent (Antoine du HAMEL) https://github.com/nodejs/node/pull/32217 * (SEMVER-MINOR) package "imports" field (Guy Bedford) https://github.com/nodejs/node/pull/34117 src: * (SEMVER-MINOR) add option to track unmanaged file descriptors (Anna Henningsen) https://github.com/nodejs/node/pull/34303 * (SEMVER-MINOR) allow embedders to disable esm loader (Shelley Vohr) https://github.com/nodejs/node/pull/34060 tls: * (SEMVER-MINOR) make 'createSecureContext' honor more options (Mateusz Krawczuk) https://github.com/nodejs/node/pull/33974 vm: * (SEMVER-MINOR) add run-after-evaluate microtask mode (Anna Henningsen) https://github.com/nodejs/node/pull/34023 worker: * (SEMVER-MINOR) add option to track unmanaged file descriptors (Anna Henningsen) https://github.com/nodejs/node/pull/34303 New Collaborators: * add danielleadams to collaborators (Danielle Adams) https://github.com/nodejs/node/pull/34360 * add sxa as collaborator (Stewart X Addison) https://github.com/nodejs/node/pull/34338 * add ruyadorno to collaborators (Ruy Adorno) https://github.com/nodejs/node/pull/34297 PR-URL: https://github.com/nodejs/node/pull/34371
2020-07-15 14:11:29 -04:00
- v14.6.0
2020-10-06, Version 12.19.0 'Erbium' (LTS) Notable changes: assert: * (SEMVER-MINOR) port common.mustCall() to assert (ConorDavenport) https://github.com/nodejs/node/pull/31982 async_hooks: * (SEMVER-MINOR) add AsyncResource.bind utility (James M Snell) https://github.com/nodejs/node/pull/34574 buffer: * (SEMVER-MINOR) also alias BigUInt methods (Anna Henningsen) https://github.com/nodejs/node/pull/34960 * (SEMVER-MINOR) alias UInt ➡️ Uint in buffer methods (Anna Henningsen) https://github.com/nodejs/node/pull/34729 build: * (SEMVER-MINOR) add build flag for OSS-Fuzz integration (davkor) https://github.com/nodejs/node/pull/34761 cli: * (SEMVER-MINOR) add alias for report-directory to make it consistent (Ash Cripps) https://github.com/nodejs/node/pull/33587 crypto: * (SEMVER-MINOR) allow KeyObjects in postMessage (Tobias Nießen) https://github.com/nodejs/node/pull/33360 * (SEMVER-MINOR) add randomInt function (Oli Lalonde) https://github.com/nodejs/node/pull/34600 deps: * upgrade to libuv 1.39.0 (Colin Ihrig) https://github.com/nodejs/node/pull/34915 * upgrade npm to 6.14.7 (claudiahdz) https://github.com/nodejs/node/pull/34468 * upgrade to libuv 1.38.1 (Colin Ihrig) https://github.com/nodejs/node/pull/34187 dgram: * (SEMVER-MINOR) add IPv6 scope id suffix to received udp6 dgrams (Pekka Nikander) https://github.com/nodejs/node/pull/14500 * (SEMVER-MINOR) allow typed arrays in .send() (Sarat Addepalli) https://github.com/nodejs/node/pull/22413 doc: * (SEMVER-MINOR) Add maxTotalSockets option to agent constructor (rickyes) https://github.com/nodejs/node/pull/33617 * (SEMVER-MINOR) add basic embedding example documentation (Anna Henningsen) https://github.com/nodejs/node/pull/30467 * add Ricky Zhou to collaborators (rickyes) https://github.com/nodejs/node/pull/34676 * add release key for Ruy Adorno (Ruy Adorno) https://github.com/nodejs/node/pull/34628 * add DerekNonGeneric to collaborators (Derek Lewis) https://github.com/nodejs/node/pull/34602 * add AshCripps to collaborators (Ash Cripps) https://github.com/nodejs/node/pull/34494 * add HarshithaKP to collaborators (Harshitha K P) https://github.com/nodejs/node/pull/34417 * add rexagod to collaborators (Pranshu Srivastava) https://github.com/nodejs/node/pull/34457 * add release key for Richard Lau (Richard Lau) https://github.com/nodejs/node/pull/34397 * add danielleadams to collaborators (Danielle Adams) https://github.com/nodejs/node/pull/34360 * add sxa as collaborator (Stewart X Addison) https://github.com/nodejs/node/pull/34338 * add ruyadorno to collaborators (Ruy Adorno) https://github.com/nodejs/node/pull/34297 * (SEMVER-MAJOR) deprecate process.umask() with no arguments (Colin Ihrig) https://github.com/nodejs/node/pull/32499 embedding: * (SEMVER-MINOR) make Stop() stop Workers (Anna Henningsen) https://github.com/nodejs/node/pull/32531 * (SEMVER-MINOR) provide hook for custom process.exit() behaviour (Anna Henningsen) https://github.com/nodejs/node/pull/32531 fs: * (SEMVER-MINOR) implement lutimes (Maël Nison) https://github.com/nodejs/node/pull/33399 http: * (SEMVER-MINOR) add maxTotalSockets to agent class (rickyes) https://github.com/nodejs/node/pull/33617 * (SEMVER-MINOR) return this from IncomingMessage#destroy() (Colin Ihrig) https://github.com/nodejs/node/pull/32789 * (SEMVER-MINOR) expose host and protocol on ClientRequest (wenningplus) https://github.com/nodejs/node/pull/33803 http2: * (SEMVER-MINOR) return this for Http2ServerRequest#setTimeout (Pranshu Srivastava) https://github.com/nodejs/node/pull/33994 * (SEMVER-MINOR) do not modify explicity set date headers (Pranshu Srivastava) https://github.com/nodejs/node/pull/33160 module: * (SEMVER-MINOR) named exports for CJS via static analysis (Guy Bedford) https://github.com/nodejs/node/pull/35249 * (SEMVER-MINOR) exports pattern support (Guy Bedford) https://github.com/nodejs/node/pull/34718 * (SEMVER-MINOR) package "imports" field (Guy Bedford) https://github.com/nodejs/node/pull/34117 * (SEMVER-MINOR) deprecate module.parent (Antoine du HAMEL) https://github.com/nodejs/node/pull/32217 n-api: * (SEMVER-MINOR) create N-API version 7 (Gabriel Schulhof) https://github.com/nodejs/node/pull/35199 * (SEMVER-MINOR) support type-tagging objects (Gabriel Schulhof) https://github.com/nodejs/node/pull/28237 n-api,src: * (SEMVER-MINOR) provide asynchronous cleanup hooks (Anna Henningsen) https://github.com/nodejs/node/pull/34572 perf_hooks: * (SEMVER-MINOR) add idleTime and event loop util (Trevor Norris) https://github.com/nodejs/node/pull/34938 timers: * (SEMVER-MINOR) allow timers to be used as primitives (Denys Otrishko) https://github.com/nodejs/node/pull/34017 tls: * (SEMVER-MINOR) make 'createSecureContext' honor more options (Mateusz Krawczuk) https://github.com/nodejs/node/pull/33974 worker: * (SEMVER-MINOR) add public method for marking objects as untransferable (Anna Henningsen) https://github.com/nodejs/node/pull/33979 * (SEMVER-MINOR) emit `'messagerror'` events for failed deserialization (Anna Henningsen) https://github.com/nodejs/node/pull/33772 * (SEMVER-MINOR) allow passing JS wrapper objects via postMessage (Anna Henningsen) https://github.com/nodejs/node/pull/33772 * (SEMVER-MINOR) allow transferring/cloning generic BaseObjects (Anna Henningsen) https://github.com/nodejs/node/pull/33772 * (SEMVER-MINOR) add option to track unmanaged file descriptors (Anna Henningsen) https://github.com/nodejs/node/pull/34303 * (SEMVER-MINOR) add stack size resource limit option (Anna Henningsen) https://github.com/nodejs/node/pull/33085 worker,fs: * (SEMVER-MINOR) make FileHandle transferable (Anna Henningsen) https://github.com/nodejs/node/pull/33772 zlib: * (SEMVER-MINOR) add `maxOutputLength` option (unknown) https://github.com/nodejs/node/pull/33516 * switch to lazy init for zlib streams (Andrey Pechkurov) https://github.com/nodejs/node/pull/34048 PR-URL: https://github.com/nodejs/node/pull/35401
2020-09-28 10:54:13 -07:00
- v12.19.0
2020-07-21, Version 14.6.0 (Current) Notable changes: deps: * upgrade npm to 6.14.6 (claudiahdz) https://github.com/nodejs/node/pull/34246 * upgrade to libuv 1.38.1 (Colin Ihrig) https://github.com/nodejs/node/pull/34187 * (SEMVER-MINOR) update V8 to 8.4.371.19 (Michaël Zasso) [#33579](https://github.com/nodejs/node/pull/33579) module: * (SEMVER-MINOR) deprecate module.parent (Antoine du HAMEL) https://github.com/nodejs/node/pull/32217 * (SEMVER-MINOR) package "imports" field (Guy Bedford) https://github.com/nodejs/node/pull/34117 src: * (SEMVER-MINOR) add option to track unmanaged file descriptors (Anna Henningsen) https://github.com/nodejs/node/pull/34303 * (SEMVER-MINOR) allow embedders to disable esm loader (Shelley Vohr) https://github.com/nodejs/node/pull/34060 tls: * (SEMVER-MINOR) make 'createSecureContext' honor more options (Mateusz Krawczuk) https://github.com/nodejs/node/pull/33974 vm: * (SEMVER-MINOR) add run-after-evaluate microtask mode (Anna Henningsen) https://github.com/nodejs/node/pull/34023 worker: * (SEMVER-MINOR) add option to track unmanaged file descriptors (Anna Henningsen) https://github.com/nodejs/node/pull/34303 New Collaborators: * add danielleadams to collaborators (Danielle Adams) https://github.com/nodejs/node/pull/34360 * add sxa as collaborator (Stewart X Addison) https://github.com/nodejs/node/pull/34338 * add ruyadorno to collaborators (Ruy Adorno) https://github.com/nodejs/node/pull/34297 PR-URL: https://github.com/nodejs/node/pull/34371
2020-07-15 14:11:29 -04:00
pr-url: https://github.com/nodejs/node/pull/34303
description: The `trackUnmanagedFds` option was introduced.
- version:
- v13.13.0
- v12.17.0
pr-url: https://github.com/nodejs/node/pull/32278
description: The `transferList` option was introduced.
- version:
- v13.12.0
- v12.17.0
pr-url: https://github.com/nodejs/node/pull/31664
description: The `filename` parameter can be a WHATWG `URL` object using
`file:` protocol.
- version:
- v13.4.0
- v12.16.0
pr-url: https://github.com/nodejs/node/pull/30559
description: The `argv` option was introduced.
- version:
- v13.2.0
- v12.16.0
pr-url: https://github.com/nodejs/node/pull/26628
description: The `resourceLimits` option was introduced.
-->
* `filename` {string|URL} The path to the Worker's main script or module. Must
be either an absolute path or a relative path (i.e. relative to the
current working directory) starting with `./` or `../`, or a WHATWG `URL`
object using `file:` or `data:` protocol.
When using a [`data:` URL][], the data is interpreted based on MIME type using
the [ECMAScript module loader][].
If `options.eval` is `true`, this is a string containing JavaScript code
rather than a path.
* `options` {Object}
* `argv` {any\[]} List of arguments which would be stringified and appended to
`process.argv` in the worker. This is mostly similar to the `workerData`
but the values are available on the global `process.argv` as if they
were passed as CLI options to the script.
* `env` {Object} If set, specifies the initial value of `process.env` inside
the Worker thread. As a special value, [`worker.SHARE_ENV`][] may be used
to specify that the parent thread and the child thread should share their
environment variables; in that case, changes to one thread's `process.env`
object affect the other thread as well. **Default:** `process.env`.
* `eval` {boolean} If `true` and the first argument is a `string`, interpret
the first argument to the constructor as a script that is executed once the
worker is online.
* `execArgv` {string\[]} List of node CLI options passed to the worker.
V8 options (such as `--max-old-space-size`) and options that affect the
process (such as `--title`) are not supported. If set, this is provided
as [`process.execArgv`][] inside the worker. By default, options are
inherited from the parent thread.
* `stdin` {boolean} If this is set to `true`, then `worker.stdin`
provides a writable stream whose contents appear as `process.stdin`
inside the Worker. By default, no data is provided.
* `stdout` {boolean} If this is set to `true`, then `worker.stdout` is
not automatically piped through to `process.stdout` in the parent.
* `stderr` {boolean} If this is set to `true`, then `worker.stderr` is
not automatically piped through to `process.stderr` in the parent.
* `workerData` {any} Any JavaScript value that is cloned and made
available as [`require('node:worker_threads').workerData`][]. The cloning
occurs as described in the [HTML structured clone algorithm][], and an error
is thrown if the object cannot be cloned (e.g. because it contains
`function`s).
* `trackUnmanagedFds` {boolean} If this is set to `true`, then the Worker
tracks raw file descriptors managed through [`fs.open()`][] and
[`fs.close()`][], and closes them when the Worker exits, similar to other
resources like network sockets or file descriptors managed through
the [`FileHandle`][] API. This option is automatically inherited by all
nested `Worker`s. **Default:** `true`.
* `transferList` {Object\[]} If one or more `MessagePort`-like objects
are passed in `workerData`, a `transferList` is required for those
items or [`ERR_MISSING_MESSAGE_PORT_IN_TRANSFER_LIST`][] is thrown.
See [`port.postMessage()`][] for more information.
* `resourceLimits` {Object} An optional set of resource limits for the new JS
engine instance. Reaching these limits leads to termination of the `Worker`
instance. These limits only affect the JS engine, and no external data,
including no `ArrayBuffer`s. Even if these limits are set, the process may
still abort if it encounters a global out-of-memory situation.
* `maxOldGenerationSizeMb` {number} The maximum size of the main heap in
MB. If the command-line argument [`--max-old-space-size`][] is set, it
overrides this setting.
* `maxYoungGenerationSizeMb` {number} The maximum size of a heap space for
recently created objects. If the command-line argument
[`--max-semi-space-size`][] is set, it overrides this setting.
* `codeRangeSizeMb` {number} The size of a pre-allocated memory range
used for generated code.
* `stackSizeMb` {number} The default maximum stack size for the thread.
Small values may lead to unusable Worker instances. **Default:** `4`.
* `name` {string} An optional `name` to be replaced in the thread name
and to the worker title for debugging/identification purposes,
making the final title as `[worker ${id}] ${name}`.
This parameter has a maximum allowed size, depending on the operating
system. If the provided name exceeds the limit, it will be truncated
* Maximum sizes:
* Windows: 32,767 characters
* macOS: 64 characters
* Linux: 16 characters
* NetBSD: limited to `PTHREAD_MAX_NAMELEN_NP`
* FreeBSD and OpenBSD: limited to `MAXCOMLEN`
**Default:** `'WorkerThread'`.
### Event: `'error'`
<!-- YAML
added: v10.5.0
-->
* `err` {Error}
The `'error'` event is emitted if the worker thread throws an uncaught
exception. In that case, the worker is terminated.
### Event: `'exit'`
<!-- YAML
added: v10.5.0
-->
* `exitCode` {integer}
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`.
This is the final event emitted by any `Worker` instance.
### Event: `'message'`
<!-- YAML
added: v10.5.0
-->
* `value` {any} The transmitted value
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.
All messages sent from the worker thread are emitted before the
[`'exit'` event][] is emitted on the `Worker` object.
### Event: `'messageerror'`
<!-- YAML
2020-10-06, Version 12.19.0 'Erbium' (LTS) Notable changes: assert: * (SEMVER-MINOR) port common.mustCall() to assert (ConorDavenport) https://github.com/nodejs/node/pull/31982 async_hooks: * (SEMVER-MINOR) add AsyncResource.bind utility (James M Snell) https://github.com/nodejs/node/pull/34574 buffer: * (SEMVER-MINOR) also alias BigUInt methods (Anna Henningsen) https://github.com/nodejs/node/pull/34960 * (SEMVER-MINOR) alias UInt ➡️ Uint in buffer methods (Anna Henningsen) https://github.com/nodejs/node/pull/34729 build: * (SEMVER-MINOR) add build flag for OSS-Fuzz integration (davkor) https://github.com/nodejs/node/pull/34761 cli: * (SEMVER-MINOR) add alias for report-directory to make it consistent (Ash Cripps) https://github.com/nodejs/node/pull/33587 crypto: * (SEMVER-MINOR) allow KeyObjects in postMessage (Tobias Nießen) https://github.com/nodejs/node/pull/33360 * (SEMVER-MINOR) add randomInt function (Oli Lalonde) https://github.com/nodejs/node/pull/34600 deps: * upgrade to libuv 1.39.0 (Colin Ihrig) https://github.com/nodejs/node/pull/34915 * upgrade npm to 6.14.7 (claudiahdz) https://github.com/nodejs/node/pull/34468 * upgrade to libuv 1.38.1 (Colin Ihrig) https://github.com/nodejs/node/pull/34187 dgram: * (SEMVER-MINOR) add IPv6 scope id suffix to received udp6 dgrams (Pekka Nikander) https://github.com/nodejs/node/pull/14500 * (SEMVER-MINOR) allow typed arrays in .send() (Sarat Addepalli) https://github.com/nodejs/node/pull/22413 doc: * (SEMVER-MINOR) Add maxTotalSockets option to agent constructor (rickyes) https://github.com/nodejs/node/pull/33617 * (SEMVER-MINOR) add basic embedding example documentation (Anna Henningsen) https://github.com/nodejs/node/pull/30467 * add Ricky Zhou to collaborators (rickyes) https://github.com/nodejs/node/pull/34676 * add release key for Ruy Adorno (Ruy Adorno) https://github.com/nodejs/node/pull/34628 * add DerekNonGeneric to collaborators (Derek Lewis) https://github.com/nodejs/node/pull/34602 * add AshCripps to collaborators (Ash Cripps) https://github.com/nodejs/node/pull/34494 * add HarshithaKP to collaborators (Harshitha K P) https://github.com/nodejs/node/pull/34417 * add rexagod to collaborators (Pranshu Srivastava) https://github.com/nodejs/node/pull/34457 * add release key for Richard Lau (Richard Lau) https://github.com/nodejs/node/pull/34397 * add danielleadams to collaborators (Danielle Adams) https://github.com/nodejs/node/pull/34360 * add sxa as collaborator (Stewart X Addison) https://github.com/nodejs/node/pull/34338 * add ruyadorno to collaborators (Ruy Adorno) https://github.com/nodejs/node/pull/34297 * (SEMVER-MAJOR) deprecate process.umask() with no arguments (Colin Ihrig) https://github.com/nodejs/node/pull/32499 embedding: * (SEMVER-MINOR) make Stop() stop Workers (Anna Henningsen) https://github.com/nodejs/node/pull/32531 * (SEMVER-MINOR) provide hook for custom process.exit() behaviour (Anna Henningsen) https://github.com/nodejs/node/pull/32531 fs: * (SEMVER-MINOR) implement lutimes (Maël Nison) https://github.com/nodejs/node/pull/33399 http: * (SEMVER-MINOR) add maxTotalSockets to agent class (rickyes) https://github.com/nodejs/node/pull/33617 * (SEMVER-MINOR) return this from IncomingMessage#destroy() (Colin Ihrig) https://github.com/nodejs/node/pull/32789 * (SEMVER-MINOR) expose host and protocol on ClientRequest (wenningplus) https://github.com/nodejs/node/pull/33803 http2: * (SEMVER-MINOR) return this for Http2ServerRequest#setTimeout (Pranshu Srivastava) https://github.com/nodejs/node/pull/33994 * (SEMVER-MINOR) do not modify explicity set date headers (Pranshu Srivastava) https://github.com/nodejs/node/pull/33160 module: * (SEMVER-MINOR) named exports for CJS via static analysis (Guy Bedford) https://github.com/nodejs/node/pull/35249 * (SEMVER-MINOR) exports pattern support (Guy Bedford) https://github.com/nodejs/node/pull/34718 * (SEMVER-MINOR) package "imports" field (Guy Bedford) https://github.com/nodejs/node/pull/34117 * (SEMVER-MINOR) deprecate module.parent (Antoine du HAMEL) https://github.com/nodejs/node/pull/32217 n-api: * (SEMVER-MINOR) create N-API version 7 (Gabriel Schulhof) https://github.com/nodejs/node/pull/35199 * (SEMVER-MINOR) support type-tagging objects (Gabriel Schulhof) https://github.com/nodejs/node/pull/28237 n-api,src: * (SEMVER-MINOR) provide asynchronous cleanup hooks (Anna Henningsen) https://github.com/nodejs/node/pull/34572 perf_hooks: * (SEMVER-MINOR) add idleTime and event loop util (Trevor Norris) https://github.com/nodejs/node/pull/34938 timers: * (SEMVER-MINOR) allow timers to be used as primitives (Denys Otrishko) https://github.com/nodejs/node/pull/34017 tls: * (SEMVER-MINOR) make 'createSecureContext' honor more options (Mateusz Krawczuk) https://github.com/nodejs/node/pull/33974 worker: * (SEMVER-MINOR) add public method for marking objects as untransferable (Anna Henningsen) https://github.com/nodejs/node/pull/33979 * (SEMVER-MINOR) emit `'messagerror'` events for failed deserialization (Anna Henningsen) https://github.com/nodejs/node/pull/33772 * (SEMVER-MINOR) allow passing JS wrapper objects via postMessage (Anna Henningsen) https://github.com/nodejs/node/pull/33772 * (SEMVER-MINOR) allow transferring/cloning generic BaseObjects (Anna Henningsen) https://github.com/nodejs/node/pull/33772 * (SEMVER-MINOR) add option to track unmanaged file descriptors (Anna Henningsen) https://github.com/nodejs/node/pull/34303 * (SEMVER-MINOR) add stack size resource limit option (Anna Henningsen) https://github.com/nodejs/node/pull/33085 worker,fs: * (SEMVER-MINOR) make FileHandle transferable (Anna Henningsen) https://github.com/nodejs/node/pull/33772 zlib: * (SEMVER-MINOR) add `maxOutputLength` option (unknown) https://github.com/nodejs/node/pull/33516 * switch to lazy init for zlib streams (Andrey Pechkurov) https://github.com/nodejs/node/pull/34048 PR-URL: https://github.com/nodejs/node/pull/35401
2020-09-28 10:54:13 -07:00
added:
- v14.5.0
- v12.19.0
-->
* `error` {Error} An Error object
The `'messageerror'` event is emitted when deserializing a message failed.
### Event: `'online'`
<!-- YAML
added: v10.5.0
-->
The `'online'` event is emitted when the worker thread has started executing
JavaScript code.
### `worker.getHeapSnapshot([options])`
<!-- YAML
added:
- v13.9.0
- v12.17.0
changes:
- version: v19.1.0
pr-url: https://github.com/nodejs/node/pull/44989
description: Support options to configure the heap snapshot.
-->
* `options` {Object}
* `exposeInternals` {boolean} If true, expose internals in the heap snapshot.
**Default:** `false`.
* `exposeNumericValues` {boolean} If true, expose numeric values in
artificial fields. **Default:** `false`.
* Returns: {Promise} A promise for a Readable Stream containing
a V8 heap snapshot
Returns a readable stream for a V8 snapshot of the current state of the Worker.
See [`v8.getHeapSnapshot()`][] for more details.
If the Worker thread is no longer running, which may occur before the
[`'exit'` event][] is emitted, the returned `Promise` is rejected
immediately with an [`ERR_WORKER_NOT_RUNNING`][] error.
### `worker.getHeapStatistics()`
<!-- YAML
2025-05-21, Version 22.16.0 'Jod' (LTS) Notable changes: deps: * update timezone to 2025b (Node.js GitHub Bot) https://github.com/nodejs/node/pull/57857 doc: * add dario-piotrowicz to collaborators (Dario Piotrowicz) https://github.com/nodejs/node/pull/58102 * (SEMVER-MINOR) graduate multiple experimental apis (James M Snell) https://github.com/nodejs/node/pull/57765 esm: * (SEMVER-MINOR) graduate import.meta properties (James M Snell) https://github.com/nodejs/node/pull/58011 * (SEMVER-MINOR) support top-level Wasm without package type (Guy Bedford) https://github.com/nodejs/node/pull/57610 sqlite: * (SEMVER-MINOR) add StatementSync.prototype.columns() (Colin Ihrig) https://github.com/nodejs/node/pull/57490 src: * (SEMVER-MINOR) set default config as `node.config.json` (Marco Ippolito) https://github.com/nodejs/node/pull/57171 * (SEMVER-MINOR) create `THROW_ERR_OPTIONS_BEFORE_BOOTSTRAPPING` (Marco Ippolito) https://github.com/nodejs/node/pull/57016 * (SEMVER-MINOR) add config file support (Marco Ippolito) https://github.com/nodejs/node/pull/57016 * (SEMVER-MINOR) add ExecutionAsyncId getter for any Context (Attila Szegedi) https://github.com/nodejs/node/pull/57820 stream: * (SEMVER-MINOR) preserve AsyncLocalStorage context in finished() (Gürgün Dayıoğlu) https://github.com/nodejs/node/pull/57865 util: * (SEMVER-MINOR) add `types.isFloat16Array()` (Livia Medeiros) https://github.com/nodejs/node/pull/57879 worker: * (SEMVER-MINOR) add worker.getHeapStatistics() (Matteo Collina) https://github.com/nodejs/node/pull/57888 PR-URL: https://github.com/nodejs/node/pull/58388
2025-05-19 12:38:17 +02:00
added:
- v24.0.0
- v22.16.0
-->
* Returns: {Promise}
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.
### `worker.performance`
<!-- YAML
added:
- v15.1.0
2021-05-11, Version 14.17.0 'Fermium' (LTS) Notable Changes: Diagnostics channel (experimental module): `diagnostics_channel` is a new experimental module that provides an API to create named channels to report arbitrary message data for diagnostics purposes. The module was initially introduced in Node.js v15.1.0 and is backported to v14.17.0 to enable testing it at a larger scale. With `diagnostics_channel`, Node.js core and module authors can publish contextual data about what they are doing at a given time. This could be the hostname and query string of a mysql query, for example. Just create a named channel with `dc.channel(name)` and call `channel.publish(data)` to send the data to any listeners to that channel. ```js const dc = require('diagnostics_channel'); const channel = dc.channel('mysql.query'); MySQL.prototype.query = function query(queryString, values, callback) { // Broadcast query information whenever a query is made channel.publish({ query: queryString, host: this.hostname, }); this.doQuery(queryString, values, callback); }; ``` Channels are like one big global event emitter but are split into separate objects to ensure they get the best performance. If nothing is listening to the channel, the publishing overhead should be as close to zero as possible. Consuming channel data is as easy as using `channel.subscribe(listener)` to run a function whenever a message is published to that channel. ```js const dc = require('diagnostics_channel'); const channel = dc.channel('mysql.query'); channel.subscribe(({ query, host }) => { console.log(`mysql query to ${host}: ${query}`); }); ``` The data captured can be used to provide context for what an app is doing at a given time. This can be used for things like augmenting tracing data, tracking network and filesystem activity, logging queries, and many other things. It's also a very useful data source for diagnostics tools to provide a clearer picture of exactly what the application is doing at a given point in the data they are presenting. Contributed by Stephen Belanger (https://github.com/nodejs/node/pull/34895). UUID support in the crypto module: The new `crypto.randomUUID()` method now allows to generate random [RFC 4122](https://www.rfc-editor.org/rfc/rfc4122.txt) Version 4 UUID strings: ```js const { randomUUID } = require('crypto'); console.log(randomUUID()); // 'aa7c91a1-f8fc-4339-b9db-f93fc7233429' ``` Contributed by James M Snell (https://github.com/nodejs/node/pull/36729). Experimental support for `AbortController` and `AbortSignal`: Node.js 14.17.0 adds experimental partial support for `AbortController` and `AbortSignal`. Both constructors can be enabled globally using the `--experimental-abortcontroller` flag. Additionally, several Node.js APIs have been updated to support `AbortSignal` for cancellation. It is not mandatory to use the built-in constructors with them. Any spec-compliant third-party alternatives should be compatible. `AbortSignal` support was added to the following methods: * `child_process.exec` * `child_process.execFile` * `child_process.fork` * `child_process.spawn` * `dgram.createSocket` * `events.on` * `events.once` * `fs.readFile` * `fs.watch` * `fs.writeFile` * `http.request` * `https.request` * `http2Session.request` * The promisified variants of `setImmediate` and `setTimeout` Other notable changes: * doc: * revoke deprecation of legacy url, change status to legacy (James M Snell) (https://github.com/nodejs/node/pull/37784) * add legacy status to stability index (James M Snell) (https://github.com/nodejs/node/pull/37784) * upgrade stability status of report API (Gireesh Punathil) (https://github.com/nodejs/node/pull/35654) * deps: * V8: Backport various patches for Apple Silicon support (BoHong Li) (https://github.com/nodejs/node/pull/38051) * update ICU to 68.1 (Michaël Zasso) (https://github.com/nodejs/node/pull/36187) * upgrade to libuv 1.41.0 (Colin Ihrig) (https://github.com/nodejs/node/pull/37360) * http: * add http.ClientRequest.getRawHeaderNames() (simov) (https://github.com/nodejs/node/pull/37660) * report request start and end with diagnostics\_channel (Stephen Belanger) (https://github.com/nodejs/node/pull/34895) * util: * add getSystemErrorMap() impl (eladkeyshawn) (https://github.com/nodejs/node/pull/38101) PR-URL: https://github.com/nodejs/node/pull/38507
2021-05-02 23:12:18 -04:00
- v14.17.0
- v12.22.0
-->
An object that can be used to query performance information from a worker
instance. Similar to [`perf_hooks.performance`][].
#### `performance.eventLoopUtilization([utilization1[, utilization2]])`
<!-- YAML
added:
- v15.1.0
2021-05-11, Version 14.17.0 'Fermium' (LTS) Notable Changes: Diagnostics channel (experimental module): `diagnostics_channel` is a new experimental module that provides an API to create named channels to report arbitrary message data for diagnostics purposes. The module was initially introduced in Node.js v15.1.0 and is backported to v14.17.0 to enable testing it at a larger scale. With `diagnostics_channel`, Node.js core and module authors can publish contextual data about what they are doing at a given time. This could be the hostname and query string of a mysql query, for example. Just create a named channel with `dc.channel(name)` and call `channel.publish(data)` to send the data to any listeners to that channel. ```js const dc = require('diagnostics_channel'); const channel = dc.channel('mysql.query'); MySQL.prototype.query = function query(queryString, values, callback) { // Broadcast query information whenever a query is made channel.publish({ query: queryString, host: this.hostname, }); this.doQuery(queryString, values, callback); }; ``` Channels are like one big global event emitter but are split into separate objects to ensure they get the best performance. If nothing is listening to the channel, the publishing overhead should be as close to zero as possible. Consuming channel data is as easy as using `channel.subscribe(listener)` to run a function whenever a message is published to that channel. ```js const dc = require('diagnostics_channel'); const channel = dc.channel('mysql.query'); channel.subscribe(({ query, host }) => { console.log(`mysql query to ${host}: ${query}`); }); ``` The data captured can be used to provide context for what an app is doing at a given time. This can be used for things like augmenting tracing data, tracking network and filesystem activity, logging queries, and many other things. It's also a very useful data source for diagnostics tools to provide a clearer picture of exactly what the application is doing at a given point in the data they are presenting. Contributed by Stephen Belanger (https://github.com/nodejs/node/pull/34895). UUID support in the crypto module: The new `crypto.randomUUID()` method now allows to generate random [RFC 4122](https://www.rfc-editor.org/rfc/rfc4122.txt) Version 4 UUID strings: ```js const { randomUUID } = require('crypto'); console.log(randomUUID()); // 'aa7c91a1-f8fc-4339-b9db-f93fc7233429' ``` Contributed by James M Snell (https://github.com/nodejs/node/pull/36729). Experimental support for `AbortController` and `AbortSignal`: Node.js 14.17.0 adds experimental partial support for `AbortController` and `AbortSignal`. Both constructors can be enabled globally using the `--experimental-abortcontroller` flag. Additionally, several Node.js APIs have been updated to support `AbortSignal` for cancellation. It is not mandatory to use the built-in constructors with them. Any spec-compliant third-party alternatives should be compatible. `AbortSignal` support was added to the following methods: * `child_process.exec` * `child_process.execFile` * `child_process.fork` * `child_process.spawn` * `dgram.createSocket` * `events.on` * `events.once` * `fs.readFile` * `fs.watch` * `fs.writeFile` * `http.request` * `https.request` * `http2Session.request` * The promisified variants of `setImmediate` and `setTimeout` Other notable changes: * doc: * revoke deprecation of legacy url, change status to legacy (James M Snell) (https://github.com/nodejs/node/pull/37784) * add legacy status to stability index (James M Snell) (https://github.com/nodejs/node/pull/37784) * upgrade stability status of report API (Gireesh Punathil) (https://github.com/nodejs/node/pull/35654) * deps: * V8: Backport various patches for Apple Silicon support (BoHong Li) (https://github.com/nodejs/node/pull/38051) * update ICU to 68.1 (Michaël Zasso) (https://github.com/nodejs/node/pull/36187) * upgrade to libuv 1.41.0 (Colin Ihrig) (https://github.com/nodejs/node/pull/37360) * http: * add http.ClientRequest.getRawHeaderNames() (simov) (https://github.com/nodejs/node/pull/37660) * report request start and end with diagnostics\_channel (Stephen Belanger) (https://github.com/nodejs/node/pull/34895) * util: * add getSystemErrorMap() impl (eladkeyshawn) (https://github.com/nodejs/node/pull/38101) PR-URL: https://github.com/nodejs/node/pull/38507
2021-05-02 23:12:18 -04:00
- v14.17.0
- v12.22.0
-->
* `utilization1` {Object} The result of a previous call to
`eventLoopUtilization()`.
* `utilization2` {Object} The result of a previous call to
`eventLoopUtilization()` prior to `utilization1`.
* Returns: {Object}
* `idle` {number}
* `active` {number}
* `utilization` {number}
The same call as [`perf_hooks` `eventLoopUtilization()`][], except the values
of the worker instance are returned.
One difference is that, unlike the main thread, bootstrapping within a worker
is done within the event loop. So the event loop utilization is
immediately available once the worker's script begins execution.
An `idle` time that does not increase does not indicate that the worker is
stuck in bootstrap. The following examples shows how the worker's entire
lifetime never accumulates any `idle` time, but is still be able to process
messages.
```mjs
import { Worker, isMainThread, parentPort } from 'node:worker_threads';
if (isMainThread) {
const worker = new Worker(new URL(import.meta.url));
setInterval(() => {
worker.postMessage('hi');
console.log(worker.performance.eventLoopUtilization());
}, 100).unref();
} else {
parentPort.on('message', () => console.log('msg')).unref();
(function r(n) {
if (--n < 0) return;
const t = Date.now();
while (Date.now() - t < 300);
setImmediate(r, n);
})(10);
}
```
```cjs
'use strict';
const { Worker, isMainThread, parentPort } = require('node:worker_threads');
if (isMainThread) {
const worker = new Worker(__filename);
setInterval(() => {
worker.postMessage('hi');
console.log(worker.performance.eventLoopUtilization());
}, 100).unref();
} else {
parentPort.on('message', () => console.log('msg')).unref();
(function r(n) {
if (--n < 0) return;
const t = Date.now();
while (Date.now() - t < 300);
setImmediate(r, n);
})(10);
}
```
The event loop utilization of a worker is available only after the [`'online'`
event][] emitted, and if called before this, or after the [`'exit'`
event][], then all properties have the value of `0`.
### `worker.postMessage(value[, transferList])`
<!-- YAML
added: v10.5.0
-->
* `value` {any}
* `transferList` {Object\[]}
Send a message to the worker that is received via
[`require('node:worker_threads').parentPort.on('message')`][].
See [`port.postMessage()`][] for more details.
### `worker.ref()`
<!-- YAML
added: v10.5.0
-->
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.
### `worker.resourceLimits`
<!-- YAML
added:
- v13.2.0
- v12.16.0
-->
* {Object}
* `maxYoungGenerationSizeMb` {number}
* `maxOldGenerationSizeMb` {number}
* `codeRangeSizeMb` {number}
* `stackSizeMb` {number}
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.
If the worker has stopped, the return value is an empty object.
### `worker.stderr`
<!-- YAML
added: v10.5.0
-->
* {stream.Readable}
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.
### `worker.stdin`
<!-- YAML
added: v10.5.0
-->
* {null|stream.Writable}
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`][].
### `worker.stdout`
<!-- YAML
added: v10.5.0
-->
* {stream.Readable}
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.
### `worker.terminate()`
<!-- YAML
added: v10.5.0
worker: refactor `worker.terminate()` At the collaborator summit in Berlin, the behaviour of `worker.terminate()` was discussed. In particular, switching from a callback-based to a Promise-based API was suggested. While investigating that possibility later, it was discovered that `.terminate()` was unintentionally synchronous up until now (including calling its callback synchronously). Also, the topic of its stability has been brought up. I have performed two manual reviews of the native codebase for compatibility with `.terminate()`, and performed some manual fuzz testing with the test suite. At this point, bugs with `.terminate()` should, in my opinion, be treated like bugs in other Node.js features. (It is possible to make Node.js crash with `.terminate()` by messing with internals and/or built-in prototype objects, but that is already the case without `.terminate()` as well.) This commit: - Makes `.terminate()` an asynchronous operation. - Makes `.terminate()` return a `Promise`. - Runtime-deprecates passing a callback. - Removes a warning about its stability from the documentation. - Eliminates an unnecessary extra function from the C++ code. A possible alternative to returning a `Promise` would be to keep the method synchronous and just drop the callback. Generally, providing an asynchronous API does provide us with a bit more flexibility. Refs: https://github.com/nodejs/summit/issues/141 PR-URL: https://github.com/nodejs/node/pull/28021 Reviewed-By: Michaël Zasso <targos@protonmail.com> Reviewed-By: Rich Trott <rtrott@gmail.com> Reviewed-By: Ben Noordhuis <info@bnoordhuis.nl> Reviewed-By: Tiancheng "Timothy" Gu <timothygu99@gmail.com> Reviewed-By: Ruben Bridgewater <ruben@bridgewater.de> Reviewed-By: Benjamin Gruenbaum <benjamingr@gmail.com> Reviewed-By: James M Snell <jasnell@gmail.com>
2019-06-02 15:09:57 +02:00
changes:
2019-06-27, Version 12.5.0 (Current) Notable changes: * build: * The startup time is reduced by enabling V8 snapshots by default https://github.com/nodejs/node/pull/28181 * deps: * Updated `V8` to 7.5.288.22 https://github.com/nodejs/node/pull/27375 * The numeric separator (v8.dev/features/numeric-separators) feature is now enabled by default * Updated `OpenSSL` to 1.1.1c https://github.com/nodejs/node/pull/28211 * inspector: * The `--inspect-publish-uid` flag was added to specify ways of the inspector web socket url exposure https://github.com/nodejs/node/pull/27741 * n-api: * Accessors on napi_define_* are now ECMAScript-compliant https://github.com/nodejs/node/pull/27851 * report: * The cpu info got added to the report output https://github.com/nodejs/node/pull/28188 * src: * Restore the original state of the stdio file descriptors on exit to prevent leaving stdio in raw or non-blocking mode https://github.com/nodejs/node/pull/24260 * tools,gyp: * Introduce MSVS 2019 https://github.com/nodejs/node/pull/27375 * util: * inspect: * Array grouping became more compact and uses more columns than before https://github.com/nodejs/node/pull/28059 https://github.com/nodejs/node/pull/28070 * Long strings will not be split at 80 characters anymore. Instead they will be split on new lines https://github.com/nodejs/node/pull/28055 * worker: * `worker.terminate()` now returns a promise and using the callback is deprecated https://github.com/nodejs/node/pull/28021 PR-URL: https://github.com/nodejs/node/pull/28268
2019-06-17 21:31:37 +02:00
- version: v12.5.0
worker: refactor `worker.terminate()` At the collaborator summit in Berlin, the behaviour of `worker.terminate()` was discussed. In particular, switching from a callback-based to a Promise-based API was suggested. While investigating that possibility later, it was discovered that `.terminate()` was unintentionally synchronous up until now (including calling its callback synchronously). Also, the topic of its stability has been brought up. I have performed two manual reviews of the native codebase for compatibility with `.terminate()`, and performed some manual fuzz testing with the test suite. At this point, bugs with `.terminate()` should, in my opinion, be treated like bugs in other Node.js features. (It is possible to make Node.js crash with `.terminate()` by messing with internals and/or built-in prototype objects, but that is already the case without `.terminate()` as well.) This commit: - Makes `.terminate()` an asynchronous operation. - Makes `.terminate()` return a `Promise`. - Runtime-deprecates passing a callback. - Removes a warning about its stability from the documentation. - Eliminates an unnecessary extra function from the C++ code. A possible alternative to returning a `Promise` would be to keep the method synchronous and just drop the callback. Generally, providing an asynchronous API does provide us with a bit more flexibility. Refs: https://github.com/nodejs/summit/issues/141 PR-URL: https://github.com/nodejs/node/pull/28021 Reviewed-By: Michaël Zasso <targos@protonmail.com> Reviewed-By: Rich Trott <rtrott@gmail.com> Reviewed-By: Ben Noordhuis <info@bnoordhuis.nl> Reviewed-By: Tiancheng "Timothy" Gu <timothygu99@gmail.com> Reviewed-By: Ruben Bridgewater <ruben@bridgewater.de> Reviewed-By: Benjamin Gruenbaum <benjamingr@gmail.com> Reviewed-By: James M Snell <jasnell@gmail.com>
2019-06-02 15:09:57 +02:00
pr-url: https://github.com/nodejs/node/pull/28021
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.
-->
worker: refactor `worker.terminate()` At the collaborator summit in Berlin, the behaviour of `worker.terminate()` was discussed. In particular, switching from a callback-based to a Promise-based API was suggested. While investigating that possibility later, it was discovered that `.terminate()` was unintentionally synchronous up until now (including calling its callback synchronously). Also, the topic of its stability has been brought up. I have performed two manual reviews of the native codebase for compatibility with `.terminate()`, and performed some manual fuzz testing with the test suite. At this point, bugs with `.terminate()` should, in my opinion, be treated like bugs in other Node.js features. (It is possible to make Node.js crash with `.terminate()` by messing with internals and/or built-in prototype objects, but that is already the case without `.terminate()` as well.) This commit: - Makes `.terminate()` an asynchronous operation. - Makes `.terminate()` return a `Promise`. - Runtime-deprecates passing a callback. - Removes a warning about its stability from the documentation. - Eliminates an unnecessary extra function from the C++ code. A possible alternative to returning a `Promise` would be to keep the method synchronous and just drop the callback. Generally, providing an asynchronous API does provide us with a bit more flexibility. Refs: https://github.com/nodejs/summit/issues/141 PR-URL: https://github.com/nodejs/node/pull/28021 Reviewed-By: Michaël Zasso <targos@protonmail.com> Reviewed-By: Rich Trott <rtrott@gmail.com> Reviewed-By: Ben Noordhuis <info@bnoordhuis.nl> Reviewed-By: Tiancheng "Timothy" Gu <timothygu99@gmail.com> Reviewed-By: Ruben Bridgewater <ruben@bridgewater.de> Reviewed-By: Benjamin Gruenbaum <benjamingr@gmail.com> Reviewed-By: James M Snell <jasnell@gmail.com>
2019-06-02 15:09:57 +02:00
* Returns: {Promise}
Stop all JavaScript execution in the worker thread as soon as possible.
worker: refactor `worker.terminate()` At the collaborator summit in Berlin, the behaviour of `worker.terminate()` was discussed. In particular, switching from a callback-based to a Promise-based API was suggested. While investigating that possibility later, it was discovered that `.terminate()` was unintentionally synchronous up until now (including calling its callback synchronously). Also, the topic of its stability has been brought up. I have performed two manual reviews of the native codebase for compatibility with `.terminate()`, and performed some manual fuzz testing with the test suite. At this point, bugs with `.terminate()` should, in my opinion, be treated like bugs in other Node.js features. (It is possible to make Node.js crash with `.terminate()` by messing with internals and/or built-in prototype objects, but that is already the case without `.terminate()` as well.) This commit: - Makes `.terminate()` an asynchronous operation. - Makes `.terminate()` return a `Promise`. - Runtime-deprecates passing a callback. - Removes a warning about its stability from the documentation. - Eliminates an unnecessary extra function from the C++ code. A possible alternative to returning a `Promise` would be to keep the method synchronous and just drop the callback. Generally, providing an asynchronous API does provide us with a bit more flexibility. Refs: https://github.com/nodejs/summit/issues/141 PR-URL: https://github.com/nodejs/node/pull/28021 Reviewed-By: Michaël Zasso <targos@protonmail.com> Reviewed-By: Rich Trott <rtrott@gmail.com> Reviewed-By: Ben Noordhuis <info@bnoordhuis.nl> Reviewed-By: Tiancheng "Timothy" Gu <timothygu99@gmail.com> Reviewed-By: Ruben Bridgewater <ruben@bridgewater.de> Reviewed-By: Benjamin Gruenbaum <benjamingr@gmail.com> Reviewed-By: James M Snell <jasnell@gmail.com>
2019-06-02 15:09:57 +02:00
Returns a Promise for the exit code that is fulfilled when the
[`'exit'` event][] is emitted.
### `worker.threadId`
<!-- YAML
added: v10.5.0
-->
* {integer}
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.
### `worker.unref()`
<!-- YAML
added: v10.5.0
-->
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.
### `worker[Symbol.asyncDispose]()`
<!-- YAML
2025-06-09, Version 24.2.0 (Current) Notable changes: doc: * add Filip Skokan to TSC (Rafael Gonzaga) https://github.com/nodejs/node/pull/58499 * deprecate `util.isNativeError` in favor of `Error.isError` (Miguel Marcondes Filho) https://github.com/nodejs/node/pull/58262 * deprecate passing an empty string to `options.shell` (Antoine du Hamel) https://github.com/nodejs/node/pull/58564 * deprecate HTTP/2 priority signaling (Matteo Collina) https://github.com/nodejs/node/pull/58313 * (SEMVER-MINOR) graduate `Symbol.dispose`/`asyncDispose` from experimental (James M Snell) https://github.com/nodejs/node/pull/58467 esm: * (SEMVER-MINOR) implement import.meta.main (Joe) https://github.com/nodejs/node/pull/57804 fs: * (SEMVER-MINOR) add `autoClose` option to `FileHandle` `readableWebStream` (James M Snell) https://github.com/nodejs/node/pull/58548 http: * deprecate instantiating classes without new (Yagiz Nizipli) https://github.com/nodejs/node/pull/58518 http2: * (SEMVER-MINOR) add diagnostics channel 'http2.server.stream.finish' (Darshan Sen) https://github.com/nodejs/node/pull/58560 * (SEMVER-MAJOR) remove support for priority signaling (Matteo Collina) https://github.com/nodejs/node/pull/58293 lib: * (SEMVER-MINOR) graduate error codes that have been around for years (James M Snell) https://github.com/nodejs/node/pull/58541 perf_hooks: * (SEMVER-MINOR) make event loop delay histogram disposable (James M Snell) https://github.com/nodejs/node/pull/58384 src: * (SEMVER-MINOR) support namespace options in configuration file (Pietro Marchini) https://github.com/nodejs/node/pull/58073 permission: * implicit allow-fs-read to app entrypoint (Rafael Gonzaga) https://github.com/nodejs/node/pull/58579 test: * (SEMVER-MINOR) add disposable histogram test (James M Snell) https://github.com/nodejs/node/pull/58384 * (SEMVER-MINOR) add test for async disposable worker thread (James M Snell) https://github.com/nodejs/node/pull/58385 util: * (SEMVER-MINOR) add 'none' style to styleText (James M Snell) https://github.com/nodejs/node/pull/58437 worker: * (SEMVER-MINOR) make Worker async disposable (James M Snell) https://github.com/nodejs/node/pull/58385 PR-URL: https://github.com/nodejs/node/pull/58635
2025-06-08 14:03:03 -04:00
added: v24.2.0
-->
Calls [`worker.terminate()`][] when the dispose scope is exited.
```js
async function example() {
await using worker = new Worker('for (;;) {}', { eval: true });
// Worker is automatically terminate when the scope is exited.
}
```
## Notes
### Synchronous blocking of stdio
`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.
```mjs
import {
Worker,
isMainThread,
} from 'node:worker_threads';
if (isMainThread) {
new Worker(new URL(import.meta.url));
for (let n = 0; n < 1e10; n++) {
// Looping to simulate work.
}
} else {
// This output will be blocked by the for loop in the main thread.
console.log('foo');
}
```
```cjs
'use strict';
const {
Worker,
isMainThread,
} = require('node:worker_threads');
if (isMainThread) {
new Worker(__filename);
for (let n = 0; n < 1e10; n++) {
// Looping to simulate work.
}
} else {
// This output will be blocked by the for loop in the main thread.
console.log('foo');
}
```
### Launching worker threads from preload scripts
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.
[Addons worker support]: addons.md#worker-support
[ECMAScript module loader]: esm.md#data-imports
[HTML structured clone algorithm]: https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm
[Signals events]: process.md#signal-events
[Web Workers]: https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API
[`'close'` event]: #event-close
[`'exit'` event]: #event-exit
[`'online'` event]: #event-online
[`--max-old-space-size`]: cli.md#--max-old-space-sizesize-in-mib
[`--max-semi-space-size`]: cli.md#--max-semi-space-sizesize-in-mib
[`AsyncResource`]: async_hooks.md#class-asyncresource
[`Buffer.allocUnsafe()`]: buffer.md#static-method-bufferallocunsafesize
[`ERR_MISSING_MESSAGE_PORT_IN_TRANSFER_LIST`]: errors.md#err_missing_message_port_in_transfer_list
[`ERR_WORKER_MESSAGING_ERRORED`]: errors.md#err_worker_messaging_errored
[`ERR_WORKER_MESSAGING_FAILED`]: errors.md#err_worker_messaging_failed
[`ERR_WORKER_MESSAGING_SAME_THREAD`]: errors.md#err_worker_messaging_same_thread
[`ERR_WORKER_MESSAGING_TIMEOUT`]: errors.md#err_worker_messaging_timeout
[`ERR_WORKER_NOT_RUNNING`]: errors.md#err_worker_not_running
[`FileHandle`]: fs.md#class-filehandle
[`MessagePort`]: #class-messageport
[`WebAssembly.Module`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/Module
[`Worker constructor options`]: #new-workerfilename-options
[`Worker`]: #class-worker
[`data:` URL]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URIs
[`fs.close()`]: fs.md#fsclosefd-callback
[`fs.open()`]: fs.md#fsopenpath-flags-mode-callback
[`markAsUntransferable()`]: #workermarkasuntransferableobject
[`node:cluster` module]: cluster.md
[`perf_hooks.performance`]: perf_hooks.md#perf_hooksperformance
[`perf_hooks` `eventLoopUtilization()`]: perf_hooks.md#performanceeventlooputilizationutilization1-utilization2
[`port.on('message')`]: #event-message
[`port.onmessage()`]: https://developer.mozilla.org/en-US/docs/Web/API/MessagePort/onmessage
[`port.postMessage()`]: #portpostmessagevalue-transferlist
[`process.abort()`]: process.md#processabort
[`process.chdir()`]: process.md#processchdirdirectory
[`process.env`]: process.md#processenv
[`process.execArgv`]: process.md#processexecargv
[`process.exit()`]: process.md#processexitcode
[`process.stderr`]: process.md#processstderr
[`process.stdin`]: process.md#processstdin
[`process.stdout`]: process.md#processstdout
[`process.title`]: process.md#processtitle
[`require('node:worker_threads').isMainThread`]: #workerismainthread
[`require('node:worker_threads').parentPort.on('message')`]: #event-message
[`require('node:worker_threads').parentPort.postMessage()`]: #workerpostmessagevalue-transferlist
[`require('node:worker_threads').parentPort`]: #workerparentport
[`require('node:worker_threads').threadId`]: #workerthreadid
[`require('node:worker_threads').workerData`]: #workerworkerdata
[`trace_events`]: tracing.md
[`v8.getHeapSnapshot()`]: v8.md#v8getheapsnapshotoptions
[`v8.getHeapStatistics()`]: v8.md#v8getheapstatistics
[`vm`]: vm.md
[`worker.SHARE_ENV`]: #workershare_env
[`worker.on('message')`]: #event-message_1
[`worker.postMessage()`]: #workerpostmessagevalue-transferlist
[`worker.terminate()`]: #workerterminate
[`worker.threadId`]: #workerthreadid_1
[async-resource-worker-pool]: async_context.md#using-asyncresource-for-a-worker-thread-pool
[browser `MessagePort`]: https://developer.mozilla.org/en-US/docs/Web/API/MessagePort
[child processes]: child_process.md
[contextified]: vm.md#what-does-it-mean-to-contextify-an-object
[v8.serdes]: v8.md#serialization-api