diff --git a/content/api/v18/addons.en.md b/content/api/v18/addons.en.md index a214eb545a..b83cb3238e 100644 --- a/content/api/v18/addons.en.md +++ b/content/api/v18/addons.en.md @@ -2,20 +2,20 @@ title: 'addons' displayTitle: 'C++ addons' category: 'api' -editPage: 'https://github.com/nodejs/node/blob/v18.8.0/doc/api/addons.md' +editPage: 'https://github.com/nodejs/node/blob/v18.9.0/doc/api/addons.md' version: 'v18' --- - + - + _Addons_ are dynamically-linked shared objects written in C++. The [`require()`][require] function can load addons as ordinary Node.js modules. Addons provide an interface between JavaScript and C/C++ libraries. There are three options for implementing addons: Node-API, nan, or direct -use of internal V8, libuv and Node.js libraries. Unless there is a need for +use of internal V8, libuv, and Node.js libraries. Unless there is a need for direct access to functionality which is not exposed by Node-API, use Node-API. Refer to [C/C++ addons with Node-API](n-api.md) for more information on Node-API. @@ -46,7 +46,7 @@ involving knowledge of several components and APIs: * Node.js includes other statically linked libraries including OpenSSL. These other libraries are located in the `deps/` directory in the Node.js source - tree. Only the libuv, OpenSSL, V8 and zlib symbols are purposefully + tree. Only the libuv, OpenSSL, V8, and zlib symbols are purposefully re-exported by Node.js and may be used to various extents by addons. See [Linking to libraries included with Node.js][] for additional information. @@ -242,7 +242,7 @@ NODE_MODULE_INIT(/* exports, module, context */) { ##### Worker support - + In order to be loaded from multiple Node.js environments, such as a main thread and a Worker thread, an add-on needs to either: @@ -392,7 +392,7 @@ try { #### Linking to libraries included with Node.js -Node.js uses statically linked libraries such as V8, libuv and OpenSSL. All +Node.js uses statically linked libraries such as V8, libuv, and OpenSSL. All addons are required to link to V8 and may link to any of the other dependencies as well. Typically, this is as simple as including the appropriate `#include <...>` statements (e.g. `#include `) and `node-gyp` will locate @@ -441,7 +441,7 @@ illustration of how it can be used. ### Node-API - + Node-API is an API for building native addons. It is independent from the underlying JavaScript runtime (e.g. V8) and is maintained as part of diff --git a/content/api/v18/assert.en.md b/content/api/v18/assert.en.md index cb9971009d..277200d52d 100644 --- a/content/api/v18/assert.en.md +++ b/content/api/v18/assert.en.md @@ -2,22 +2,22 @@ title: 'assert' displayTitle: 'Assert' category: 'api' -editPage: 'https://github.com/nodejs/node/blob/v18.8.0/doc/api/assert.md' +editPage: 'https://github.com/nodejs/node/blob/v18.9.0/doc/api/assert.md' version: 'v18' --- - + - + - + The `node:assert` module provides a set of assertion functions for verifying invariants. ### Strict assertion mode - + In strict assertion mode, non-strict methods behave like their corresponding strict methods. For example, [`assert.deepEqual()`][] will behave like @@ -116,16 +116,16 @@ Legacy assertion mode may have surprising results, especially when using assert.deepEqual(/a/gi, new Date()); ``` -### assert.AssertionError +### assert.AssertionError * Extends: [`errors.Error`](/api/errors#error) Indicates the failure of an assertion. All errors thrown by the `node:assert` module will be instances of the `AssertionError` class. -#### `new assert.AssertionError(options)` +#### `new assert.AssertionError(options)` - + * `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) * `message` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) If provided, the error message is set to this value. @@ -200,17 +200,17 @@ try { } ``` -### `assert.CallTracker` +### `assert.CallTracker` - + - + This feature is currently experimental and behavior might still change. -#### `new assert.CallTracker()` +#### `new assert.CallTracker()` - + Creates a new [`CallTracker`][] object which can be used to track if functions were called a specific number of times. The `tracker.verify()` must be called @@ -256,9 +256,9 @@ process.on('exit', () => { }); ``` -#### `tracker.calls([fn][, exact])` +#### `tracker.calls([fn][, exact])` - + * `fn` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) **Default:** A no-op function. * `exact` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) **Default:** `1`. @@ -295,9 +295,9 @@ function func() {} const callsfunc = tracker.calls(func); ``` -#### `tracker.getCalls(fn)` +#### `tracker.getCalls(fn)` - + * `fn` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function). @@ -334,9 +334,9 @@ assert.deepStrictEqual(tracker.getCalls(callsfunc), [{ thisArg: this, arguments: [1, 2, 3 ] }]); ``` -#### `tracker.report()` +#### `tracker.report()` - + * Returns: [`Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array) of objects containing information about the wrapper functions returned by [`tracker.calls()`][]. @@ -403,9 +403,9 @@ tracker.report(); // ] ``` -#### `tracker.reset([fn])` +#### `tracker.reset([fn])` - + * `fn` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) a tracked function to reset. @@ -443,9 +443,9 @@ tracker.reset(callsfunc); tracker.getCalls(callsfunc).length === 0; ``` -#### `tracker.verify()` +#### `tracker.verify()` - + Iterates through the list of functions passed to [`tracker.calls()`][] and will throw an error for functions that @@ -487,18 +487,18 @@ callsfunc(); tracker.verify(); ``` -### `assert(value[, message])` +### `assert(value[, message])` - + * `value` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) The input that is checked for being truthy. * `message` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Error`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error) An alias of [`assert.ok()`][]. -### `assert.deepEqual(actual, expected[, message])` +### `assert.deepEqual(actual, expected[, message])` - + * `actual` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) * `expected` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) @@ -510,7 +510,7 @@ An alias of [`assert.deepStrictEqual()`][]. **Legacy assertion mode** - + Tests for deep equality between the `actual` and `expected` parameters. Consider using [`assert.deepStrictEqual()`][] instead. [`assert.deepEqual()`][] can have @@ -636,9 +636,9 @@ parameter is undefined, a default error message is assigned. If the `message` parameter is an instance of an [`Error`][] then it will be thrown instead of the [`AssertionError`][]. -### `assert.deepStrictEqual(actual, expected[, message])` +### `assert.deepStrictEqual(actual, expected[, message])` - + * `actual` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) * `expected` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) @@ -858,9 +858,9 @@ parameter is undefined, a default error message is assigned. If the `message` parameter is an instance of an [`Error`][] then it will be thrown instead of the `AssertionError`. -### `assert.doesNotMatch(string, regexp[, message])` +### `assert.doesNotMatch(string, regexp[, message])` - + * `string` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) * `regexp` [`RegExp`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp) @@ -901,9 +901,9 @@ undefined, a default error message is assigned. If the `message` parameter is an instance of an [`Error`][] then it will be thrown instead of the [`AssertionError`][]. -### `assert.doesNotReject(asyncFn[, error][, message])` +### `assert.doesNotReject(asyncFn[, error][, message])` - + * `asyncFn` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) | [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) * `error` [`RegExp`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp) | [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) @@ -972,9 +972,9 @@ assert.doesNotReject(Promise.reject(new TypeError('Wrong value'))) }); ``` -### `assert.doesNotThrow(fn[, error][, message])` +### `assert.doesNotThrow(fn[, error][, message])` - + * `fn` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) * `error` [`RegExp`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp) | [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) @@ -1078,9 +1078,9 @@ assert.doesNotThrow( // Throws: AssertionError: Got unwanted exception: Whoops ``` -### `assert.equal(actual, expected[, message])` +### `assert.equal(actual, expected[, message])` - + * `actual` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) * `expected` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) @@ -1092,7 +1092,7 @@ An alias of [`assert.strictEqual()`][]. **Legacy assertion mode** - + Tests shallow, coercive equality between the `actual` and `expected` parameters using the [`==` operator][]. `NaN` is specially handled @@ -1136,9 +1136,9 @@ parameter is undefined, a default error message is assigned. If the `message` parameter is an instance of an [`Error`][] then it will be thrown instead of the `AssertionError`. -### `assert.fail([message])` +### `assert.fail([message])` - + * `message` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Error`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error) **Default:** `'Failed'` @@ -1175,11 +1175,11 @@ assert.fail(new TypeError('need array')); Using `assert.fail()` with more than two arguments is possible but deprecated. See below for further details. -### `assert.fail(actual, expected[, message[, operator[, stackStartFn]]])` +### `assert.fail(actual, expected[, message[, operator[, stackStartFn]]])` - + - functions instead."}}} /> + * `actual` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) * `expected` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) @@ -1265,9 +1265,9 @@ suppressFrame(); // ... ``` -### `assert.ifError(value)` +### `assert.ifError(value)` - + * `value` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) @@ -1328,9 +1328,9 @@ let err; // at errorFrame ``` -### `assert.match(string, regexp[, message])` +### `assert.match(string, regexp[, message])` - + * `string` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) * `regexp` [`RegExp`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp) @@ -1371,9 +1371,9 @@ undefined, a default error message is assigned. If the `message` parameter is an instance of an [`Error`][] then it will be thrown instead of the [`AssertionError`][]. -### `assert.notDeepEqual(actual, expected[, message])` +### `assert.notDeepEqual(actual, expected[, message])` - + * `actual` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) * `expected` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) @@ -1385,7 +1385,7 @@ An alias of [`assert.notDeepStrictEqual()`][]. **Legacy assertion mode** - + Tests for any deep inequality. Opposite of [`assert.deepEqual()`][]. @@ -1461,9 +1461,9 @@ If the values are deeply equal, an [`AssertionError`][] is thrown with a `message` parameter is an instance of an [`Error`][] then it will be thrown instead of the `AssertionError`. -### `assert.notDeepStrictEqual(actual, expected[, message])` +### `assert.notDeepStrictEqual(actual, expected[, message])` - + * `actual` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) * `expected` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) @@ -1491,9 +1491,9 @@ the `message` parameter is undefined, a default error message is assigned. If the `message` parameter is an instance of an [`Error`][] then it will be thrown instead of the [`AssertionError`][]. -### `assert.notEqual(actual, expected[, message])` +### `assert.notEqual(actual, expected[, message])` - + * `actual` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) * `expected` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) @@ -1505,7 +1505,7 @@ An alias of [`assert.notStrictEqual()`][]. **Legacy assertion mode** - + Tests shallow, coercive inequality with the [`!=` operator][]. `NaN` is specially handled and treated as being identical if both sides are `NaN`. @@ -1542,9 +1542,9 @@ parameter is undefined, a default error message is assigned. If the `message` parameter is an instance of an [`Error`][] then it will be thrown instead of the `AssertionError`. -### `assert.notStrictEqual(actual, expected[, message])` +### `assert.notStrictEqual(actual, expected[, message])` - + * `actual` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) * `expected` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) @@ -1589,9 +1589,9 @@ If the values are strictly equal, an [`AssertionError`][] is thrown with a `message` parameter is an instance of an [`Error`][] then it will be thrown instead of the `AssertionError`. -### `assert.ok(value[, message])` +### `assert.ok(value[, message])` - + * `value` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) * `message` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Error`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error) @@ -1700,9 +1700,9 @@ assert(0); // assert(0) ``` -### `assert.rejects(asyncFn[, error][, message])` +### `assert.rejects(asyncFn[, error][, message])` - + * `asyncFn` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) | [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) * `error` [`RegExp`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp) | [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) | [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) | [`Error`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error) @@ -1819,33 +1819,49 @@ argument, then `error` is assumed to be omitted and the string will be used for example in [`assert.throws()`][] carefully if using a string as the second argument gets considered. -### `assert.snapshot(value, name)` +### `assert.snapshot(value, name)` - + - + -* `value` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) the value to snapshot -* `name` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) the name of snapshot. +* `value` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) the value to snapshot. +* `name` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) the name of the snapshot. * Returns: [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) -reads a snapshot from a file, and compares `value` to the snapshot. -`value` is serialized with [`util.inspect()`][] -If the value is not strictly equal to the snapshot, -`assert.snapshot()` will return a rejected `Promise` -with an [`AssertionError`][]. +Reads the `name` snapshot from a file and compares `value` to the snapshot. +`value` is serialized with [`util.inspect()`][]. If the value is not strictly +equal to the snapshot, `assert.snapshot()` returns a rejected `Promise` with an +[`AssertionError`][]. + +The snapshot filename uses the same basename as the application's main +entrypoint with a `.snapshot` extension. If the snapshot file does not exist, +it is created. The [`--update-assert-snapshot`][] command line flag can be used +to force the update of an existing snapshot. -If the snapshot file does not exist, the snapshot is written. +```mjs +import assert from 'node:assert/strict'; -In case it is needed to force a snapshot update, -use [`--update-assert-snapshot`][]; +// Assuming that the application's main entrypoint is app.mjs, this reads the +// 'snapshotName' snapshot from app.snapshot and strictly compares its value +// to `util.inspect('value')`. +await assert.snapshot('value', 'snapshotName'); +``` -By default, a snapshot is read and written to a file, -using the same name as the main entrypoint with `.snapshot` as the extension. +```cjs +const assert = require('node:assert/strict'); + +(async () => { + // Assuming that the application's main entrypoint is app.js, this reads the + // 'snapshotName' snapshot from app.snapshot and strictly compares its value + // to `util.inspect('value')`. + await assert.snapshot('value', 'snapshotName'); +})(); +``` -### `assert.strictEqual(actual, expected[, message])` +### `assert.strictEqual(actual, expected[, message])` - + * `actual` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) * `expected` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) @@ -1875,7 +1891,7 @@ assert.strictEqual('Hello foobar', 'Hello World!'); const apples = 1; const oranges = 2; -assert.strictEqual(apples, oranges, `apples $apples !== oranges $oranges`); +assert.strictEqual(apples, oranges, `apples ${apples} !== oranges ${oranges}`); // AssertionError [ERR_ASSERTION]: apples 1 !== oranges 2 assert.strictEqual(1, '1', new TypeError('Inputs are not identical')); @@ -1903,7 +1919,7 @@ assert.strictEqual('Hello foobar', 'Hello World!'); const apples = 1; const oranges = 2; -assert.strictEqual(apples, oranges, `apples $apples !== oranges $oranges`); +assert.strictEqual(apples, oranges, `apples ${apples} !== oranges ${oranges}`); // AssertionError [ERR_ASSERTION]: apples 1 !== oranges 2 assert.strictEqual(1, '1', new TypeError('Inputs are not identical')); @@ -1916,9 +1932,9 @@ If the values are not strictly equal, an [`AssertionError`][] is thrown with a `message` parameter is an instance of an [`Error`][] then it will be thrown instead of the [`AssertionError`][]. -### `assert.throws(fn[, error][, message])` +### `assert.throws(fn[, error][, message])` - + * `fn` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) * `error` [`RegExp`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp) | [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) | [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) | [`Error`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error) diff --git a/content/api/v18/async_context.en.md b/content/api/v18/async_context.en.md index 0bd163f87e..714d20bb21 100644 --- a/content/api/v18/async_context.en.md +++ b/content/api/v18/async_context.en.md @@ -2,15 +2,15 @@ title: 'async_context' displayTitle: 'Asynchronous context tracking' category: 'api' -editPage: 'https://github.com/nodejs/node/blob/v18.8.0/doc/api/async_context.md' +editPage: 'https://github.com/nodejs/node/blob/v18.9.0/doc/api/async_context.md' version: 'v18' --- - + - + - + ### Introduction @@ -31,9 +31,9 @@ import { AsyncLocalStorage, AsyncResource } from 'node:async_hooks'; const { AsyncLocalStorage, AsyncResource } = require('node:async_hooks'); ``` -### `AsyncLocalStorage` +### `AsyncLocalStorage` - + This class creates stores that stay coherent through asynchronous operations. @@ -114,18 +114,18 @@ Each instance of `AsyncLocalStorage` maintains an independent storage context. Multiple instances can safely exist simultaneously without risk of interfering with each other's data. -#### `new AsyncLocalStorage()` +#### `new AsyncLocalStorage()` - + Creates a new instance of `AsyncLocalStorage`. Store is only provided within a `run()` call or after an `enterWith()` call. -#### `asyncLocalStorage.disable()` +#### `asyncLocalStorage.disable()` - + - + Disables the instance of `AsyncLocalStorage`. All subsequent calls to `asyncLocalStorage.getStore()` will return `undefined` until @@ -142,9 +142,9 @@ along with the corresponding async resources. Use this method when the `asyncLocalStorage` is not in use anymore in the current process. -#### `asyncLocalStorage.getStore()` +#### `asyncLocalStorage.getStore()` - + * Returns: [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) @@ -153,11 +153,11 @@ If called outside of an asynchronous context initialized by calling `asyncLocalStorage.run()` or `asyncLocalStorage.enterWith()`, it returns `undefined`. -#### `asyncLocalStorage.enterWith(store)` +#### `asyncLocalStorage.enterWith(store)` - + - + * `store` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) @@ -199,9 +199,9 @@ emitter.emit('my-event'); asyncLocalStorage.getStore(); // Returns the same object ``` -#### `asyncLocalStorage.run(store, callback[, ...args])` +#### `asyncLocalStorage.run(store, callback[, ...args])` - + * `store` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) * `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) @@ -235,11 +235,11 @@ try { } ``` -#### `asyncLocalStorage.exit(callback[, ...args])` +#### `asyncLocalStorage.exit(callback[, ...args])` - + - + * `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) * `...args` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) @@ -304,9 +304,9 @@ of `asyncLocalStorage.getStore()` after the calls you suspect are responsible for the loss. When the code logs `undefined`, the last callback called is probably responsible for the context loss. -### `AsyncResource` +### `AsyncResource` - + The class `AsyncResource` is designed to be extended by the embedder's async resources. Using this, users can easily trigger the lifetime events of their @@ -372,7 +372,7 @@ asyncResource.asyncId(); asyncResource.triggerAsyncId(); ``` -#### `new AsyncResource(type[, options])` +#### `new AsyncResource(type[, options])` * `type` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The type of async event. * `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) @@ -410,7 +410,7 @@ class DBQuery extends AsyncResource { #### Static method: `AsyncResource.bind(fn[, type[, thisArg]])` - + * `fn` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) The function to bind to the current execution context. * `type` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) An optional name to associate with the underlying @@ -422,9 +422,9 @@ Binds the given function to the current execution context. The returned function will have an `asyncResource` property referencing the `AsyncResource` to which the function is bound. -#### `asyncResource.bind(fn[, thisArg])` +#### `asyncResource.bind(fn[, thisArg])` - + * `fn` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) The function to bind to the current `AsyncResource`. * `thisArg` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) @@ -434,9 +434,9 @@ Binds the given function to execute to this `AsyncResource`'s scope. The returned function will have an `asyncResource` property referencing the `AsyncResource` to which the function is bound. -#### `asyncResource.runInAsyncScope(fn[, thisArg, ...args])` +#### `asyncResource.runInAsyncScope(fn[, thisArg, ...args])` - + * `fn` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) The function to call in the execution context of this async resource. @@ -448,7 +448,7 @@ of the async resource. This will establish the context, trigger the AsyncHooks before callbacks, call the function, trigger the AsyncHooks after callbacks, and then restore the original execution context. -#### `asyncResource.emitDestroy()` +#### `asyncResource.emitDestroy()` * Returns: [`AsyncResource`](/api/async_hooks#asyncresource) A reference to `asyncResource`. @@ -457,11 +457,11 @@ be thrown if it is called more than once. This **must** be manually called. If the resource is left to be collected by the GC then the `destroy` hooks will never be called. -#### `asyncResource.asyncId()` +#### `asyncResource.asyncId()` * Returns: [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The unique `asyncId` assigned to the resource. -#### `asyncResource.triggerAsyncId()` +#### `asyncResource.triggerAsyncId()` * Returns: [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The same `triggerAsyncId` that is passed to the `AsyncResource` constructor. diff --git a/content/api/v18/async_hooks.en.md b/content/api/v18/async_hooks.en.md index 41508f2d3f..18e5f7cb76 100644 --- a/content/api/v18/async_hooks.en.md +++ b/content/api/v18/async_hooks.en.md @@ -2,15 +2,15 @@ title: 'async_hooks' displayTitle: 'Async hooks' category: 'api' -editPage: 'https://github.com/nodejs/node/blob/v18.8.0/doc/api/async_hooks.md' +editPage: 'https://github.com/nodejs/node/blob/v18.9.0/doc/api/async_hooks.md' version: 'v18' --- - + - + - + The `node:async_hooks` module provides an API to track asynchronous resources. It can be accessed using: @@ -135,9 +135,9 @@ function destroy(asyncId) { } function promiseResolve(asyncId) { } ``` -### `async_hooks.createHook(callbacks)` +### `async_hooks.createHook(callbacks)` - + * `callbacks` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) The [Hook Callbacks][] to register * `init` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) The [`init` callback][]. @@ -249,12 +249,12 @@ provided by `AsyncHook` itself. The logging should then be skipped when it was the logging itself that caused the `AsyncHook` callback to be called. By doing this, the otherwise infinite recursion is broken. -### `AsyncHook` +### `AsyncHook` The class `AsyncHook` exposes an interface for tracking lifetime events of asynchronous operations. -#### `asyncHook.enable()` +#### `asyncHook.enable()` * Returns: [`AsyncHook`](/api/async_hooks#async_hookscreatehookcallbacks) A reference to `asyncHook`. @@ -276,7 +276,7 @@ const async_hooks = require('node:async_hooks'); const hook = async_hooks.createHook(callbacks).enable(); ``` -#### `asyncHook.disable()` +#### `asyncHook.disable()` * Returns: [`AsyncHook`](/api/async_hooks#async_hookscreatehookcallbacks) A reference to `asyncHook`. @@ -292,7 +292,7 @@ Key events in the lifetime of asynchronous events have been categorized into four areas: instantiation, before/after the callback is called, and when the instance is destroyed. -##### `init(asyncId, type, triggerAsyncId, resource)` +##### `init(asyncId, type, triggerAsyncId, resource)` * `asyncId` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) A unique ID for the async resource. * `type` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The type of the async resource. @@ -374,7 +374,7 @@ createHook({ const eid = executionAsyncId(); fs.writeSync( stdout.fd, - `$type($asyncId): trigger: $triggerAsyncId execution: $eid\n`); + `${type}(${asyncId}): trigger: ${triggerAsyncId} execution: ${eid}\n`); } }).enable(); @@ -391,7 +391,7 @@ createHook({ const eid = executionAsyncId(); fs.writeSync( stdout.fd, - `$type($asyncId): trigger: $triggerAsyncId execution: $eid\n`); + `${type}(${asyncId}): trigger: ${triggerAsyncId} execution: ${eid}\n`); } }).enable(); @@ -449,22 +449,22 @@ async_hooks.createHook({ const indentStr = ' '.repeat(indent); fs.writeSync( fd, - `$indentStr$type($asyncId):` + - ` trigger: $triggerAsyncId execution: $eid\n`); + `${indentStr}${type}(${asyncId}):` + + ` trigger: ${triggerAsyncId} execution: ${eid}\n`); }, before(asyncId) { const indentStr = ' '.repeat(indent); - fs.writeSync(fd, `$indentStrbefore: $asyncId\n`); + fs.writeSync(fd, `${indentStr}before: ${asyncId}\n`); indent += 2; }, after(asyncId) { indent -= 2; const indentStr = ' '.repeat(indent); - fs.writeSync(fd, `$indentStrafter: $asyncId\n`); + fs.writeSync(fd, `${indentStr}after: ${asyncId}\n`); }, destroy(asyncId) { const indentStr = ' '.repeat(indent); - fs.writeSync(fd, `$indentStrdestroy: $asyncId\n`); + fs.writeSync(fd, `${indentStr}destroy: ${asyncId}\n`); }, }).enable(); @@ -533,7 +533,7 @@ TCPSERVERWRAP(5) Timeout(7) ``` -##### `before(asyncId)` +##### `before(asyncId)` * `asyncId` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) @@ -550,7 +550,7 @@ asynchronous resources like a TCP server will typically call the `before` callback multiple times, while other operations like `fs.open()` will call it only once. -##### `after(asyncId)` +##### `after(asyncId)` * `asyncId` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) @@ -560,7 +560,7 @@ If an uncaught exception occurs during execution of the callback, then `after` will run _after_ the `'uncaughtException'` event is emitted or a `domain`'s handler runs. -##### `destroy(asyncId)` +##### `destroy(asyncId)` * `asyncId` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) @@ -572,9 +572,9 @@ made to the `resource` object passed to `init` it is possible that `destroy` will never be called, causing a memory leak in the application. If the resource does not depend on garbage collection, then this will not be an issue. -##### `promiseResolve(asyncId)` +##### `promiseResolve(asyncId)` - + * `asyncId` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) @@ -601,9 +601,9 @@ init for PROMISE with id 6, trigger id: 5 # the Promise returned by then() after 6 ``` -#### `async_hooks.executionAsyncResource()` +#### `async_hooks.executionAsyncResource()` - + * Returns: [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) The resource representing the current execution. Useful to store data within the resource. @@ -691,9 +691,9 @@ const server = createServer((req, res) => { }).listen(3000); ``` -#### `async_hooks.executionAsyncId()` +#### `async_hooks.executionAsyncId()` - + * Returns: [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The `asyncId` of the current execution context. Useful to track when something calls. @@ -735,7 +735,7 @@ const server = net.createServer((conn) => { Promise contexts may not get precise `executionAsyncIds` by default. See the section on [promise execution tracking][]. -#### `async_hooks.triggerAsyncId()` +#### `async_hooks.triggerAsyncId()` * Returns: [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The ID of the resource responsible for calling the callback that is currently being executed. @@ -758,9 +758,9 @@ const server = net.createServer((conn) => { Promise contexts may not get valid `triggerAsyncId`s by default. See the section on [promise execution tracking][]. -#### `async_hooks.asyncWrapProviders` +#### `async_hooks.asyncWrapProviders` - + * Returns: A map of provider types to the corresponding numeric id. This map contains all the event types that might be emitted by the `async_hooks.init()` event. @@ -843,11 +843,11 @@ Library developers that handle their own asynchronous resources performing tasks like I/O, connection pooling, or managing callback queues may use the `AsyncResource` JavaScript API so that all the appropriate callbacks are called. -#### `AsyncResource` +#### `AsyncResource` The documentation for this class has moved [`AsyncResource`][]. -### `AsyncLocalStorage` +### `AsyncLocalStorage` The documentation for this class has moved [`AsyncLocalStorage`][]. diff --git a/content/api/v18/buffer.en.md b/content/api/v18/buffer.en.md index 1a6dec5bff..633c2991e7 100644 --- a/content/api/v18/buffer.en.md +++ b/content/api/v18/buffer.en.md @@ -2,15 +2,15 @@ title: 'buffer' displayTitle: 'Buffer' category: 'api' -editPage: 'https://github.com/nodejs/node/blob/v18.8.0/doc/api/buffer.md' +editPage: 'https://github.com/nodejs/node/blob/v18.9.0/doc/api/buffer.md' version: 'v18' --- - + - + - + `Buffer` objects are used to represent a fixed-length sequence of bytes. Many Node.js APIs support `Buffer`s. @@ -90,7 +90,7 @@ const buf7 = Buffer.from('tést', 'latin1'); ### Buffers and character encodings - + When converting between `Buffer`s and strings, a character encoding may be specified. If no character encoding is specified, UTF-8 will be used as the @@ -228,7 +228,7 @@ the characters. ### Buffers and TypedArrays - + `Buffer` instances are also JavaScript [`Uint8Array`][] and [`TypedArray`][] instances. All [`TypedArray`][] methods are available on `Buffer`s. There are, @@ -438,16 +438,16 @@ for (const b of buf) { Additionally, the [`buf.values()`][], [`buf.keys()`][], and [`buf.entries()`][] methods can be used to create iterators. -### `Blob` +### `Blob` - + A [`Blob`][] encapsulates immutable, raw data that can be safely shared across multiple worker threads. -#### `new buffer.Blob([sources[, options]])` +#### `new buffer.Blob([sources[, options]])` - + * `sources` string\[]|ArrayBuffer\[]|TypedArray\[]|DataView\[]|Blob\[] An array of string, [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer), [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray), [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView), or [`Blob`](/api/buffer#blob) objects, @@ -469,24 +469,24 @@ String sources are encoded as UTF-8 byte sequences and copied into the Blob. Unmatched surrogate pairs within each string part will be replaced by Unicode U+FFFD replacement characters. -#### `blob.arrayBuffer()` +#### `blob.arrayBuffer()` - + * Returns: [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) Returns a promise that fulfills with an [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) containing a copy of the `Blob` data. -#### `blob.size` +#### `blob.size` - + The total size of the `Blob` in bytes. -#### `blob.slice([start[, end[, type]]])` +#### `blob.slice([start[, end[, type]]])` - + * `start` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The starting index. * `end` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The ending index. @@ -495,32 +495,32 @@ The total size of the `Blob` in bytes. Creates and returns a new `Blob` containing a subset of this `Blob` objects data. The original `Blob` is not altered. -#### `blob.stream()` +#### `blob.stream()` - + * Returns: [`ReadableStream`](/api/webstreams#readablestream) Returns a new `ReadableStream` that allows the content of the `Blob` to be read. -#### `blob.text()` +#### `blob.text()` - + * Returns: [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) Returns a promise that fulfills with the contents of the `Blob` decoded as a UTF-8 string. -#### `blob.type` +#### `blob.type` - + * Type: [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The content-type of the `Blob`. -#### `Blob` objects and `MessageChannel` +#### `Blob` objects and `MessageChannel` Once a [`Blob`](/api/buffer#blob) object is created, it can be sent via `MessagePort` to multiple destinations without transferring or immediately copying the data. The data @@ -581,17 +581,17 @@ mc2.port2.postMessage(blob); blob.text().then(console.log); ``` -### `Buffer` +### `Buffer` The `Buffer` class is a global type for dealing with binary data directly. It can be constructed in a variety of ways. #### Static method: `Buffer.alloc(size[, fill[, encoding]])` - + * `size` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The desired length of the new `Buffer`. -* `fill` {string|Buffer|Uint8Array|integer} A value to pre-fill the new `Buffer` +* `fill` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`Uint8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array) | [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) A value to pre-fill the new `Buffer` with. **Default:** `0`. * `encoding` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) If `fill` is a string, this is its encoding. **Default:** `'utf8'`. @@ -672,7 +672,7 @@ A `TypeError` will be thrown if `size` is not a number. #### Static method: `Buffer.allocUnsafe(size)` - + * `size` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The desired length of the new `Buffer`. @@ -732,7 +732,7 @@ additional performance that [`Buffer.allocUnsafe()`][] provides. #### Static method: `Buffer.allocUnsafeSlow(size)` - + * `size` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The desired length of the new `Buffer`. @@ -801,7 +801,7 @@ A `TypeError` will be thrown if `size` is not a number. #### Static method: `Buffer.byteLength(string[, encoding])` - + * `string` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) | [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) | [`SharedArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer) A value to calculate the length of. @@ -823,7 +823,7 @@ import { Buffer } from 'node:buffer'; const str = '\u00bd + \u00bc = \u00be'; -console.log(`$str: $str.length characters, ` + +console.log(`${str}: ${str.length} characters, ` + `${Buffer.byteLength(str, 'utf8')} bytes`); // Prints: ½ + ¼ = ¾: 9 characters, 12 bytes ``` @@ -833,7 +833,7 @@ const { Buffer } = require('node:buffer'); const str = '\u00bd + \u00bc = \u00be'; -console.log(`$str: $str.length characters, ` + +console.log(`${str}: ${str.length} characters, ` + `${Buffer.byteLength(str, 'utf8')} bytes`); // Prints: ½ + ¼ = ¾: 9 characters, 12 bytes ``` @@ -844,10 +844,10 @@ is returned. #### Static method: `Buffer.compare(buf1, buf2)` - + -* `buf1` {Buffer|Uint8Array} -* `buf2` {Buffer|Uint8Array} +* `buf1` [`Buffer`](/api/buffer#buffer) | [`Uint8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array) +* `buf2` [`Buffer`](/api/buffer#buffer) | [`Uint8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array) * Returns: [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Either `-1`, `0`, or `1`, depending on the result of the comparison. See [`buf.compare()`][] for details. @@ -881,9 +881,9 @@ console.log(arr.sort(Buffer.compare)); #### Static method: `Buffer.concat(list[, totalLength])` - + -* `list` {Buffer\[] | Uint8Array\[]} List of `Buffer` or [`Uint8Array`][] +* `list` Buffer\[] | Uint8Array\[] List of `Buffer` or [`Uint8Array`][] instances to concatenate. * `totalLength` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Total length of the `Buffer` instances in `list` when concatenated. @@ -949,7 +949,7 @@ console.log(bufA.length); #### Static method: `Buffer.from(array)` - + * `array` integer\[] @@ -978,7 +978,7 @@ appropriate for `Buffer.from()` variants. #### Static method: `Buffer.from(arrayBuffer[, byteOffset[, length]])` - + * `arrayBuffer` [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) | [`SharedArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer) An [`ArrayBuffer`][], [`SharedArrayBuffer`][], for example the `.buffer` property of a @@ -1092,9 +1092,9 @@ console.log(buf); #### Static method: `Buffer.from(buffer)` - + -* `buffer` {Buffer|Uint8Array} An existing `Buffer` or [`Uint8Array`][] from +* `buffer` [`Buffer`](/api/buffer#buffer) | [`Uint8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array) An existing `Buffer` or [`Uint8Array`][] from which to copy data. Copies the passed `buffer` data onto a new `Buffer` instance. @@ -1132,7 +1132,7 @@ appropriate for `Buffer.from()` variants. #### Static method: `Buffer.from(object[, offsetOrEncoding[, length]])` - + * `object` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) An object supporting `Symbol.toPrimitive` or `valueOf()`. * `offsetOrEncoding` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) A byte-offset or encoding. @@ -1189,7 +1189,7 @@ is not of another type appropriate for `Buffer.from()` variants. #### Static method: `Buffer.from(string[, encoding])` - + * `string` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) A string to encode. * `encoding` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The encoding of `string`. **Default:** `'utf8'`. @@ -1230,7 +1230,7 @@ appropriate for `Buffer.from()` variants. #### Static method: `Buffer.isBuffer(obj)` - + * `obj` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) * Returns: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) @@ -1259,7 +1259,7 @@ Buffer.isBuffer(new Uint8Array(1024)); // false #### Static method: `Buffer.isEncoding(encoding)` - + * `encoding` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) A character encoding name to check. * Returns: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) @@ -1301,14 +1301,14 @@ console.log(Buffer.isEncoding('')); #### Class property: `Buffer.poolSize` - + * [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) **Default:** `8192` This is the size (in bytes) of pre-allocated internal `Buffer` instances used for pooling. This value may be modified. -#### `buf[index]` +#### `buf[index]` * `index` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) @@ -1358,7 +1358,7 @@ console.log(buf.toString('utf8')); // Prints: Node.js ``` -#### `buf.buffer` +#### `buf.buffer` * [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) The underlying `ArrayBuffer` object based on which this `Buffer` object is created. @@ -1386,7 +1386,7 @@ console.log(buffer.buffer === arrayBuffer); // Prints: true ``` -#### `buf.byteOffset` +#### `buf.byteOffset` * [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The `byteOffset` of the `Buffer`s underlying `ArrayBuffer` object. @@ -1425,11 +1425,11 @@ const nodeBuffer = Buffer.from([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]); new Int8Array(nodeBuffer.buffer, nodeBuffer.byteOffset, nodeBuffer.length); ``` -#### `buf.compare(target[, targetStart[, targetEnd[, sourceStart[, sourceEnd]]]])` +#### `buf.compare(target[, targetStart[, targetEnd[, sourceStart[, sourceEnd]]]])` - + -* `target` {Buffer|Uint8Array} A `Buffer` or [`Uint8Array`][] with which to +* `target` [`Buffer`](/api/buffer#buffer) | [`Uint8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array) A `Buffer` or [`Uint8Array`][] with which to compare `buf`. * `targetStart` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The offset within `target` at which to begin comparison. **Default:** `0`. @@ -1528,11 +1528,11 @@ console.log(buf1.compare(buf2, 5, 6, 5)); [`ERR_OUT_OF_RANGE`][] is thrown if `targetStart < 0`, `sourceStart < 0`, `targetEnd > target.byteLength`, or `sourceEnd > source.byteLength`. -#### `buf.copy(target[, targetStart[, sourceStart[, sourceEnd]]])` +#### `buf.copy(target[, targetStart[, sourceStart[, sourceEnd]]])` - + -* `target` {Buffer|Uint8Array} A `Buffer` or [`Uint8Array`][] to copy into. +* `target` [`Buffer`](/api/buffer#buffer) | [`Uint8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array) A `Buffer` or [`Uint8Array`][] to copy into. * `targetStart` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The offset within `target` at which to begin writing. **Default:** `0`. * `sourceStart` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The offset within `buf` from which to begin copying. @@ -1628,9 +1628,9 @@ console.log(buf.toString()); // Prints: efghijghijklmnopqrstuvwxyz ``` -#### `buf.entries()` +#### `buf.entries()` - + * Returns: [`Iterator`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#The_iterator_protocol) @@ -1675,11 +1675,11 @@ for (const pair of buf.entries()) { // [5, 114] ``` -#### `buf.equals(otherBuffer)` +#### `buf.equals(otherBuffer)` - + -* `otherBuffer` {Buffer|Uint8Array} A `Buffer` or [`Uint8Array`][] with which to +* `otherBuffer` [`Buffer`](/api/buffer#buffer) | [`Uint8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array) A `Buffer` or [`Uint8Array`][] with which to compare `buf`. * Returns: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) @@ -1713,11 +1713,11 @@ console.log(buf1.equals(buf3)); // Prints: false ``` -#### `buf.fill(value[, offset[, end]][, encoding])` +#### `buf.fill(value[, offset[, end]][, encoding])` - + -* `value` {string|Buffer|Uint8Array|integer} The value with which to fill `buf`. +* `value` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`Uint8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array) | [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The value with which to fill `buf`. * `offset` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number of bytes to skip before starting to fill `buf`. **Default:** `0`. * `end` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Where to stop filling `buf` (not inclusive). **Default:** @@ -1805,11 +1805,11 @@ console.log(buf.fill('zz', 'hex')); // Throws an exception. ``` -#### `buf.includes(value[, byteOffset][, encoding])` +#### `buf.includes(value[, byteOffset][, encoding])` - + -* `value` {string|Buffer|Uint8Array|integer} What to search for. +* `value` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`Uint8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array) | [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) What to search for. * `byteOffset` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Where to begin searching in `buf`. If negative, then offset is calculated from the end of `buf`. **Default:** `0`. * `encoding` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) If `value` is a string, this is its encoding. @@ -1860,11 +1860,11 @@ console.log(buf.includes('this', 4)); // Prints: false ``` -#### `buf.indexOf(value[, byteOffset][, encoding])` +#### `buf.indexOf(value[, byteOffset][, encoding])` - + -* `value` {string|Buffer|Uint8Array|integer} What to search for. +* `value` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`Uint8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array) | [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) What to search for. * `byteOffset` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Where to begin searching in `buf`. If negative, then offset is calculated from the end of `buf`. **Default:** `0`. * `encoding` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) If `value` is a string, this is the encoding used to @@ -1982,9 +1982,9 @@ If `value` is an empty string or empty `Buffer` and `byteOffset` is less than `buf.length`, `byteOffset` will be returned. If `value` is empty and `byteOffset` is at least `buf.length`, `buf.length` will be returned. -#### `buf.keys()` +#### `buf.keys()` - + * Returns: [`Iterator`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#The_iterator_protocol) @@ -2024,11 +2024,11 @@ for (const key of buf.keys()) { // 5 ``` -#### `buf.lastIndexOf(value[, byteOffset][, encoding])` +#### `buf.lastIndexOf(value[, byteOffset][, encoding])` - + -* `value` {string|Buffer|Uint8Array|integer} What to search for. +* `value` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`Uint8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array) | [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) What to search for. * `byteOffset` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Where to begin searching in `buf`. If negative, then offset is calculated from the end of `buf`. **Default:** `buf.length - 1`. @@ -2149,9 +2149,9 @@ console.log(b.lastIndexOf('b', [])); If `value` is an empty string or empty `Buffer`, `byteOffset` will be returned. -#### `buf.length` +#### `buf.length` - + * [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) @@ -2189,17 +2189,17 @@ console.log(buf.length); // Prints: 1234 ``` -#### `buf.parent` +#### `buf.parent` - + - + The `buf.parent` property is a deprecated alias for `buf.buffer`. -#### `buf.readBigInt64BE([offset])` +#### `buf.readBigInt64BE([offset])` - + * `offset` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number of bytes to skip before starting to read. Must satisfy: `0 <= offset <= buf.length - 8`. **Default:** `0`. @@ -2210,9 +2210,9 @@ Reads a signed, big-endian 64-bit integer from `buf` at the specified `offset`. Integers read from a `Buffer` are interpreted as two's complement signed values. -#### `buf.readBigInt64LE([offset])` +#### `buf.readBigInt64LE([offset])` - + * `offset` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number of bytes to skip before starting to read. Must satisfy: `0 <= offset <= buf.length - 8`. **Default:** `0`. @@ -2224,9 +2224,9 @@ Reads a signed, little-endian 64-bit integer from `buf` at the specified Integers read from a `Buffer` are interpreted as two's complement signed values. -#### `buf.readBigUInt64BE([offset])` +#### `buf.readBigUInt64BE([offset])` - + * `offset` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number of bytes to skip before starting to read. Must satisfy: `0 <= offset <= buf.length - 8`. **Default:** `0`. @@ -2255,9 +2255,9 @@ console.log(buf.readBigUInt64BE(0)); // Prints: 4294967295n ``` -#### `buf.readBigUInt64LE([offset])` +#### `buf.readBigUInt64LE([offset])` - + * `offset` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number of bytes to skip before starting to read. Must satisfy: `0 <= offset <= buf.length - 8`. **Default:** `0`. @@ -2286,9 +2286,9 @@ console.log(buf.readBigUInt64LE(0)); // Prints: 18446744069414584320n ``` -#### `buf.readDoubleBE([offset])` +#### `buf.readDoubleBE([offset])` - + * `offset` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 8`. **Default:** `0`. @@ -2314,9 +2314,9 @@ console.log(buf.readDoubleBE(0)); // Prints: 8.20788039913184e-304 ``` -#### `buf.readDoubleLE([offset])` +#### `buf.readDoubleLE([offset])` - + * `offset` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 8`. **Default:** `0`. @@ -2346,9 +2346,9 @@ console.log(buf.readDoubleLE(1)); // Throws ERR_OUT_OF_RANGE. ``` -#### `buf.readFloatBE([offset])` +#### `buf.readFloatBE([offset])` - + * `offset` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 4`. **Default:** `0`. @@ -2374,9 +2374,9 @@ console.log(buf.readFloatBE(0)); // Prints: 2.387939260590663e-38 ``` -#### `buf.readFloatLE([offset])` +#### `buf.readFloatLE([offset])` - + * `offset` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 4`. **Default:** `0`. @@ -2406,9 +2406,9 @@ console.log(buf.readFloatLE(1)); // Throws ERR_OUT_OF_RANGE. ``` -#### `buf.readInt8([offset])` +#### `buf.readInt8([offset])` - + * `offset` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 1`. **Default:** `0`. @@ -2444,9 +2444,9 @@ console.log(buf.readInt8(2)); // Throws ERR_OUT_OF_RANGE. ``` -#### `buf.readInt16BE([offset])` +#### `buf.readInt16BE([offset])` - + * `offset` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 2`. **Default:** `0`. @@ -2474,9 +2474,9 @@ console.log(buf.readInt16BE(0)); // Prints: 5 ``` -#### `buf.readInt16LE([offset])` +#### `buf.readInt16LE([offset])` - + * `offset` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 2`. **Default:** `0`. @@ -2509,9 +2509,9 @@ console.log(buf.readInt16LE(1)); // Throws ERR_OUT_OF_RANGE. ``` -#### `buf.readInt32BE([offset])` +#### `buf.readInt32BE([offset])` - + * `offset` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 4`. **Default:** `0`. @@ -2539,9 +2539,9 @@ console.log(buf.readInt32BE(0)); // Prints: 5 ``` -#### `buf.readInt32LE([offset])` +#### `buf.readInt32LE([offset])` - + * `offset` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 4`. **Default:** `0`. @@ -2574,9 +2574,9 @@ console.log(buf.readInt32LE(1)); // Throws ERR_OUT_OF_RANGE. ``` -#### `buf.readIntBE(offset, byteLength)` +#### `buf.readIntBE(offset, byteLength)` - + * `offset` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - byteLength`. @@ -2614,9 +2614,9 @@ console.log(buf.readIntBE(1, 0).toString(16)); // Throws ERR_OUT_OF_RANGE. ``` -#### `buf.readIntLE(offset, byteLength)` +#### `buf.readIntLE(offset, byteLength)` - + * `offset` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - byteLength`. @@ -2646,9 +2646,9 @@ console.log(buf.readIntLE(0, 6).toString(16)); // Prints: -546f87a9cbee ``` -#### `buf.readUInt8([offset])` +#### `buf.readUInt8([offset])` - + * `offset` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 1`. **Default:** `0`. @@ -2684,9 +2684,9 @@ console.log(buf.readUInt8(2)); // Throws ERR_OUT_OF_RANGE. ``` -#### `buf.readUInt16BE([offset])` +#### `buf.readUInt16BE([offset])` - + * `offset` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 2`. **Default:** `0`. @@ -2719,9 +2719,9 @@ console.log(buf.readUInt16BE(1).toString(16)); // Prints: 3456 ``` -#### `buf.readUInt16LE([offset])` +#### `buf.readUInt16LE([offset])` - + * `offset` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 2`. **Default:** `0`. @@ -2758,9 +2758,9 @@ console.log(buf.readUInt16LE(2).toString(16)); // Throws ERR_OUT_OF_RANGE. ``` -#### `buf.readUInt32BE([offset])` +#### `buf.readUInt32BE([offset])` - + * `offset` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 4`. **Default:** `0`. @@ -2789,9 +2789,9 @@ console.log(buf.readUInt32BE(0).toString(16)); // Prints: 12345678 ``` -#### `buf.readUInt32LE([offset])` +#### `buf.readUInt32LE([offset])` - + * `offset` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 4`. **Default:** `0`. @@ -2824,9 +2824,9 @@ console.log(buf.readUInt32LE(1).toString(16)); // Throws ERR_OUT_OF_RANGE. ``` -#### `buf.readUIntBE(offset, byteLength)` +#### `buf.readUIntBE(offset, byteLength)` - + * `offset` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - byteLength`. @@ -2862,9 +2862,9 @@ console.log(buf.readUIntBE(1, 6).toString(16)); // Throws ERR_OUT_OF_RANGE. ``` -#### `buf.readUIntLE(offset, byteLength)` +#### `buf.readUIntLE(offset, byteLength)` - + * `offset` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - byteLength`. @@ -2896,9 +2896,9 @@ console.log(buf.readUIntLE(0, 6).toString(16)); // Prints: ab9078563412 ``` -#### `buf.subarray([start[, end]])` +#### `buf.subarray([start[, end]])` - + * `start` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Where the new `Buffer` will start. **Default:** `0`. * `end` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Where the new `Buffer` will end (not inclusive). @@ -3003,16 +3003,16 @@ console.log(buf.subarray(-5, -2).toString()); // (Equivalent to buf.subarray(1, 4).) ``` -#### `buf.slice([start[, end]])` +#### `buf.slice([start[, end]])` - + * `start` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Where the new `Buffer` will start. **Default:** `0`. * `end` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Where the new `Buffer` will end (not inclusive). **Default:** [`buf.length`][]. * Returns: [`Buffer`](/api/buffer#buffer) - + Returns a new `Buffer` that references the same memory as the original, but offset and cropped by the `start` and `end` indices. @@ -3065,9 +3065,9 @@ console.log(buf.toString()); // Also prints: cuffer (!) ``` -#### `buf.swap16()` +#### `buf.swap16()` - + * Returns: [`Buffer`](/api/buffer#buffer) A reference to `buf`. @@ -3130,9 +3130,9 @@ const buf = Buffer.from('This is little-endian UTF-16', 'utf16le'); buf.swap16(); // Convert to big-endian UTF-16 text. ``` -#### `buf.swap32()` +#### `buf.swap32()` - + * Returns: [`Buffer`](/api/buffer#buffer) A reference to `buf`. @@ -3178,9 +3178,9 @@ buf2.swap32(); // Throws ERR_INVALID_BUFFER_SIZE. ``` -#### `buf.swap64()` +#### `buf.swap64()` - + * Returns: [`Buffer`](/api/buffer#buffer) A reference to `buf`. @@ -3225,9 +3225,9 @@ buf2.swap64(); // Throws ERR_INVALID_BUFFER_SIZE. ``` -#### `buf.toJSON()` +#### `buf.toJSON()` - + * Returns: [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) @@ -3275,9 +3275,9 @@ console.log(copy); // Prints: ``` -#### `buf.toString([encoding[, start[, end]]])` +#### `buf.toString([encoding[, start[, end]]])` - + * `encoding` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The character encoding to use. **Default:** `'utf8'`. * `start` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The byte offset to start decoding at. **Default:** `0`. @@ -3344,9 +3344,9 @@ console.log(buf2.toString(undefined, 0, 3)); // Prints: té ``` -#### `buf.values()` +#### `buf.values()` - + * Returns: [`Iterator`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#The_iterator_protocol) @@ -3409,9 +3409,9 @@ for (const value of buf) { // 114 ``` -#### `buf.write(string[, offset[, length]][, encoding])` +#### `buf.write(string[, offset[, length]][, encoding])` - + * `string` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) String to write to `buf`. * `offset` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number of bytes to skip before starting to write `string`. @@ -3433,14 +3433,14 @@ const buf = Buffer.alloc(256); const len = buf.write('\u00bd + \u00bc = \u00be', 0); -console.log(`$len bytes: ${buf.toString('utf8', 0, len)}`); +console.log(`${len} bytes: ${buf.toString('utf8', 0, len)}`); // Prints: 12 bytes: ½ + ¼ = ¾ const buffer = Buffer.alloc(10); const length = buffer.write('abcd', 8); -console.log(`$length bytes: ${buffer.toString('utf8', 8, 10)}`); +console.log(`${length} bytes: ${buffer.toString('utf8', 8, 10)}`); // Prints: 2 bytes : ab ``` @@ -3451,20 +3451,20 @@ const buf = Buffer.alloc(256); const len = buf.write('\u00bd + \u00bc = \u00be', 0); -console.log(`$len bytes: ${buf.toString('utf8', 0, len)}`); +console.log(`${len} bytes: ${buf.toString('utf8', 0, len)}`); // Prints: 12 bytes: ½ + ¼ = ¾ const buffer = Buffer.alloc(10); const length = buffer.write('abcd', 8); -console.log(`$length bytes: ${buffer.toString('utf8', 8, 10)}`); +console.log(`${length} bytes: ${buffer.toString('utf8', 8, 10)}`); // Prints: 2 bytes : ab ``` -#### `buf.writeBigInt64BE(value[, offset])` +#### `buf.writeBigInt64BE(value[, offset])` - + * `value` [`bigint`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt) Number to be written to `buf`. * `offset` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number of bytes to skip before starting to write. Must @@ -3497,9 +3497,9 @@ console.log(buf); // Prints: ``` -#### `buf.writeBigInt64LE(value[, offset])` +#### `buf.writeBigInt64LE(value[, offset])` - + * `value` [`bigint`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt) Number to be written to `buf`. * `offset` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number of bytes to skip before starting to write. Must @@ -3532,9 +3532,9 @@ console.log(buf); // Prints: ``` -#### `buf.writeBigUInt64BE(value[, offset])` +#### `buf.writeBigUInt64BE(value[, offset])` - + * `value` [`bigint`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt) Number to be written to `buf`. * `offset` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number of bytes to skip before starting to write. Must @@ -3567,9 +3567,9 @@ console.log(buf); // Prints: ``` -#### `buf.writeBigUInt64LE(value[, offset])` +#### `buf.writeBigUInt64LE(value[, offset])` - + * `value` [`bigint`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt) Number to be written to `buf`. * `offset` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number of bytes to skip before starting to write. Must @@ -3602,9 +3602,9 @@ console.log(buf); This function is also available under the `writeBigUint64LE` alias. -#### `buf.writeDoubleBE(value[, offset])` +#### `buf.writeDoubleBE(value[, offset])` - + * `value` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number to be written to `buf`. * `offset` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number of bytes to skip before starting to write. Must @@ -3637,9 +3637,9 @@ console.log(buf); // Prints: ``` -#### `buf.writeDoubleLE(value[, offset])` +#### `buf.writeDoubleLE(value[, offset])` - + * `value` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number to be written to `buf`. * `offset` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number of bytes to skip before starting to write. Must @@ -3672,9 +3672,9 @@ console.log(buf); // Prints: ``` -#### `buf.writeFloatBE(value[, offset])` +#### `buf.writeFloatBE(value[, offset])` - + * `value` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number to be written to `buf`. * `offset` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number of bytes to skip before starting to write. Must @@ -3706,9 +3706,9 @@ console.log(buf); // Prints: ``` -#### `buf.writeFloatLE(value[, offset])` +#### `buf.writeFloatLE(value[, offset])` - + * `value` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number to be written to `buf`. * `offset` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number of bytes to skip before starting to write. Must @@ -3740,9 +3740,9 @@ console.log(buf); // Prints: ``` -#### `buf.writeInt8(value[, offset])` +#### `buf.writeInt8(value[, offset])` - + * `value` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number to be written to `buf`. * `offset` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number of bytes to skip before starting to write. Must @@ -3779,9 +3779,9 @@ console.log(buf); // Prints: ``` -#### `buf.writeInt16BE(value[, offset])` +#### `buf.writeInt16BE(value[, offset])` - + * `value` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number to be written to `buf`. * `offset` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number of bytes to skip before starting to write. Must @@ -3816,9 +3816,9 @@ console.log(buf); // Prints: ``` -#### `buf.writeInt16LE(value[, offset])` +#### `buf.writeInt16LE(value[, offset])` - + * `value` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number to be written to `buf`. * `offset` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number of bytes to skip before starting to write. Must @@ -3853,9 +3853,9 @@ console.log(buf); // Prints: ``` -#### `buf.writeInt32BE(value[, offset])` +#### `buf.writeInt32BE(value[, offset])` - + * `value` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number to be written to `buf`. * `offset` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number of bytes to skip before starting to write. Must @@ -3890,9 +3890,9 @@ console.log(buf); // Prints: ``` -#### `buf.writeInt32LE(value[, offset])` +#### `buf.writeInt32LE(value[, offset])` - + * `value` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number to be written to `buf`. * `offset` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number of bytes to skip before starting to write. Must @@ -3927,9 +3927,9 @@ console.log(buf); // Prints: ``` -#### `buf.writeIntBE(value, offset, byteLength)` +#### `buf.writeIntBE(value, offset, byteLength)` - + * `value` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number to be written to `buf`. * `offset` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number of bytes to skip before starting to write. Must @@ -3964,9 +3964,9 @@ console.log(buf); // Prints: ``` -#### `buf.writeIntLE(value, offset, byteLength)` +#### `buf.writeIntLE(value, offset, byteLength)` - + * `value` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number to be written to `buf`. * `offset` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number of bytes to skip before starting to write. Must @@ -4001,9 +4001,9 @@ console.log(buf); // Prints: ``` -#### `buf.writeUInt8(value[, offset])` +#### `buf.writeUInt8(value[, offset])` - + * `value` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number to be written to `buf`. * `offset` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number of bytes to skip before starting to write. Must @@ -4044,9 +4044,9 @@ console.log(buf); // Prints: ``` -#### `buf.writeUInt16BE(value[, offset])` +#### `buf.writeUInt16BE(value[, offset])` - + * `value` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number to be written to `buf`. * `offset` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number of bytes to skip before starting to write. Must @@ -4083,9 +4083,9 @@ console.log(buf); // Prints: ``` -#### `buf.writeUInt16LE(value[, offset])` +#### `buf.writeUInt16LE(value[, offset])` - + * `value` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number to be written to `buf`. * `offset` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number of bytes to skip before starting to write. Must @@ -4122,9 +4122,9 @@ console.log(buf); // Prints: ``` -#### `buf.writeUInt32BE(value[, offset])` +#### `buf.writeUInt32BE(value[, offset])` - + * `value` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number to be written to `buf`. * `offset` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number of bytes to skip before starting to write. Must @@ -4159,9 +4159,9 @@ console.log(buf); // Prints: ``` -#### `buf.writeUInt32LE(value[, offset])` +#### `buf.writeUInt32LE(value[, offset])` - + * `value` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number to be written to `buf`. * `offset` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number of bytes to skip before starting to write. Must @@ -4196,9 +4196,9 @@ console.log(buf); // Prints: ``` -#### `buf.writeUIntBE(value, offset, byteLength)` +#### `buf.writeUIntBE(value, offset, byteLength)` - + * `value` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number to be written to `buf`. * `offset` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number of bytes to skip before starting to write. Must @@ -4235,9 +4235,9 @@ console.log(buf); // Prints: ``` -#### `buf.writeUIntLE(value, offset, byteLength)` +#### `buf.writeUIntLE(value, offset, byteLength)` - + * `value` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number to be written to `buf`. * `offset` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number of bytes to skip before starting to write. Must @@ -4274,21 +4274,21 @@ console.log(buf); // Prints: ``` -#### `new Buffer(array)` +#### `new Buffer(array)` - + - + * `array` integer\[] An array of bytes to copy from. See [`Buffer.from(array)`][]. -#### `new Buffer(arrayBuffer[, byteOffset[, length]])` +#### `new Buffer(arrayBuffer[, byteOffset[, length]])` - + - [`Buffer.from(arrayBuffer[, byteOffset[, length]])`][`Buffer.from(arrayBuf)`]\n> instead."}}} /> + instead."}}} /> * `arrayBuffer` [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) | [`SharedArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer) An [`ArrayBuffer`][], [`SharedArrayBuffer`][] or the `.buffer` property of a [`TypedArray`][]. @@ -4299,50 +4299,50 @@ See [`Buffer.from(array)`][]. See [`Buffer.from(arrayBuffer[, byteOffset[, length]])`][`Buffer.from(arrayBuf)`]. -#### `new Buffer(buffer)` +#### `new Buffer(buffer)` - + - + -* `buffer` {Buffer|Uint8Array} An existing `Buffer` or [`Uint8Array`][] from +* `buffer` [`Buffer`](/api/buffer#buffer) | [`Uint8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array) An existing `Buffer` or [`Uint8Array`][] from which to copy data. See [`Buffer.from(buffer)`][]. -#### `new Buffer(size)` +#### `new Buffer(size)` - + - [`Buffer.allocUnsafe()`][])."}}} /> + * `size` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The desired length of the new `Buffer`. See [`Buffer.alloc()`][] and [`Buffer.allocUnsafe()`][]. This variant of the constructor is equivalent to [`Buffer.alloc()`][]. -#### `new Buffer(string[, encoding])` +#### `new Buffer(string[, encoding])` - + - Use [`Buffer.from(string[, encoding])`][`Buffer.from(string)`] instead."}}} /> + * `string` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) String to encode. * `encoding` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The encoding of `string`. **Default:** `'utf8'`. See [`Buffer.from(string[, encoding])`][`Buffer.from(string)`]. -### `node:buffer` module APIs +### `node:buffer` module APIs While, the `Buffer` object is available as a global, there are additional `Buffer`-related APIs that are available only via the `node:buffer` module accessed using `require('node:buffer')`. -#### `buffer.atob(data)` +#### `buffer.atob(data)` - + - + * `data` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) The Base64-encoded input string. @@ -4358,11 +4358,11 @@ For code running using Node.js APIs, converting between base64-encoded strings and binary data should be performed using `Buffer.from(str, 'base64')` and `buf.toString('base64')`.** -#### `buffer.btoa(data)` +#### `buffer.btoa(data)` - + - + * `data` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) An ASCII (Latin1) string. @@ -4378,9 +4378,9 @@ For code running using Node.js APIs, converting between base64-encoded strings and binary data should be performed using `Buffer.from(str, 'base64')` and `buf.toString('base64')`.** -#### `buffer.INSPECT_MAX_BYTES` +#### `buffer.INSPECT_MAX_BYTES` - + * [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) **Default:** `50` @@ -4388,27 +4388,27 @@ Returns the maximum number of bytes that will be returned when `buf.inspect()` is called. This can be overridden by user modules. See [`util.inspect()`][] for more details on `buf.inspect()` behavior. -#### `buffer.kMaxLength` +#### `buffer.kMaxLength` - + * [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The largest size allowed for a single `Buffer` instance. An alias for [`buffer.constants.MAX_LENGTH`][]. -#### `buffer.kStringMaxLength` +#### `buffer.kStringMaxLength` - + * [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The largest length allowed for a single `string` instance. An alias for [`buffer.constants.MAX_STRING_LENGTH`][]. -#### `buffer.resolveObjectURL(id)` +#### `buffer.resolveObjectURL(id)` - + - + * `id` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) A `'blob:nodedata:...` URL string returned by a prior call to `URL.createObjectURL()`. @@ -4417,11 +4417,11 @@ An alias for [`buffer.constants.MAX_STRING_LENGTH`][]. Resolves a `'blob:nodedata:...'` an associated [`Blob`](/api/buffer#blob) object registered using a prior call to `URL.createObjectURL()`. -#### `buffer.transcode(source, fromEnc, toEnc)` +#### `buffer.transcode(source, fromEnc, toEnc)` - + -* `source` {Buffer|Uint8Array} A `Buffer` or `Uint8Array` instance. +* `source` [`Buffer`](/api/buffer#buffer) | [`Uint8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array) A `Buffer` or `Uint8Array` instance. * `fromEnc` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The current encoding. * `toEnc` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) To target encoding. * Returns: [`Buffer`](/api/buffer#buffer) @@ -4457,21 +4457,21 @@ console.log(newBuf.toString('ascii')); Because the Euro (`€`) sign is not representable in US-ASCII, it is replaced with `?` in the transcoded `Buffer`. -#### `SlowBuffer` +#### `SlowBuffer` - + - + See [`Buffer.allocUnsafeSlow()`][]. This was never a class in the sense that the constructor always returned a `Buffer` instance, rather than a `SlowBuffer` instance. -##### `new SlowBuffer(size)` +##### `new SlowBuffer(size)` - + - + * `size` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The desired length of the new `SlowBuffer`. @@ -4479,11 +4479,11 @@ See [`Buffer.allocUnsafeSlow()`][]. #### Buffer constants - + -##### `buffer.constants.MAX_LENGTH` +##### `buffer.constants.MAX_LENGTH` -32 on 64-bit architectures."},{"version":"v14.0.0","pr-url":"https://github.com/nodejs/node/pull/32116","description":"Value is changed from 231 - 1 to 232 - 1 on 64-bit architectures."}],"update":{"type":"added","version":["v8.2.0"]}}} /> +32 on 64-bit architectures."},{"version":"v14.0.0","pr-url":"https://github.com/nodejs/node/pull/32116","description":"Value is changed from 231 - 1 to 232 - 1 on 64-bit architectures."}],"update":{"type":"added","version":["v8.2.0"]}}} /> * [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The largest size allowed for a single `Buffer` instance. @@ -4496,9 +4496,9 @@ It reflects [`v8::TypedArray::kMaxLength`][] under the hood. This value is also available as [`buffer.kMaxLength`][]. -##### `buffer.constants.MAX_STRING_LENGTH` +##### `buffer.constants.MAX_STRING_LENGTH` - + * [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The largest length allowed for a single `string` instance. @@ -4507,7 +4507,7 @@ in UTF-16 code units. This value may depend on the JS engine that is being used. -### `Buffer.from()`, `Buffer.alloc()`, and `Buffer.allocUnsafe()` +### `Buffer.from()`, `Buffer.alloc()`, and `Buffer.allocUnsafe()` In versions of Node.js prior to 6.0.0, `Buffer` instances were created using the `Buffer` constructor function, which allocates the returned `Buffer` @@ -4584,7 +4584,7 @@ memory pool. #### The `--zero-fill-buffers` command-line option - + Node.js can be started using the `--zero-fill-buffers` command-line option to cause all newly-allocated `Buffer` instances to be zero-filled upon creation by diff --git a/content/api/v18/child_process.en.md b/content/api/v18/child_process.en.md index f5d3a88d96..eca68f87b7 100644 --- a/content/api/v18/child_process.en.md +++ b/content/api/v18/child_process.en.md @@ -2,15 +2,15 @@ title: 'child_process' displayTitle: 'Child process' category: 'api' -editPage: 'https://github.com/nodejs/node/blob/v18.8.0/doc/api/child_process.md' +editPage: 'https://github.com/nodejs/node/blob/v18.9.0/doc/api/child_process.md' version: 'v18' --- - + - + - + The `node:child_process` module provides the ability to spawn subprocesses in a manner that is similar, but not identical, to popen(3). This capability @@ -21,15 +21,15 @@ const { spawn } = require('node:child_process'); const ls = spawn('ls', ['-lh', '/usr']); ls.stdout.on('data', (data) => { - console.log(`stdout: $data`); + console.log(`stdout: ${data}`); }); ls.stderr.on('data', (data) => { - console.error(`stderr: $data`); + console.error(`stderr: ${data}`); }); ls.on('close', (code) => { - console.log(`child process exited with code $code`); + console.log(`child process exited with code ${code}`); }); ``` @@ -38,7 +38,7 @@ the parent Node.js process and the spawned subprocess. These pipes have limited (and platform-specific) capacity. If the subprocess writes to stdout in excess of that limit without the output being captured, the subprocess blocks waiting for the pipe buffer to accept more data. This is -identical to the behavior of pipes in the shell. Use the `{ stdio: 'ignore' }` +identical to the behavior of pipes in the shell. Use the ````{ stdio: 'ignore' }```` option if the output will not be consumed. The command lookup is performed using the `options.env.PATH` environment @@ -128,7 +128,7 @@ bat.stderr.on('data', (data) => { }); bat.on('exit', (code) => { - console.log(`Child exited with code $code`); + console.log(`Child exited with code ${code}`); }); ``` @@ -151,9 +151,9 @@ exec('"my script.cmd" a b', (err, stdout, stderr) => { }); ``` -#### `child_process.exec(command[, options][, callback])` +#### `child_process.exec(command[, options][, callback])` - + * `command` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The command to run, with space-separated arguments. * `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) @@ -220,11 +220,11 @@ encoding, `Buffer` objects will be passed to the callback instead. const { exec } = require('node:child_process'); exec('cat *.js missing_file | wc -l', (error, stdout, stderr) => { if (error) { - console.error(`exec error: $error`); + console.error(`exec error: ${error}`); return; } - console.log(`stdout: $stdout`); - console.error(`stderr: $stderr`); + console.log(`stdout: ${stdout}`); + console.error(`stderr: ${stderr}`); }); ``` @@ -268,9 +268,9 @@ const child = exec('grep ssh', { signal }, (error) => { controller.abort(); ``` -#### `child_process.execFile(file[, args][, options][, callback])` +#### `child_process.execFile(file[, args][, options][, callback])` - + * `file` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The name or path of the executable file to run. * `args` string\[] List of string arguments. @@ -363,9 +363,9 @@ const child = execFile('node', ['--version'], { signal }, (error) => { controller.abort(); ``` -#### `child_process.fork(modulePath[, args][, options])` +#### `child_process.fork(modulePath[, args][, options])` - + * `modulePath` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`URL`](/api/url#the-whatwg-url-api) The module to run in the child. * `args` string\[] List of string arguments. @@ -450,9 +450,9 @@ if (process.argv[2] === 'child') { } ``` -#### `child_process.spawn(command[, args][, options])` +#### `child_process.spawn(command[, args][, options])` - + * `command` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The command to run. * `args` string\[] List of string arguments. @@ -524,15 +524,15 @@ const { spawn } = require('node:child_process'); const ls = spawn('ls', ['-lh', '/usr']); ls.stdout.on('data', (data) => { - console.log(`stdout: $data`); + console.log(`stdout: ${data}`); }); ls.stderr.on('data', (data) => { - console.error(`stderr: $data`); + console.error(`stderr: ${data}`); }); ls.on('close', (code) => { - console.log(`child process exited with code $code`); + console.log(`child process exited with code ${code}`); }); ``` @@ -548,12 +548,12 @@ ps.stdout.on('data', (data) => { }); ps.stderr.on('data', (data) => { - console.error(`ps stderr: $data`); + console.error(`ps stderr: ${data}`); }); ps.on('close', (code) => { if (code !== 0) { - console.log(`ps process exited with code $code`); + console.log(`ps process exited with code ${code}`); } grep.stdin.end(); }); @@ -563,12 +563,12 @@ grep.stdout.on('data', (data) => { }); grep.stderr.on('data', (data) => { - console.error(`grep stderr: $data`); + console.error(`grep stderr: ${data}`); }); grep.on('close', (code) => { if (code !== 0) { - console.log(`grep process exited with code $code`); + console.log(`grep process exited with code ${code}`); } }); ``` @@ -607,9 +607,9 @@ grep.on('error', (err) => { controller.abort(); // Stops the child process ``` -##### `options.detached` +##### `options.detached` - + On Windows, setting `options.detached` to `true` makes it possible for the child process to continue running after the parent exits. The child will have @@ -664,9 +664,9 @@ const subprocess = spawn('prg', [], { subprocess.unref(); ``` -##### `options.stdio` +##### `options.stdio` - + The `options.stdio` option is used to configure the pipes that are established between the parent and child process. By default, the child's stdin, stdout, @@ -774,9 +774,9 @@ Blocking calls like these are mostly useful for simplifying general-purpose scripting tasks and for simplifying the loading/processing of application configuration at startup. -#### `child_process.execFileSync(file[, args][, options])` +#### `child_process.execFileSync(file[, args][, options])` - + * `file` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The name or path of the executable file to run. * `args` string\[] List of string arguments. @@ -826,9 +826,9 @@ If the process times out or has a non-zero exit code, this method will throw an function. Any input containing shell metacharacters may be used to trigger arbitrary command execution.** -#### `child_process.execSync(command[, options])` +#### `child_process.execSync(command[, options])` - + * `command` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The command to run. * `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) @@ -874,9 +874,9 @@ The [`Error`][] object will contain the entire result from **Never pass unsanitized user input to this function. Any input containing shell metacharacters may be used to trigger arbitrary command execution.** -#### `child_process.spawnSync(command[, args][, options])` +#### `child_process.spawnSync(command[, args][, options])` - + * `command` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The command to run. * `args` string\[] List of string arguments. @@ -933,9 +933,9 @@ exited. function. Any input containing shell metacharacters may be used to trigger arbitrary command execution.** -### `ChildProcess` +### `ChildProcess` - + * Extends: [`EventEmitter`](/api/events#eventemitter) @@ -946,9 +946,9 @@ use the [`child_process.spawn()`][], [`child_process.exec()`][], [`child_process.execFile()`][], or [`child_process.fork()`][] methods to create instances of `ChildProcess`. -#### `'close'` +#### `'close'` - + * `code` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The exit code if the child exited on its own. * `signal` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The signal by which the child process was terminated. @@ -964,21 +964,21 @@ const { spawn } = require('node:child_process'); const ls = spawn('ls', ['-lh', '/usr']); ls.stdout.on('data', (data) => { - console.log(`stdout: $data`); + console.log(`stdout: ${data}`); }); ls.on('close', (code) => { - console.log(`child process close all stdio with code $code`); + console.log(`child process close all stdio with code ${code}`); }); ls.on('exit', (code) => { - console.log(`child process exited with code $code`); + console.log(`child process exited with code ${code}`); }); ``` -#### `'disconnect'` +#### `'disconnect'` - + The `'disconnect'` event is emitted after calling the [`subprocess.disconnect()`][] method in parent process or @@ -986,7 +986,7 @@ The `'disconnect'` event is emitted after calling the possible to send or receive messages, and the [`subprocess.connected`][] property is `false`. -#### `'error'` +#### `'error'` * `err` [`Error`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error) The error. @@ -1002,9 +1002,9 @@ against accidentally invoking handler functions multiple times. See also [`subprocess.kill()`][] and [`subprocess.send()`][]. -#### `'exit'` +#### `'exit'` - + * `code` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The exit code if the child exited on its own. * `signal` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The signal by which the child process was terminated. @@ -1024,9 +1024,9 @@ re-raise the handled signal. See waitpid(2). -#### `'message'` +#### `'message'` - + * `message` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) A parsed JSON object or primitive value. * `sendHandle` [`Handle`](/api/net#serverlistenhandle-backlog-callback) A [`net.Socket`][] or [`net.Server`][] object, or @@ -1043,9 +1043,9 @@ child process, the `message` argument can contain data that JSON is not able to represent. See [Advanced serialization][] for more details. -#### `'spawn'` +#### `'spawn'` - + The `'spawn'` event is emitted once the child process has spawned successfully. If the child process does not spawn successfully, the `'spawn'` event is not @@ -1057,34 +1057,34 @@ data is received via `stdout` or `stderr`. The `'spawn'` event will fire regardless of whether an error occurs **within** the spawned process. For example, if `bash some-command` spawns successfully, the `'spawn'` event will fire, though `bash` may fail to spawn `some-command`. -This caveat also applies when using `{ shell: true }`. +This caveat also applies when using ````{ shell: true }````. -#### `subprocess.channel` +#### `subprocess.channel` - + * [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) A pipe representing the IPC channel to the child process. The `subprocess.channel` property is a reference to the child's IPC channel. If no IPC channel currently exists, this property is `undefined`. -##### `subprocess.channel.ref()` +##### `subprocess.channel.ref()` - + This method makes the IPC channel keep the event loop of the parent process running if `.unref()` has been called before. -##### `subprocess.channel.unref()` +##### `subprocess.channel.unref()` - + This method makes the IPC channel not keep the event loop of the parent process running, and lets it finish even while the channel is open. -#### `subprocess.connected` +#### `subprocess.connected` - + * [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) Set to `false` after `subprocess.disconnect()` is called. @@ -1092,9 +1092,9 @@ The `subprocess.connected` property indicates whether it is still possible to send and receive messages from a child process. When `subprocess.connected` is `false`, it is no longer possible to send or receive messages. -#### `subprocess.disconnect()` +#### `subprocess.disconnect()` - + Closes the IPC channel between parent and child, allowing the child to exit gracefully once there are no other connections keeping it alive. After calling @@ -1110,16 +1110,16 @@ When the child process is a Node.js instance (e.g. spawned using [`child_process.fork()`][]), the `process.disconnect()` method can be invoked within the child process to close the IPC channel as well. -#### `subprocess.exitCode` +#### `subprocess.exitCode` * [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The `subprocess.exitCode` property indicates the exit code of the child process. If the child process is still running, the field will be `null`. -#### `subprocess.kill([signal])` +#### `subprocess.kill([signal])` - + * `signal` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) * Returns: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) @@ -1135,7 +1135,7 @@ const grep = spawn('grep', ['ssh']); grep.on('close', (code, signal) => { console.log( - `child process terminated due to receipt of signal $signal`); + `child process terminated due to receipt of signal ${signal}`); }); // Send SIGHUP to process. @@ -1183,9 +1183,9 @@ setTimeout(() => { }, 2000); ``` -#### `subprocess.killed` +#### `subprocess.killed` - + * [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) Set to `true` after `subprocess.kill()` is used to successfully send a signal to the child process. @@ -1194,9 +1194,9 @@ The `subprocess.killed` property indicates whether the child process successfully received a signal from `subprocess.kill()`. The `killed` property does not indicate that the child process has been terminated. -#### `subprocess.pid` +#### `subprocess.pid` - + * [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) | [`undefined`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type) @@ -1208,13 +1208,13 @@ emitted. const { spawn } = require('node:child_process'); const grep = spawn('grep', ['ssh']); -console.log(`Spawned child pid: $grep.pid`); +console.log(`Spawned child pid: ${grep.pid}`); grep.stdin.end(); ``` -#### `subprocess.ref()` +#### `subprocess.ref()` - + Calling `subprocess.ref()` after making a call to `subprocess.unref()` will restore the removed reference count for the child process, forcing the parent @@ -1232,9 +1232,9 @@ subprocess.unref(); subprocess.ref(); ``` -#### `subprocess.send(message[, sendHandle[, options]][, callback])` +#### `subprocess.send(message[, sendHandle[, options]][, callback])` - + * `message` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) * `sendHandle` [`Handle`](/api/net#serverlistenhandle-backlog-callback) @@ -1283,7 +1283,7 @@ process.send({ foo: 'bar', baz: NaN }); Child Node.js processes will have a [`process.send()`][] method of their own that allows the child to send messages back to the parent. -There is a special case when sending a `{cmd: 'NODE_foo'}` message. Messages +There is a special case when sending a ````{cmd: 'NODE_foo'}```` message. Messages containing a `NODE_` prefix in the `cmd` property are reserved for use within Node.js core and will not be emitted in the child's [`'message'`][] event. Rather, such messages are emitted using the @@ -1399,21 +1399,21 @@ Any `'message'` handlers in the subprocess should verify that `socket` exists, as the connection may have been closed during the time it takes to send the connection to the child. -#### `subprocess.signalCode` +#### `subprocess.signalCode` * [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`null`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type) The `subprocess.signalCode` property indicates the signal received by the child process if any, else `null`. -#### `subprocess.spawnargs` +#### `subprocess.spawnargs` * [`Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array) The `subprocess.spawnargs` property represents the full list of command-line arguments the child process was launched with. -#### `subprocess.spawnfile` +#### `subprocess.spawnfile` * [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) @@ -1427,9 +1427,9 @@ the executable file. For [`child_process.exec()`][], its value will be the name of the shell in which the child process is launched. -#### `subprocess.stderr` +#### `subprocess.stderr` - + * [`stream.Readable`](/api/stream#streamreadable) | [`null`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type) | [`undefined`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type) @@ -1444,9 +1444,9 @@ refer to the same value. The `subprocess.stderr` property can be `null` or `undefined` if the child process could not be successfully spawned. -#### `subprocess.stdin` +#### `subprocess.stdin` - + * [`stream.Writable`](/api/stream#streamwritable) | [`null`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type) | [`undefined`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type) @@ -1464,9 +1464,9 @@ refer to the same value. The `subprocess.stdin` property can be `null` or `undefined` if the child process could not be successfully spawned. -#### `subprocess.stdio` +#### `subprocess.stdio` - + * [`Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array) @@ -1506,9 +1506,9 @@ assert.strictEqual(subprocess.stdio[2], subprocess.stderr); The `subprocess.stdio` property can be `undefined` if the child process could not be successfully spawned. -#### `subprocess.stdout` +#### `subprocess.stdout` - + * [`stream.Readable`](/api/stream#streamreadable) | [`null`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type) | [`undefined`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type) @@ -1526,16 +1526,16 @@ const { spawn } = require('node:child_process'); const subprocess = spawn('ls'); subprocess.stdout.on('data', (data) => { - console.log(`Received chunk $data`); + console.log(`Received chunk ${data}`); }); ``` The `subprocess.stdout` property can be `null` or `undefined` if the child process could not be successfully spawned. -#### `subprocess.unref()` +#### `subprocess.unref()` - + By default, the parent will wait for the detached child to exit. To prevent the parent from waiting for a given `subprocess` to exit, use the @@ -1555,7 +1555,7 @@ const subprocess = spawn(process.argv[0], ['child_program.js'], { subprocess.unref(); ``` -### `maxBuffer` and Unicode +### `maxBuffer` and Unicode The `maxBuffer` option specifies the largest number of bytes allowed on `stdout` or `stderr`. If this value is exceeded, then the child process is terminated. @@ -1579,7 +1579,7 @@ unavailable. ### Advanced serialization - + Child processes support a serialization mechanism for IPC that is based on the [serialization API of the `node:v8` module][v8.serdes], based on the diff --git a/content/api/v18/cli.en.md b/content/api/v18/cli.en.md index 345bc84761..27c7a6afc2 100644 --- a/content/api/v18/cli.en.md +++ b/content/api/v18/cli.en.md @@ -2,13 +2,13 @@ title: 'cli' displayTitle: 'Command-line API' category: 'api' -editPage: 'https://github.com/nodejs/node/blob/v18.8.0/doc/api/cli.md' +editPage: 'https://github.com/nodejs/node/blob/v18.9.0/doc/api/cli.md' version: 'v18' --- - + - + Node.js comes with a variety of CLI options. These options expose built-in debugging, multiple ways to execute scripts, and other helpful runtime options. @@ -56,7 +56,7 @@ extensions; and with `.wasm` extensions when ### Options - + All options, including V8 options, allow words to be separated by both dashes (`-`) or underscores (`_`). For example, `--pending-deprecation` is @@ -67,25 +67,25 @@ passed more than once, then the last passed value is used. Options from the command line take precedence over options passed through the [`NODE_OPTIONS`][] environment variable. -#### `-` +#### `-` - + Alias for stdin. Analogous to the use of `-` in other command-line utilities, meaning that the script is read from stdin, and the rest of the options are passed to that script. -#### `--` +#### `--` - + Indicate the end of node options. Pass the rest of the arguments to the script. If no script filename or eval/print script is supplied prior to this, then the next argument is used as a script filename. -#### `--abort-on-uncaught-exception` +#### `--abort-on-uncaught-exception` - + Aborting instead of exiting causes a core file to be generated for post-mortem analysis using a debugger (such as `lldb`, `gdb`, and `mdb`). @@ -94,11 +94,11 @@ If this flag is passed, the behavior can still be set to not abort through [`process.setUncaughtExceptionCaptureCallback()`][] (and through usage of the `node:domain` module that uses it). -#### `--build-snapshot` +#### `--build-snapshot` - + - + Generates a snapshot blob when the process exits and writes it to disk, which can be loaded later with `--snapshot-blob`. @@ -111,13 +111,13 @@ the path specified by `--snapshot-blob`. ```console $ echo "globalThis.foo = 'I am from the snapshot'" > snapshot.js -## Run snapshot.js to intialize the application and snapshot the +# Run snapshot.js to intialize the application and snapshot the # state of it into snapshot.blob. $ node --snapshot-blob snapshot.blob --build-snapshot snapshot.js $ echo "console.log(globalThis.foo)" > index.js -## Load the generated snapshot and start the application from index.js. +# Load the generated snapshot and start the application from index.js. $ node --snapshot-blob snapshot.blob index.js I am from the snapshot ``` @@ -148,9 +148,9 @@ Currently the support for run-time snapshot is experimental in that: a report in the [Node.js issue tracker][] and link to it in the [tracking issue for user-land snapshots][]. -#### `--completion-bash` +#### `--completion-bash` - + Print source-able bash completion script for Node.js. @@ -159,11 +159,11 @@ $ node --completion-bash > node_bash_completion $ source node_bash_completion ``` -#### `-C=condition`, `--conditions=condition` +#### `-C=condition`, `--conditions=condition` - + - + Enable experimental support for custom [conditional exports][] resolution conditions. @@ -179,11 +179,11 @@ For example, to run a module with "development" resolutions: $ node -C=development app.js ``` -#### `--cpu-prof` +#### `--cpu-prof` - + - + Starts the V8 CPU profiler on start up, and writes the CPU profile to disk before exit. @@ -200,11 +200,11 @@ $ ls *.cpuprofile CPU.20190409.202950.15293.0.0.cpuprofile ``` -#### `--cpu-prof-dir` +#### `--cpu-prof-dir` - + - + Specify the directory where the CPU profiles generated by `--cpu-prof` will be placed. @@ -212,24 +212,24 @@ be placed. The default value is controlled by the [`--diagnostic-dir`][] command-line option. -#### `--cpu-prof-interval` +#### `--cpu-prof-interval` - + - + Specify the sampling interval in microseconds for the CPU profiles generated by `--cpu-prof`. The default is 1000 microseconds. -#### `--cpu-prof-name` +#### `--cpu-prof-name` - + - + Specify the file name of the CPU profile generated by `--cpu-prof`. -#### `--diagnostic-dir=directory` +#### `--diagnostic-dir=directory` Set the directory to which all diagnostic output files are written. Defaults to current working directory. @@ -240,25 +240,25 @@ Affects the default output directory of: * [`--heap-prof-dir`][] * [`--redirect-warnings`][] -#### `--disable-proto=mode` +#### `--disable-proto=mode` - + Disable the `Object.prototype.__proto__` property. If `mode` is `delete`, the property is removed entirely. If `mode` is `throw`, accesses to the property throw an exception with the code `ERR_PROTO_ACCESS`. -#### `--disallow-code-generation-from-strings` +#### `--disallow-code-generation-from-strings` - + Make built-in language features like `eval` and `new Function` that generate code from strings throw an exception instead. This does not affect the Node.js `node:vm` module. -#### `--dns-result-order=order` +#### `--dns-result-order=order` - + Set the default value of `verbatim` in [`dns.lookup()`][] and [`dnsPromises.lookup()`][]. The value could be: @@ -269,16 +269,16 @@ Set the default value of `verbatim` in [`dns.lookup()`][] and The default is `verbatim` and [`dns.setDefaultResultOrder()`][] have higher priority than `--dns-result-order`. -#### `--enable-fips` +#### `--enable-fips` - + Enable FIPS-compliant crypto at startup. (Requires Node.js to be built against FIPS-compatible OpenSSL.) -#### `--enable-source-maps` +#### `--enable-source-maps` - + Enable [Source Map v3][Source Map] support for stack traces. @@ -295,60 +295,60 @@ when `Error.stack` is accessed. If you access `Error.stack` frequently in your application, take into account the performance implications of `--enable-source-maps`. -#### `--experimental-global-customevent` +#### `--experimental-global-customevent` - + Expose the [CustomEvent Web API][] on the global scope. -#### `--experimental-global-webcrypto` +#### `--experimental-global-webcrypto` - + Expose the [Web Crypto API][] on the global scope. -#### `--experimental-import-meta-resolve` +#### `--experimental-import-meta-resolve` - + Enable experimental `import.meta.resolve()` support. -#### `--experimental-loader=module` +#### `--experimental-loader=module` - + Specify the `module` of a custom experimental [ECMAScript module loader][]. `module` may be any string accepted as an [`import` specifier][]. -#### `--experimental-network-imports` +#### `--experimental-network-imports` - + - + Enable experimental support for the `https:` protocol in `import` specifiers. -#### `--experimental-policy` +#### `--experimental-policy` - + Use the specified file as a security policy. -#### `--no-experimental-fetch` +#### `--no-experimental-fetch` - + Disable experimental support for the [Fetch API][]. -#### `--no-experimental-repl-await` +#### `--no-experimental-repl-await` - + Use this flag to disable top-level await in REPL. -#### `--experimental-specifier-resolution=mode` +#### `--experimental-specifier-resolution=mode` - + Sets the resolution algorithm for resolving ES module specifiers. Valid options are `explicit` and `node`. @@ -359,42 +359,42 @@ the ability to import a directory that has an index file. See [customizing ESM specifier resolution][] for example usage. -#### `--experimental-vm-modules` +#### `--experimental-vm-modules` - + Enable experimental ES Module support in the `node:vm` module. -#### `--experimental-wasi-unstable-preview1` +#### `--experimental-wasi-unstable-preview1` - + Enable experimental WebAssembly System Interface (WASI) support. -#### `--experimental-wasm-modules` +#### `--experimental-wasm-modules` - + Enable experimental WebAssembly module support. -#### `--force-context-aware` +#### `--force-context-aware` - + Disable loading native addons that are not [context-aware][]. -#### `--force-fips` +#### `--force-fips` - + Force FIPS-compliant crypto on startup. (Cannot be disabled from script code.) (Same requirements as `--enable-fips`.) -#### `--frozen-intrinsics` +#### `--frozen-intrinsics` - + - + Enable experimental frozen intrinsics like `Array` and `Object`. @@ -404,9 +404,9 @@ under this flag. To allow polyfills to be added, `--require` runs before freezing intrinsics. -#### `--force-node-api-uncaught-exceptions-policy` +#### `--force-node-api-uncaught-exceptions-policy` - + Enforces `uncaughtException` event on Node-API asynchronous callbacks. @@ -414,11 +414,11 @@ To prevent from an existing add-on from crashing the process, this flag is not enabled by default. In the future, this flag will be enabled by default to enforce the correct behavior. -#### `--heapsnapshot-near-heap-limit=max_count` +#### `--heapsnapshot-near-heap-limit=max_count` - + - + Writes a V8 heap snapshot to disk when the V8 heap usage is approaching the heap limit. `count` should be a non-negative integer (in which case @@ -459,9 +459,9 @@ FATAL ERROR: Ineffective mark-compacts near heap limit Allocation failed - JavaS .... ``` -#### `--heapsnapshot-signal=signal` +#### `--heapsnapshot-signal=signal` - + Enables a signal handler that causes the Node.js process to write a heap dump when the specified signal is received. `signal` must be a valid signal name. @@ -477,11 +477,11 @@ $ ls Heap.20190718.133405.15554.0.001.heapsnapshot ``` -#### `--heap-prof` +#### `--heap-prof` - + - + Starts the V8 heap profiler on start up, and writes the heap profile to disk before exit. @@ -498,11 +498,11 @@ $ ls *.heapprofile Heap.20190409.202950.15293.0.001.heapprofile ``` -#### `--heap-prof-dir` +#### `--heap-prof-dir` - + - + Specify the directory where the heap profiles generated by `--heap-prof` will be placed. @@ -510,32 +510,32 @@ be placed. The default value is controlled by the [`--diagnostic-dir`][] command-line option. -#### `--heap-prof-interval` +#### `--heap-prof-interval` - + - + Specify the average sampling interval in bytes for the heap profiles generated by `--heap-prof`. The default is 512 \* 1024 bytes. -#### `--heap-prof-name` +#### `--heap-prof-name` - + - + Specify the file name of the heap profile generated by `--heap-prof`. -#### `--icu-data-dir=file` +#### `--icu-data-dir=file` - + Specify ICU data load path. (Overrides `NODE_ICU_DATA`.) -#### `--input-type=type` +#### `--input-type=type` - + This configures Node.js to interpret string input as CommonJS or as an ES module. String input is input via `--eval`, `--print`, or `STDIN`. @@ -544,16 +544,16 @@ Valid values are `"commonjs"` and `"module"`. The default is `"commonjs"`. The REPL does not support this option. -#### `--inspect-brk[=[host:]port]` +#### `--inspect-brk[=[host:]port]` - + Activate inspector on `host:port` and break at start of user script. Default `host:port` is `127.0.0.1:9229`. -#### `--inspect-port=[host:]port` +#### `--inspect-port=[host:]port` - + Set the `host:port` to be used when the inspector is activated. Useful when activating the inspector by sending the `SIGUSR1` signal. @@ -563,9 +563,9 @@ Default host is `127.0.0.1`. See the [security warning][] below regarding the `host` parameter usage. -#### `--inspect[=[host:]port]` +#### `--inspect[=[host:]port]` - + Activate inspector on `host:port`. Default is `127.0.0.1:9229`. @@ -593,25 +593,25 @@ default) is not firewall-protected.** See the [debugging security implications][] section for more information. -#### `--inspect-publish-uid=stderr,http` +#### `--inspect-publish-uid=stderr,http` Specify ways of the inspector web socket url exposure. By default inspector websocket url is available in stderr and under `/json/list` endpoint on `http://host:port/json/list`. -#### `--insecure-http-parser` +#### `--insecure-http-parser` - + Use an insecure HTTP parser that accepts invalid HTTP headers. This may allow interoperability with non-conformant HTTP implementations. It may also allow request smuggling and other HTTP attacks that rely on invalid headers being accepted. Avoid using this option. -#### `--jitless` +#### `--jitless` - + Disable [runtime allocation of executable memory][jitless]. This may be required on some platforms for security reasons. It can also reduce attack @@ -620,76 +620,76 @@ surface on other platforms, but the performance impact may be severe. This flag is inherited from V8 and is subject to change upstream. It may disappear in a non-semver-major release. -#### `--max-http-header-size=size` +#### `--max-http-header-size=size` - + Specify the maximum size, in bytes, of HTTP headers. Defaults to 16 KiB. -#### `--napi-modules` +#### `--napi-modules` - + This option is a no-op. It is kept for compatibility. -#### `--no-addons` +#### `--no-addons` - + Disable the `node-addons` exports condition as well as disable loading native addons. When `--no-addons` is specified, calling `process.dlopen` or requiring a native C++ addon will fail and throw an exception. -#### `--no-deprecation` +#### `--no-deprecation` - + Silence deprecation warnings. -#### `--no-extra-info-on-fatal-exception` +#### `--no-extra-info-on-fatal-exception` - + Hide extra information on fatal exception that causes exit. -#### `--no-force-async-hooks-checks` +#### `--no-force-async-hooks-checks` - + Disables runtime checks for `async_hooks`. These will still be enabled dynamically when `async_hooks` is enabled. -#### `--no-global-search-paths` +#### `--no-global-search-paths` - + Do not search modules from global paths like `$HOME/.node_modules` and `$NODE_PATH`. -#### `--no-warnings` +#### `--no-warnings` - + Silence all process warnings (including deprecations). -#### `--node-memory-debug` +#### `--node-memory-debug` - + Enable extra debug checks for memory leaks in Node.js internals. This is usually only useful for developers debugging Node.js itself. -#### `--openssl-config=file` +#### `--openssl-config=file` - + Load an OpenSSL configuration file on startup. Among other uses, this can be used to enable FIPS-compliant crypto if Node.js is built against FIPS-enabled OpenSSL. -#### `--openssl-shared-config` +#### `--openssl-shared-config` - + Enable OpenSSL default configuration section, `openssl_conf` to be read from the OpenSSL configuration file. The default configuration file is named @@ -700,16 +700,16 @@ is being linked to Node.js. Sharing the OpenSSL configuration may have unwanted implications and it is recommended to use a configuration section specific to Node.js which is `nodejs_conf` and is default when this option is not used. -#### `--openssl-legacy-provider` +#### `--openssl-legacy-provider` - + Enable OpenSSL 3.0 legacy provider. For more information please see [OSSL\_PROVIDER-legacy][OSSL_PROVIDER-legacy]. -#### `--pending-deprecation` +#### `--pending-deprecation` - + Emit pending deprecation warnings. @@ -720,19 +720,19 @@ unless either the `--pending-deprecation` command-line flag, or the are used to provide a kind of selective "early warning" mechanism that developers may leverage to detect deprecated API usage. -#### `--policy-integrity=sri` +#### `--policy-integrity=sri` - + - + Instructs Node.js to error prior to running any code if the policy does not have the specified integrity. It expects a [Subresource Integrity][] string as a parameter. -#### `--preserve-symlinks` +#### `--preserve-symlinks` - + Instructs the module loader to preserve symbolic links when resolving and caching modules. @@ -746,11 +746,11 @@ illustrated in the example below, the default behavior causes an exception to be thrown if `moduleA` attempts to require `moduleB` as a peer dependency: ```text -appDir +{appDir} ├── app │ ├── index.js │ └── node_modules - │ ├── moduleA -> appDir/moduleA + │ ├── moduleA -> {appDir}/moduleA │ └── moduleB │ ├── index.js │ └── package.json @@ -773,9 +773,9 @@ The `--preserve-symlinks` flag does not apply to the main module, which allows `node --preserve-symlinks node_module/.bin/` to work. To apply the same behavior for the main module, also use `--preserve-symlinks-main`. -#### `--preserve-symlinks-main` +#### `--preserve-symlinks-main` - + Instructs the module loader to preserve symbolic links when resolving and caching the main module (`require.main`). @@ -791,21 +791,21 @@ resolving relative paths. See `--preserve-symlinks` for more information. -#### `--prof` +#### `--prof` - + Generate V8 profiler output. -#### `--prof-process` +#### `--prof-process` - + Process V8 profiler output generated using the V8 option `--prof`. -#### `--redirect-warnings=file` +#### `--redirect-warnings=file` - + Write process warnings to the given file instead of printing to stderr. The file will be created if it does not exist, and will be appended to if it does. @@ -816,32 +816,32 @@ The `file` name may be an absolute path. If it is not, the default directory it will be written to is controlled by the [`--diagnostic-dir`][] command-line option. -#### `--report-compact` +#### `--report-compact` - + Write reports in a compact format, single-line JSON, more easily consumable by log processing systems than the default multi-line format designed for human consumption. -#### `--report-dir=directory`, `report-directory=directory` +#### `--report-dir=directory`, `report-directory=directory` - + Location at which the report will be generated. -#### `--report-filename=filename` +#### `--report-filename=filename` - + Name of the file to which the report will be written. If the filename is set to `'stdout'` or `'stderr'`, the report is written to the stdout or stderr of the process respectively. -#### `--report-on-fatalerror` +#### `--report-on-fatalerror` - + Enables the report to be triggered on fatal errors (internal errors within the Node.js runtime such as out of memory) that lead to termination of the @@ -849,32 +849,32 @@ application. Useful to inspect various diagnostic data elements such as heap, stack, event loop state, resource consumption etc. to reason about the fatal error. -#### `--report-on-signal` +#### `--report-on-signal` - + Enables report to be generated upon receiving the specified (or predefined) signal to the running Node.js process. The signal to trigger the report is specified through `--report-signal`. -#### `--report-signal=signal` +#### `--report-signal=signal` - + Sets or resets the signal for report generation (not supported on Windows). Default signal is `SIGUSR2`. -#### `--report-uncaught-exception` +#### `--report-uncaught-exception` - + Enables report to be generated when the process exits due to an uncaught exception. Useful when inspecting the JavaScript stack in conjunction with native stack and other runtime environment data. -#### `--secure-heap=n` +#### `--secure-heap=n` - + Initializes an OpenSSL secure heap of `n` bytes. When initialized, the secure heap is used for selected types of allocations within OpenSSL @@ -895,20 +895,20 @@ The secure heap is not available on Windows. See [`CRYPTO_secure_malloc_init`][] for more details. -#### `--secure-heap-min=n` +#### `--secure-heap-min=n` - + When using `--secure-heap`, the `--secure-heap-min` flag specifies the minimum allocation from the secure heap. The minimum value is `2`. The maximum value is the lesser of `--secure-heap` or `2147483647`. The value given must be a power of two. -#### `--snapshot-blob=path` +#### `--snapshot-blob=path` - + - + When used with `--build-snapshot`, `--snapshot-blob` specifies the path where the generated snapshot blob will be written to. If not specified, @@ -918,96 +918,96 @@ in the current working directory. When used without `--build-snapshot`, `--snapshot-blob` specifies the path to the blob that will be used to restore the application state. -#### `--test` +#### `--test` - + Starts the Node.js command line test runner. This flag cannot be combined with `--check`, `--eval`, `--interactive`, or the inspector. See the documentation on [running tests from the command line][] for more details. -#### `--test-only` +#### `--test-only` - + Configures the test runner to only execute top level tests that have the `only` option set. -#### `--throw-deprecation` +#### `--throw-deprecation` - + Throw errors for deprecations. -#### `--title=title` +#### `--title=title` - + Set `process.title` on startup. -#### `--tls-cipher-list=list` +#### `--tls-cipher-list=list` - + Specify an alternative default TLS cipher list. Requires Node.js to be built with crypto support (default). -#### `--tls-keylog=file` +#### `--tls-keylog=file` - + Log TLS key material to a file. The key material is in NSS `SSLKEYLOGFILE` format and can be used by software (such as Wireshark) to decrypt the TLS traffic. -#### `--tls-max-v1.2` +#### `--tls-max-v1.2` - + Set [`tls.DEFAULT_MAX_VERSION`][] to 'TLSv1.2'. Use to disable support for TLSv1.3. -#### `--tls-max-v1.3` +#### `--tls-max-v1.3` - + Set default [`tls.DEFAULT_MAX_VERSION`][] to 'TLSv1.3'. Use to enable support for TLSv1.3. -#### `--tls-min-v1.0` +#### `--tls-min-v1.0` - + Set default [`tls.DEFAULT_MIN_VERSION`][] to 'TLSv1'. Use for compatibility with old TLS clients or servers. -#### `--tls-min-v1.1` +#### `--tls-min-v1.1` - + Set default [`tls.DEFAULT_MIN_VERSION`][] to 'TLSv1.1'. Use for compatibility with old TLS clients or servers. -#### `--tls-min-v1.2` +#### `--tls-min-v1.2` - + Set default [`tls.DEFAULT_MIN_VERSION`][] to 'TLSv1.2'. This is the default for 12.x and later, but the option is supported for compatibility with older Node.js versions. -#### `--tls-min-v1.3` +#### `--tls-min-v1.3` - + Set default [`tls.DEFAULT_MIN_VERSION`][] to 'TLSv1.3'. Use to disable support for TLSv1.2, which is not as secure as TLSv1.3. -#### `--trace-atomics-wait` +#### `--trace-atomics-wait` - + - + Print short summaries of calls to [`Atomics.wait()`][] to stderr. The output could look like this: @@ -1031,62 +1031,62 @@ The fields here correspond to: * The expected value that was passed to `Atomics.wait()` * The timeout passed to `Atomics.wait` -#### `--trace-deprecation` +#### `--trace-deprecation` - + Print stack traces for deprecations. -#### `--trace-event-categories` +#### `--trace-event-categories` - + A comma separated list of categories that should be traced when trace event tracing is enabled using `--trace-events-enabled`. -#### `--trace-event-file-pattern` +#### `--trace-event-file-pattern` - + Template string specifying the filepath for the trace event data, it supports `$rotation` and `$pid`. -#### `--trace-events-enabled` +#### `--trace-events-enabled` - + Enables the collection of trace event tracing information. -#### `--trace-exit` +#### `--trace-exit` - + Prints a stack trace whenever an environment is exited proactively, i.e. invoking `process.exit()`. -#### `--trace-sigint` +#### `--trace-sigint` - + Prints a stack trace on SIGINT. -#### `--trace-sync-io` +#### `--trace-sync-io` - + Prints a stack trace whenever synchronous I/O is detected after the first turn of the event loop. -#### `--trace-tls` +#### `--trace-tls` - + Prints TLS packet trace information to `stderr`. This can be used to debug TLS connection problems. -#### `--trace-uncaught` +#### `--trace-uncaught` - + Print stack traces for uncaught exceptions; usually, the stack trace associated with the creation of an `Error` is printed, whereas this makes Node.js also @@ -1095,21 +1095,21 @@ to be an `Error` instance). Enabling this option may affect garbage collection behavior negatively. -#### `--trace-warnings` +#### `--trace-warnings` - + Print stack traces for process warnings (including deprecations). -#### `--track-heap-objects` +#### `--track-heap-objects` - + Track heap object allocations for heap snapshots. -#### `--unhandled-rejections=mode` +#### `--unhandled-rejections=mode` - + Using this flag allows to change what should happen when an unhandled rejection occurs. One of the following modes can be chosen: @@ -1127,15 +1127,15 @@ occurs. One of the following modes can be chosen: If a rejection happens during the command line entry point's ES module static loading phase, it will always raise it as an uncaught exception. -#### `--update-assert-snapshot` +#### `--update-assert-snapshot` - + -Force updating snapshot files for [`assert.snapshot()`][] +Updates snapshot files used by [`assert.snapshot()`][]. -#### `--use-bundled-ca`, `--use-openssl-ca` +#### `--use-bundled-ca`, `--use-openssl-ca` - + Use bundled Mozilla CA store as supplied by current Node.js version or use OpenSSL's default CA store. The default store is selectable @@ -1152,9 +1152,9 @@ environment variables. See `SSL_CERT_DIR` and `SSL_CERT_FILE`. -#### `--use-largepages=mode` +#### `--use-largepages=mode` - + Re-map the Node.js static code to large memory pages at startup. If supported on the target system, this will cause the Node.js static code to be moved onto 2 @@ -1168,15 +1168,15 @@ The following values are valid for `mode`: * `silent`: If supported by the OS, mapping will be attempted. Failure to map will be ignored and will not be reported. -#### `--v8-options` +#### `--v8-options` - + Print V8 command-line options. -#### `--v8-pool-size=num` +#### `--v8-pool-size=num` - + Set V8's thread pool size which will be used to allocate background jobs. @@ -1186,22 +1186,22 @@ on the number of online processors. If the value provided is larger than V8's maximum, then the largest value will be chosen. -#### `--zero-fill-buffers` +#### `--zero-fill-buffers` - + Automatically zero-fills all newly allocated [`Buffer`][] and [`SlowBuffer`][] instances. -#### `-c`, `--check` +#### `-c`, `--check` - + Syntax check the script without executing. -#### `-e`, `--eval "script"` +#### `-e`, `--eval "script"` - + Evaluate the following argument as JavaScript. The modules which are predefined in the REPL can also be used in `script`. @@ -1210,28 +1210,28 @@ On Windows, using `cmd.exe` a single quote will not work correctly because it only recognizes double `"` for quoting. In Powershell or Git bash, both `'` and `"` are usable. -#### `-h`, `--help` +#### `-h`, `--help` - + Print node command-line options. The output of this option is less detailed than this document. -#### `-i`, `--interactive` +#### `-i`, `--interactive` - + Opens the REPL even if stdin does not appear to be a terminal. -#### `-p`, `--print "script"` +#### `-p`, `--print "script"` - + Identical to `-e` but prints the result. -#### `-r`, `--require module` +#### `-r`, `--require module` - + Preload the specified module at startup. @@ -1241,15 +1241,15 @@ rules. `module` may be either a path to a file, or a node module name. Only CommonJS modules are supported. Attempting to preload a ES6 Module using `--require` will fail with an error. -#### `-v`, `--version` +#### `-v`, `--version` - + Print node's version. ### Environment variables -#### `FORCE_COLOR=[1, 2, 3]` +#### `FORCE_COLOR=[1, 2, 3]` The `FORCE_COLOR` environment variable is used to enable ANSI colorized output. The value may be: @@ -1263,25 +1263,25 @@ and `NODE_DISABLE_COLORS` environment variables are ignored. Any other value will result in colorized output being disabled. -#### `NODE_DEBUG=module[,…]` +#### `NODE_DEBUG=module[,…]` - + `','`-separated list of core modules that should print debug information. -#### `NODE_DEBUG_NATIVE=module[,…]` +#### `NODE_DEBUG_NATIVE=module[,…]` `','`-separated list of core C++ modules that should print debug information. -#### `NODE_DISABLE_COLORS=1` +#### `NODE_DISABLE_COLORS=1` - + When set, colors will not be used in the REPL. -#### `NODE_EXTRA_CA_CERTS=file` +#### `NODE_EXTRA_CA_CERTS=file` - + When set, the well known "root" CAs (like VeriSign) will be extended with the extra certificates in `file`. The file should consist of one or more trusted @@ -1299,22 +1299,22 @@ The `NODE_EXTRA_CA_CERTS` environment variable is only read when the Node.js process is first launched. Changing the value at runtime using `process.env.NODE_EXTRA_CA_CERTS` has no effect on the current process. -#### `NODE_ICU_DATA=file` +#### `NODE_ICU_DATA=file` - + Data path for ICU (`Intl` object) data. Will extend linked-in data when compiled with small-icu support. -#### `NODE_NO_WARNINGS=1` +#### `NODE_NO_WARNINGS=1` - + When set to `1`, process warnings are silenced. -#### `NODE_OPTIONS=options...` +#### `NODE_OPTIONS=options...` - + A space-separated list of command-line options. `options...` are interpreted before command-line options, so command-line options will override or @@ -1469,17 +1469,17 @@ V8 options that are allowed are: `--perf-basic-prof-only-functions`, `--perf-basic-prof`, `--perf-prof-unwinding-info`, and `--perf-prof` are only available on Linux. -#### `NODE_PATH=path[:…]` +#### `NODE_PATH=path[:…]` - + `':'`-separated list of directories prefixed to the module search path. On Windows, this is a `';'`-separated list instead. -#### `NODE_PENDING_DEPRECATION=1` +#### `NODE_PENDING_DEPRECATION=1` - + When set to `1`, emit pending deprecation warnings. @@ -1490,21 +1490,21 @@ unless either the `--pending-deprecation` command-line flag, or the are used to provide a kind of selective "early warning" mechanism that developers may leverage to detect deprecated API usage. -#### `NODE_PENDING_PIPE_INSTANCES=instances` +#### `NODE_PENDING_PIPE_INSTANCES=instances` Set the number of pending pipe instance handles when the pipe server is waiting for connections. This setting applies to Windows only. -#### `NODE_PRESERVE_SYMLINKS=1` +#### `NODE_PRESERVE_SYMLINKS=1` - + When set to `1`, instructs the module loader to preserve symbolic links when resolving and caching modules. -#### `NODE_REDIRECT_WARNINGS=file` +#### `NODE_REDIRECT_WARNINGS=file` - + When set, process warnings will be emitted to the given file instead of printing to stderr. The file will be created if it does not exist, and will be @@ -1512,36 +1512,36 @@ appended to if it does. If an error occurs while attempting to write the warning to the file, the warning will be written to stderr instead. This is equivalent to using the `--redirect-warnings=file` command-line flag. -#### `NODE_REPL_HISTORY=file` +#### `NODE_REPL_HISTORY=file` - + Path to the file used to store the persistent REPL history. The default path is `~/.node_repl_history`, which is overridden by this variable. Setting the value to an empty string (`''` or `' '`) disables persistent REPL history. -#### `NODE_REPL_EXTERNAL_MODULE=file` +#### `NODE_REPL_EXTERNAL_MODULE=file` - + Path to a Node.js module which will be loaded in place of the built-in REPL. Overriding this value to an empty string (`''`) will use the built-in REPL. -#### `NODE_SKIP_PLATFORM_CHECK=value` +#### `NODE_SKIP_PLATFORM_CHECK=value` - + If `value` equals `'1'`, the check for a supported platform is skipped during Node.js startup. Node.js might not execute correctly. Any issues encountered on unsupported platforms will not be fixed. -#### `NODE_TLS_REJECT_UNAUTHORIZED=value` +#### `NODE_TLS_REJECT_UNAUTHORIZED=value` If `value` equals `'0'`, certificate validation is disabled for TLS connections. This makes TLS, and HTTPS by extension, insecure. The use of this environment variable is strongly discouraged. -#### `NODE_V8_COVERAGE=dir` +#### `NODE_V8_COVERAGE=dir` When set, Node.js will begin outputting [V8 JavaScript code coverage][] and [Source Map][] data to the directory provided as an argument (coverage @@ -1571,7 +1571,7 @@ key `result`: ##### Source map cache - + If found, source map data is appended to the top-level key `source-map-cache` on the JSON coverage object. @@ -1617,14 +1617,14 @@ and the line lengths of the source file (in the key `lineLengths`). } ``` -#### `NO_COLOR=` +#### `NO_COLOR=` [`NO_COLOR`][] is an alias for `NODE_DISABLE_COLORS`. The value of the environment variable is arbitrary. -#### `OPENSSL_CONF=file` +#### `OPENSSL_CONF=file` - + Load an OpenSSL configuration file on startup. Among other uses, this can be used to enable FIPS-compliant crypto if Node.js is built with @@ -1633,9 +1633,9 @@ used to enable FIPS-compliant crypto if Node.js is built with If the [`--openssl-config`][] command-line option is used, the environment variable is ignored. -#### `SSL_CERT_DIR=dir` +#### `SSL_CERT_DIR=dir` - + If `--use-openssl-ca` is enabled, this overrides and sets OpenSSL's directory containing trusted certificates. @@ -1644,9 +1644,9 @@ Be aware that unless the child environment is explicitly set, this environment variable will be inherited by any child processes, and if they use OpenSSL, it may cause them to trust the same CAs as node. -#### `SSL_CERT_FILE=file` +#### `SSL_CERT_FILE=file` - + If `--use-openssl-ca` is enabled, this overrides and sets OpenSSL's file containing trusted certificates. @@ -1655,9 +1655,9 @@ Be aware that unless the child environment is explicitly set, this environment variable will be inherited by any child processes, and if they use OpenSSL, it may cause them to trust the same CAs as node. -#### `TZ` +#### `TZ` - + The `TZ` environment variable is used to specify the timezone configuration. @@ -1672,7 +1672,7 @@ $ TZ=Europe/Dublin node -pe "new Date().toString()" Wed May 12 2021 20:30:48 GMT+0100 (Irish Standard Time) ``` -#### `UV_THREADPOOL_SIZE=size` +#### `UV_THREADPOOL_SIZE=size` Set the number of threads used in libuv's threadpool to `size` threads. @@ -1706,7 +1706,7 @@ options are of interest only to V8 developers. Despite this, there is a small set of V8 options that are widely applicable to Node.js, and they are documented here: -#### `--max-old-space-size=SIZE` (in megabytes) +#### `--max-old-space-size=SIZE` (in megabytes) Sets the max memory size of V8's old memory section. As memory consumption approaches the limit, V8 will spend more time on @@ -1719,7 +1719,7 @@ On a machine with 2 GiB of memory, consider setting this to $ node --max-old-space-size=1536 index.js ``` -#### `--max-semi-space-size=SIZE` (in megabytes) +#### `--max-semi-space-size=SIZE` (in megabytes) Sets the maximum [semi-space][] size for V8's [scavenge garbage collector][] in MiB (megabytes). diff --git a/content/api/v18/cluster.en.md b/content/api/v18/cluster.en.md index 1924953cc5..8fdb2738f6 100644 --- a/content/api/v18/cluster.en.md +++ b/content/api/v18/cluster.en.md @@ -2,15 +2,15 @@ title: 'cluster' displayTitle: 'Cluster' category: 'api' -editPage: 'https://github.com/nodejs/node/blob/v18.8.0/doc/api/cluster.md' +editPage: 'https://github.com/nodejs/node/blob/v18.9.0/doc/api/cluster.md' version: 'v18' --- - + - + - + Clusters of Node.js processes can be used to run multiple instances of Node.js that can distribute workloads among their application threads. When process @@ -29,7 +29,7 @@ import process from 'node:process'; const numCPUs = cpus().length; if (cluster.isPrimary) { - console.log(`Primary $process.pid is running`); + console.log(`Primary ${process.pid} is running`); // Fork workers. for (let i = 0; i < numCPUs; i++) { @@ -37,7 +37,7 @@ if (cluster.isPrimary) { } cluster.on('exit', (worker, code, signal) => { - console.log(`worker $worker.process.pid died`); + console.log(`worker ${worker.process.pid} died`); }); } else { // Workers can share any TCP connection @@ -47,7 +47,7 @@ if (cluster.isPrimary) { res.end('hello world\n'); }).listen(8000); - console.log(`Worker $process.pid started`); + console.log(`Worker ${process.pid} started`); } ``` @@ -58,7 +58,7 @@ const numCPUs = require('node:os').cpus().length; const process = require('node:process'); if (cluster.isPrimary) { - console.log(`Primary $process.pid is running`); + console.log(`Primary ${process.pid} is running`); // Fork workers. for (let i = 0; i < numCPUs; i++) { @@ -66,7 +66,7 @@ if (cluster.isPrimary) { } cluster.on('exit', (worker, code, signal) => { - console.log(`worker $worker.process.pid died`); + console.log(`worker ${worker.process.pid} died`); }); } else { // Workers can share any TCP connection @@ -76,7 +76,7 @@ if (cluster.isPrimary) { res.end('hello world\n'); }).listen(8000); - console.log(`Worker $process.pid started`); + console.log(`Worker ${process.pid} started`); } ``` @@ -95,7 +95,7 @@ On Windows, it is not yet possible to set up a named pipe server in a worker. ### How it works - + The worker processes are spawned using the [`child_process.fork()`][] method, so that they can communicate with the parent via IPC and pass server @@ -124,7 +124,7 @@ Because `server.listen()` hands off most of the work to the primary process, there are three cases where the behavior between a normal Node.js process and a cluster worker differs: -1. `server.listen({fd: 7})` Because the message is passed to the primary, +1. `server.listen(```{fd: 7}```)` Because the message is passed to the primary, file descriptor 7 **in the parent** will be listened on, and the handle passed to the worker, rather than listening to the worker's idea of what the number 7 file descriptor references. @@ -152,9 +152,9 @@ responsibility to manage the worker pool based on its own needs. Although a primary use case for the `node:cluster` module is networking, it can also be used for other use cases requiring worker processes. -### `Worker` +### `Worker` - + * Extends: [`EventEmitter`](/api/events#eventemitter) @@ -162,9 +162,9 @@ A `Worker` object contains all public information and method about a worker. In the primary it can be obtained using `cluster.workers`. In a worker it can be obtained using `cluster.worker`. -#### `'disconnect'` +#### `'disconnect'` - + Similar to the `cluster.on('disconnect')` event, but specific to this worker. @@ -174,17 +174,17 @@ cluster.fork().on('disconnect', () => { }); ``` -#### `'error'` +#### `'error'` - + This event is the same as the one provided by [`child_process.fork()`][]. Within a worker, `process.on('error')` may also be used. -#### `'exit'` +#### `'exit'` - + * `code` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The exit code, if it exited normally. * `signal` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The name of the signal (e.g. `'SIGHUP'`) that caused @@ -199,9 +199,9 @@ if (cluster.isPrimary) { const worker = cluster.fork(); worker.on('exit', (code, signal) => { if (signal) { - console.log(`worker was killed by signal: $signal`); + console.log(`worker was killed by signal: ${signal}`); } else if (code !== 0) { - console.log(`worker exited with error code: $code`); + console.log(`worker exited with error code: ${code}`); } else { console.log('worker success!'); } @@ -216,9 +216,9 @@ if (cluster.isPrimary) { const worker = cluster.fork(); worker.on('exit', (code, signal) => { if (signal) { - console.log(`worker was killed by signal: $signal`); + console.log(`worker was killed by signal: ${signal}`); } else if (code !== 0) { - console.log(`worker exited with error code: $code`); + console.log(`worker exited with error code: ${code}`); } else { console.log('worker success!'); } @@ -226,9 +226,9 @@ if (cluster.isPrimary) { } ``` -#### `'listening'` +#### `'listening'` - + * `address` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) @@ -248,9 +248,9 @@ cluster.fork().on('listening', (address) => { It is not emitted in the worker. -#### `'message'` +#### `'message'` - + * `message` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) * `handle` [`undefined`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type) | [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) @@ -275,7 +275,7 @@ if (cluster.isPrimary) { // Keep track of http requests let numReqs = 0; setInterval(() => { - console.log(`numReqs = $numReqs`); + console.log(`numReqs = ${numReqs}`); }, 1000); // Count requests @@ -318,7 +318,7 @@ if (cluster.isPrimary) { // Keep track of http requests let numReqs = 0; setInterval(() => { - console.log(`numReqs = $numReqs`); + console.log(`numReqs = ${numReqs}`); }, 1000); // Count requests @@ -351,9 +351,9 @@ if (cluster.isPrimary) { } ``` -#### `'online'` +#### `'online'` - + Similar to the `cluster.on('online')` event, but specific to this worker. @@ -365,9 +365,9 @@ cluster.fork().on('online', () => { It is not emitted in the worker. -#### `worker.disconnect()` +#### `worker.disconnect()` - + * Returns: [`cluster.Worker`](/api/cluster#worker) A reference to `worker`. @@ -430,9 +430,9 @@ if (cluster.isPrimary) { } ``` -#### `worker.exitedAfterDisconnect` +#### `worker.exitedAfterDisconnect` - + * [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) @@ -455,9 +455,9 @@ cluster.on('exit', (worker, code, signal) => { worker.kill(); ``` -#### `worker.id` +#### `worker.id` - + * [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) @@ -467,17 +467,17 @@ Each new worker is given its own unique id, this id is stored in the While a worker is alive, this is the key that indexes it in `cluster.workers`. -#### `worker.isConnected()` +#### `worker.isConnected()` - + This function returns `true` if the worker is connected to its primary via its IPC channel, `false` otherwise. A worker is connected to its primary after it has been created. It is disconnected after the `'disconnect'` event is emitted. -#### `worker.isDead()` +#### `worker.isDead()` - + This function returns `true` if the worker's process has terminated (either because of exiting or being signaled). Otherwise, it returns `false`. @@ -491,7 +491,7 @@ import process from 'node:process'; const numCPUs = cpus().length; if (cluster.isPrimary) { - console.log(`Primary $process.pid is running`); + console.log(`Primary ${process.pid} is running`); // Fork workers. for (let i = 0; i < numCPUs; i++) { @@ -509,7 +509,7 @@ if (cluster.isPrimary) { // Workers can share any TCP connection. In this case, it is an HTTP server. http.createServer((req, res) => { res.writeHead(200); - res.end(`Current process\n $process.pid`); + res.end(`Current process\n ${process.pid}`); process.kill(process.pid); }).listen(8000); } @@ -522,7 +522,7 @@ const numCPUs = require('node:os').cpus().length; const process = require('node:process'); if (cluster.isPrimary) { - console.log(`Primary $process.pid is running`); + console.log(`Primary ${process.pid} is running`); // Fork workers. for (let i = 0; i < numCPUs; i++) { @@ -540,15 +540,15 @@ if (cluster.isPrimary) { // Workers can share any TCP connection. In this case, it is an HTTP server. http.createServer((req, res) => { res.writeHead(200); - res.end(`Current process\n $process.pid`); + res.end(`Current process\n ${process.pid}`); process.kill(process.pid); }).listen(8000); } ``` -#### `worker.kill([signal])` +#### `worker.kill([signal])` - + * `signal` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) Name of the kill signal to send to the worker process. **Default:** `'SIGTERM'` @@ -565,9 +565,9 @@ This method is aliased as `worker.destroy()` for backwards compatibility. In a worker, `process.kill()` exists, but it is not this function; it is [`kill()`][]. -#### `worker.process` +#### `worker.process` - + * [`ChildProcess`](/api/child_process#childprocess) @@ -581,9 +581,9 @@ Workers will call `process.exit(0)` if the `'disconnect'` event occurs on `process` and `.exitedAfterDisconnect` is not `true`. This protects against accidental disconnection. -#### `worker.send(message[, sendHandle[, options]][, callback])` +#### `worker.send(message[, sendHandle[, options]][, callback])` - + * `message` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) * `sendHandle` [`Handle`](/api/net#serverlistenhandle-backlog-callback) @@ -618,9 +618,9 @@ if (cluster.isPrimary) { } ``` -### `'disconnect'` +### `'disconnect'` - + * `worker` [`cluster.Worker`](/api/cluster#worker) @@ -634,13 +634,13 @@ are long-living connections. ```js cluster.on('disconnect', (worker) => { - console.log(`The worker #$worker.id has disconnected`); + console.log(`The worker #${worker.id} has disconnected`); }); ``` -### `'exit'` +### `'exit'` - + * `worker` [`cluster.Worker`](/api/cluster#worker) * `code` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The exit code, if it exited normally. @@ -661,9 +661,9 @@ cluster.on('exit', (worker, code, signal) => { See [`child_process` event: `'exit'`][]. -### `'fork'` +### `'fork'` - + * `worker` [`cluster.Worker`](/api/cluster#worker) @@ -688,9 +688,9 @@ cluster.on('exit', (worker, code, signal) => { }); ``` -### `'listening'` +### `'listening'` - + * `worker` [`cluster.Worker`](/api/cluster#worker) * `address` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) @@ -707,7 +707,7 @@ worker is listening on more than one address. ```js cluster.on('listening', (worker, address) => { console.log( - `A worker is now connected to $address.address:$address.port`); + `A worker is now connected to ${address.address}:${address.port}`); }); ``` @@ -718,9 +718,9 @@ The `addressType` is one of: * `-1` (Unix domain socket) * `'udp4'` or `'udp6'` (UDPv4 or UDPv6) -### `'message'` +### `'message'` - + * `worker` [`cluster.Worker`](/api/cluster#worker) * `message` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) @@ -730,9 +730,9 @@ Emitted when the cluster primary receives a message from any worker. See [`child_process` event: `'message'`][]. -### `'online'` +### `'online'` - + * `worker` [`cluster.Worker`](/api/cluster#worker) @@ -747,9 +747,9 @@ cluster.on('online', (worker) => { }); ``` -### `'setup'` +### `'setup'` - + * `settings` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) @@ -761,9 +761,9 @@ The `settings` object is the `cluster.settings` object at the time If accuracy is important, use `cluster.settings`. -### `cluster.disconnect([callback])` +### `cluster.disconnect([callback])` - + * `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) Called when all workers are disconnected and handles are closed. @@ -778,9 +778,9 @@ finished. This can only be called from the primary process. -### `cluster.fork([env])` +### `cluster.fork([env])` - + * `env` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) Key/value pairs to add to worker process environment. * Returns: [`cluster.Worker`](/api/cluster#worker) @@ -789,15 +789,15 @@ Spawn a new worker process. This can only be called from the primary process. -### `cluster.isMaster` +### `cluster.isMaster` - + Deprecated alias for [`cluster.isPrimary`][]. -### `cluster.isPrimary` +### `cluster.isPrimary` - + * [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) @@ -805,17 +805,17 @@ True if the process is a primary. This is determined by the `process.env.NODE_UNIQUE_ID`. If `process.env.NODE_UNIQUE_ID` is undefined, then `isPrimary` is `true`. -### `cluster.isWorker` +### `cluster.isWorker` - + * [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) True if the process is not a primary (it is the negation of `cluster.isPrimary`). -### `cluster.schedulingPolicy` +### `cluster.schedulingPolicy` - + The scheduling policy, either `cluster.SCHED_RR` for round-robin or `cluster.SCHED_NONE` to leave it to the operating system. This is a @@ -830,9 +830,9 @@ distribute IOCP handles without incurring a large performance hit. `NODE_CLUSTER_SCHED_POLICY` environment variable. Valid values are `'rr'` and `'none'`. -### `cluster.settings` +### `cluster.settings` - + * [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) * `execArgv` string\[] List of string arguments passed to the Node.js @@ -865,15 +865,15 @@ contain the settings, including the default values. This object is not intended to be changed or set manually. -### `cluster.setupMaster([settings])` +### `cluster.setupMaster([settings])` - + Deprecated alias for [`.setupPrimary()`][]. -### `cluster.setupPrimary([settings])` +### `cluster.setupPrimary([settings])` - + * `settings` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) See [`cluster.settings`][]. @@ -923,9 +923,9 @@ cluster.fork(); // http worker This can only be called from the primary process. -### `cluster.worker` +### `cluster.worker` - + * [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) @@ -939,7 +939,7 @@ if (cluster.isPrimary) { cluster.fork(); cluster.fork(); } else if (cluster.isWorker) { - console.log(`I am worker #$cluster.worker.id`); + console.log(`I am worker #${cluster.worker.id}`); } ``` @@ -951,13 +951,13 @@ if (cluster.isPrimary) { cluster.fork(); cluster.fork(); } else if (cluster.isWorker) { - console.log(`I am worker #$cluster.worker.id`); + console.log(`I am worker #${cluster.worker.id}`); } ``` -### `cluster.workers` +### `cluster.workers` - + * [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) diff --git a/content/api/v18/console.en.md b/content/api/v18/console.en.md index a4c6608333..1bd5f01a12 100644 --- a/content/api/v18/console.en.md +++ b/content/api/v18/console.en.md @@ -2,15 +2,15 @@ title: 'console' displayTitle: 'Console' category: 'api' -editPage: 'https://github.com/nodejs/node/blob/v18.8.0/doc/api/console.md' +editPage: 'https://github.com/nodejs/node/blob/v18.9.0/doc/api/console.md' version: 'v18' --- - + - + - + The `node:console` module provides a simple debugging console that is similar to the JavaScript console mechanism provided by web browsers. @@ -47,7 +47,7 @@ console.error(new Error('Whoops, something bad happened')); // at node:internal/main/eval_string:23:3 const name = 'Will Robinson'; -console.warn(`Danger $name! Danger!`); +console.warn(`Danger ${name}! Danger!`); // Prints: Danger Will Robinson! Danger!, to stderr ``` @@ -66,15 +66,15 @@ myConsole.error(new Error('Whoops, something bad happened')); // Prints: [Error: Whoops, something bad happened], to err const name = 'Will Robinson'; -myConsole.warn(`Danger $name! Danger!`); +myConsole.warn(`Danger ${name}! Danger!`); // Prints: Danger Will Robinson! Danger!, to err ``` -### `Console` +### `Console` - + - + The `Console` class can be used to create a simple logger with configurable output streams and can be accessed using either `require('node:console').Console` @@ -88,11 +88,11 @@ const { Console } = require('node:console'); const { Console } = console; ``` -#### `new Console(stdout[, stderr][, ignoreErrors])` +#### `new Console(stdout[, stderr][, ignoreErrors])` -#### `new Console(options)` +#### `new Console(options)` - + * `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) * `stdout` [`stream.Writable`](/api/stream#streamwritable) @@ -133,9 +133,9 @@ The global `console` is a special `Console` whose output is sent to new Console({ stdout: process.stdout, stderr: process.stderr }); ``` -#### `console.assert(value[, ...message])` +#### `console.assert(value[, ...message])` - + * `value` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) The value tested for being truthy. * `...message` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) All arguments besides `value` are used as error message. @@ -157,9 +157,9 @@ console.assert(); // Assertion failed ``` -#### `console.clear()` +#### `console.clear()` - + When `stdout` is a TTY, calling `console.clear()` will attempt to clear the TTY. When `stdout` is not a TTY, this method does nothing. @@ -170,9 +170,9 @@ operates similarly to the `clear` shell command. On Windows, `console.clear()` will clear only the output in the current terminal viewport for the Node.js binary. -#### `console.count([label])` +#### `console.count([label])` - + * `label` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The display label for the counter. **Default:** `'default'`. @@ -203,9 +203,9 @@ undefined > ``` -#### `console.countReset([label])` +#### `console.countReset([label])` - + * `label` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The display label for the counter. **Default:** `'default'`. @@ -225,18 +225,18 @@ undefined > ``` -#### `console.debug(data[, ...args])` +#### `console.debug(data[, ...args])` - + * `data` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) * `...args` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) The `console.debug()` function is an alias for [`console.log()`][]. -#### `console.dir(obj[, options])` +#### `console.dir(obj[, options])` - + * `obj` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) * `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) @@ -252,18 +252,18 @@ The `console.debug()` function is an alias for [`console.log()`][]. Uses [`util.inspect()`][] on `obj` and prints the resulting string to `stdout`. This function bypasses any custom `inspect()` function defined on `obj`. -#### `console.dirxml(...data)` +#### `console.dirxml(...data)` - + * `...data` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) This method calls `console.log()` passing it the arguments received. This method does not produce any XML formatting. -#### `console.error([data][, ...args])` +#### `console.error([data][, ...args])` - + * `data` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) * `...args` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) @@ -285,9 +285,9 @@ If formatting elements (e.g. `%d`) are not found in the first string then [`util.inspect()`][] is called on each argument and the resulting string values are concatenated. See [`util.format()`][] for more information. -#### `console.group([...label])` +#### `console.group([...label])` - + * `...label` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) @@ -297,31 +297,31 @@ length. If one or more `label`s are provided, those are printed first without the additional indentation. -#### `console.groupCollapsed()` +#### `console.groupCollapsed()` - + An alias for [`console.group()`][]. -#### `console.groupEnd()` +#### `console.groupEnd()` - + Decreases indentation of subsequent lines by spaces for `groupIndentation` length. -#### `console.info([data][, ...args])` +#### `console.info([data][, ...args])` - + * `data` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) * `...args` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) The `console.info()` function is an alias for [`console.log()`][]. -#### `console.log([data][, ...args])` +#### `console.log([data][, ...args])` - + * `data` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) * `...args` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) @@ -341,9 +341,9 @@ console.log('count:', count); See [`util.format()`][] for more information. -#### `console.table(tabularData[, properties])` +#### `console.table(tabularData[, properties])` - + * `tabularData` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) * `properties` string\[] Alternate properties for constructing the table. @@ -377,9 +377,9 @@ console.table([{ a: 1, b: 'Y' }, { a: 'Z', b: 2 }], ['a']); // └─────────┴─────┘ ``` -#### `console.time([label])` +#### `console.time([label])` - + * `label` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) **Default:** `'default'` @@ -389,9 +389,9 @@ are identified by a unique `label`. Use the same `label` when calling suitable time units to `stdout`. For example, if the elapsed time is 3869ms, `console.timeEnd()` displays "3.869s". -#### `console.timeEnd([label])` +#### `console.timeEnd([label])` - + * `label` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) **Default:** `'default'` @@ -405,9 +405,9 @@ console.timeEnd('bunch-of-stuff'); // Prints: bunch-of-stuff: 225.438ms ``` -#### `console.timeLog([label][, ...data])` +#### `console.timeLog([label][, ...data])` - + * `label` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) **Default:** `'default'` * `...data` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) @@ -424,9 +424,9 @@ doExpensiveProcess2(value); console.timeEnd('process'); ``` -#### `console.trace([message][, ...args])` +#### `console.trace([message][, ...args])` - + * `message` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) * `...args` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) @@ -450,9 +450,9 @@ console.trace('Show me'); // at REPLServer.Interface._ttyWrite (readline.js:826:14) ``` -#### `console.warn([data][, ...args])` +#### `console.warn([data][, ...args])` - + * `data` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) * `...args` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) @@ -465,9 +465,9 @@ The following methods are exposed by the V8 engine in the general API but do not display anything unless used in conjunction with the [inspector][] (`--inspect` flag). -#### `console.profile([label])` +#### `console.profile([label])` - + * `label` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) @@ -483,9 +483,9 @@ console.profileEnd('MyLabel'); // Adds the profile 'MyLabel' to the Profiles panel of the inspector. ``` -#### `console.profileEnd([label])` +#### `console.profileEnd([label])` - + * `label` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) @@ -497,9 +497,9 @@ the report to the **Profiles** panel of the inspector. See If this method is called without a label, the most recently started profile is stopped. -#### `console.timeStamp([label])` +#### `console.timeStamp([label])` - + * `label` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) diff --git a/content/api/v18/corepack.en.md b/content/api/v18/corepack.en.md index 30501f4035..78b31878c3 100644 --- a/content/api/v18/corepack.en.md +++ b/content/api/v18/corepack.en.md @@ -2,17 +2,17 @@ title: 'corepack' displayTitle: 'Corepack' category: 'api' -editPage: 'https://github.com/nodejs/node/blob/v18.8.0/doc/api/corepack.md' +editPage: 'https://github.com/nodejs/node/blob/v18.9.0/doc/api/corepack.md' version: 'v18' --- - + - + - + - + _[Corepack][]_ is an experimental tool to help with managing versions of your package managers. It exposes binary proxies for diff --git a/content/api/v18/crypto.en.md b/content/api/v18/crypto.en.md index bf5246bc50..d89de26b29 100644 --- a/content/api/v18/crypto.en.md +++ b/content/api/v18/crypto.en.md @@ -2,15 +2,15 @@ title: 'crypto' displayTitle: 'Crypto' category: 'api' -editPage: 'https://github.com/nodejs/node/blob/v18.8.0/doc/api/crypto.md' +editPage: 'https://github.com/nodejs/node/blob/v18.9.0/doc/api/crypto.md' version: 'v18' --- - + - + - + The `node:crypto` module provides cryptographic functionality that includes a set of wrappers for OpenSSL's hash, HMAC, cipher, decipher, sign, and verify @@ -77,9 +77,9 @@ try { } ``` -### `Certificate` +### `Certificate` - + SPKAC is a Certificate Signing Request mechanism originally implemented by Netscape and was specified formally as part of [HTML5's `keygen` element][]. @@ -93,7 +93,7 @@ data. The most common usage is handling output generated by the HTML5 #### Static method: `Certificate.exportChallenge(spkac[, encoding])` - + * `spkac` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) | [`Buffer`](/api/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) * `encoding` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The [encoding][] of the `spkac` string. @@ -118,7 +118,7 @@ console.log(challenge.toString('utf8')); #### Static method: `Certificate.exportPublicKey(spkac[, encoding])` - + * `spkac` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) | [`Buffer`](/api/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) * `encoding` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The [encoding][] of the `spkac` string. @@ -143,7 +143,7 @@ console.log(publicKey); #### Static method: `Certificate.verifySpkac(spkac[, encoding])` - + * `spkac` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) | [`Buffer`](/api/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) * `encoding` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The [encoding][] of the `spkac` string. @@ -170,12 +170,12 @@ console.log(Certificate.verifySpkac(Buffer.from(spkac))); #### Legacy API - + As a legacy interface, it is possible to create new instances of the `crypto.Certificate` class as illustrated in the examples below. -##### `new crypto.Certificate()` +##### `new crypto.Certificate()` Instances of the `Certificate` class can be created using the `new` keyword or by calling `crypto.Certificate()` as a function: @@ -194,9 +194,9 @@ const cert1 = new Certificate(); const cert2 = Certificate(); ``` -##### `certificate.exportChallenge(spkac[, encoding])` +##### `certificate.exportChallenge(spkac[, encoding])` - + * `spkac` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) | [`Buffer`](/api/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) * `encoding` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The [encoding][] of the `spkac` string. @@ -221,9 +221,9 @@ console.log(challenge.toString('utf8')); // Prints: the challenge as a UTF8 string ``` -##### `certificate.exportPublicKey(spkac[, encoding])` +##### `certificate.exportPublicKey(spkac[, encoding])` - + * `spkac` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) | [`Buffer`](/api/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) * `encoding` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The [encoding][] of the `spkac` string. @@ -248,9 +248,9 @@ console.log(publicKey); // Prints: the public key as ``` -##### `certificate.verifySpkac(spkac[, encoding])` +##### `certificate.verifySpkac(spkac[, encoding])` - + * `spkac` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) | [`Buffer`](/api/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) * `encoding` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The [encoding][] of the `spkac` string. @@ -277,9 +277,9 @@ console.log(cert.verifySpkac(Buffer.from(spkac))); // Prints: true or false ``` -### `Cipher` +### `Cipher` - + * Extends: [`stream.Transform`](/api/stream#streamtransform) @@ -499,12 +499,12 @@ scrypt(password, 'salt', 24, (err, key) => { }); ``` -#### `cipher.final([outputEncoding])` +#### `cipher.final([outputEncoding])` - + * `outputEncoding` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The [encoding][] of the return value. -* Returns: {Buffer | string} Any remaining enciphered contents. +* Returns: [`Buffer`](/api/buffer#buffer) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) Any remaining enciphered contents. If `outputEncoding` is specified, a string is returned. If an `outputEncoding` is not provided, a [`Buffer`][] is returned. @@ -512,9 +512,9 @@ Once the `cipher.final()` method has been called, the `Cipher` object can no longer be used to encrypt data. Attempts to call `cipher.final()` more than once will result in an error being thrown. -#### `cipher.getAuthTag()` +#### `cipher.getAuthTag()` - + * Returns: [`Buffer`](/api/buffer#buffer) When using an authenticated encryption mode (`GCM`, `CCM`, `OCB`, and `chacha20-poly1305` are currently supported), the @@ -528,9 +528,9 @@ been completed using the [`cipher.final()`][] method. If the `authTagLength` option was set during the `cipher` instance's creation, this function will return exactly `authTagLength` bytes. -#### `cipher.setAAD(buffer[, options])` +#### `cipher.setAAD(buffer[, options])` - + * `buffer` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) | [`Buffer`](/api/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) * `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) [`stream.transform` options][] @@ -549,9 +549,9 @@ length of the plaintext in bytes. See [CCM mode][]. The `cipher.setAAD()` method must be called before [`cipher.update()`][]. -#### `cipher.setAutoPadding([autoPadding])` +#### `cipher.setAutoPadding([autoPadding])` - + * `autoPadding` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) **Default:** `true` * Returns: [`Cipher`](/api/crypto#cipher) for method chaining. @@ -568,14 +568,14 @@ using `0x0` instead of PKCS padding. The `cipher.setAutoPadding()` method must be called before [`cipher.final()`][]. -#### `cipher.update(data[, inputEncoding][, outputEncoding])` +#### `cipher.update(data[, inputEncoding][, outputEncoding])` - + * `data` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) * `inputEncoding` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The [encoding][] of the data. * `outputEncoding` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The [encoding][] of the return value. -* Returns: {Buffer | string} +* Returns: [`Buffer`](/api/buffer#buffer) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) Updates the cipher with `data`. If the `inputEncoding` argument is given, the `data` @@ -593,9 +593,9 @@ The `cipher.update()` method can be called multiple times with new data until [`cipher.final()`][] is called. Calling `cipher.update()` after [`cipher.final()`][] will result in an error being thrown. -### `Decipher` +### `Decipher` - + * Extends: [`stream.Transform`](/api/stream#streamtransform) @@ -793,12 +793,12 @@ console.log(decrypted); // Prints: some clear text data ``` -#### `decipher.final([outputEncoding])` +#### `decipher.final([outputEncoding])` - + * `outputEncoding` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The [encoding][] of the return value. -* Returns: {Buffer | string} Any remaining deciphered contents. +* Returns: [`Buffer`](/api/buffer#buffer) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) Any remaining deciphered contents. If `outputEncoding` is specified, a string is returned. If an `outputEncoding` is not provided, a [`Buffer`][] is returned. @@ -806,9 +806,9 @@ Once the `decipher.final()` method has been called, the `Decipher` object can no longer be used to decrypt data. Attempts to call `decipher.final()` more than once will result in an error being thrown. -#### `decipher.setAAD(buffer[, options])` +#### `decipher.setAAD(buffer[, options])` - + * `buffer` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) | [`Buffer`](/api/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) * `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) [`stream.transform` options][] @@ -830,9 +830,9 @@ The `decipher.setAAD()` method must be called before [`decipher.update()`][]. When passing a string as the `buffer`, please consider [caveats when using strings as inputs to cryptographic APIs][]. -#### `decipher.setAuthTag(buffer[, encoding])` +#### `decipher.setAuthTag(buffer[, encoding])` - + * `buffer` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) * `encoding` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) String encoding to use when `buffer` is a string. @@ -855,9 +855,9 @@ for `CCM` mode or before [`decipher.final()`][] for `GCM` and `OCB` modes and When passing a string as the authentication tag, please consider [caveats when using strings as inputs to cryptographic APIs][]. -#### `decipher.setAutoPadding([autoPadding])` +#### `decipher.setAutoPadding([autoPadding])` - + * `autoPadding` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) **Default:** `true` * Returns: [`Decipher`](/api/crypto#decipher) for method chaining. @@ -872,14 +872,14 @@ multiple of the ciphers block size. The `decipher.setAutoPadding()` method must be called before [`decipher.final()`][]. -#### `decipher.update(data[, inputEncoding][, outputEncoding])` +#### `decipher.update(data[, inputEncoding][, outputEncoding])` - + * `data` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) * `inputEncoding` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The [encoding][] of the `data` string. * `outputEncoding` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The [encoding][] of the return value. -* Returns: {Buffer | string} +* Returns: [`Buffer`](/api/buffer#buffer) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) Updates the decipher with `data`. If the `inputEncoding` argument is given, the `data` @@ -896,9 +896,9 @@ The `decipher.update()` method can be called multiple times with new data until [`decipher.final()`][] is called. Calling `decipher.update()` after [`decipher.final()`][] will result in an error being thrown. -### `DiffieHellman` +### `DiffieHellman` - + The `DiffieHellman` class is a utility for creating Diffie-Hellman key exchanges. @@ -952,14 +952,14 @@ const bobSecret = bob.computeSecret(aliceKey); assert.strictEqual(aliceSecret.toString('hex'), bobSecret.toString('hex')); ``` -#### `diffieHellman.computeSecret(otherPublicKey[, inputEncoding][, outputEncoding])` +#### `diffieHellman.computeSecret(otherPublicKey[, inputEncoding][, outputEncoding])` - + * `otherPublicKey` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) | [`Buffer`](/api/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) * `inputEncoding` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The [encoding][] of an `otherPublicKey` string. * `outputEncoding` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The [encoding][] of the return value. -* Returns: {Buffer | string} +* Returns: [`Buffer`](/api/buffer#buffer) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) Computes the shared secret using `otherPublicKey` as the other party's public key and returns the computed shared secret. The supplied @@ -972,12 +972,12 @@ provided, `otherPublicKey` is expected to be a [`Buffer`][], If `outputEncoding` is given a string is returned; otherwise, a [`Buffer`][] is returned. -#### `diffieHellman.generateKeys([encoding])` +#### `diffieHellman.generateKeys([encoding])` - + * `encoding` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The [encoding][] of the return value. -* Returns: {Buffer | string} +* Returns: [`Buffer`](/api/buffer#buffer) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) Generates private and public Diffie-Hellman key values, and returns the public key in the specified `encoding`. This key should be @@ -985,53 +985,53 @@ transferred to the other party. If `encoding` is provided a string is returned; otherwise a [`Buffer`][] is returned. -#### `diffieHellman.getGenerator([encoding])` +#### `diffieHellman.getGenerator([encoding])` - + * `encoding` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The [encoding][] of the return value. -* Returns: {Buffer | string} +* Returns: [`Buffer`](/api/buffer#buffer) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) Returns the Diffie-Hellman generator in the specified `encoding`. If `encoding` is provided a string is returned; otherwise a [`Buffer`][] is returned. -#### `diffieHellman.getPrime([encoding])` +#### `diffieHellman.getPrime([encoding])` - + * `encoding` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The [encoding][] of the return value. -* Returns: {Buffer | string} +* Returns: [`Buffer`](/api/buffer#buffer) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) Returns the Diffie-Hellman prime in the specified `encoding`. If `encoding` is provided a string is returned; otherwise a [`Buffer`][] is returned. -#### `diffieHellman.getPrivateKey([encoding])` +#### `diffieHellman.getPrivateKey([encoding])` - + * `encoding` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The [encoding][] of the return value. -* Returns: {Buffer | string} +* Returns: [`Buffer`](/api/buffer#buffer) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) Returns the Diffie-Hellman private key in the specified `encoding`. If `encoding` is provided a string is returned; otherwise a [`Buffer`][] is returned. -#### `diffieHellman.getPublicKey([encoding])` +#### `diffieHellman.getPublicKey([encoding])` - + * `encoding` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The [encoding][] of the return value. -* Returns: {Buffer | string} +* Returns: [`Buffer`](/api/buffer#buffer) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) Returns the Diffie-Hellman public key in the specified `encoding`. If `encoding` is provided a string is returned; otherwise a [`Buffer`][] is returned. -#### `diffieHellman.setPrivateKey(privateKey[, encoding])` +#### `diffieHellman.setPrivateKey(privateKey[, encoding])` - + * `privateKey` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) | [`Buffer`](/api/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) * `encoding` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The [encoding][] of the `privateKey` string. @@ -1041,9 +1041,9 @@ Sets the Diffie-Hellman private key. If the `encoding` argument is provided, to be a string. If no `encoding` is provided, `privateKey` is expected to be a [`Buffer`][], `TypedArray`, or `DataView`. -#### `diffieHellman.setPublicKey(publicKey[, encoding])` +#### `diffieHellman.setPublicKey(publicKey[, encoding])` - + * `publicKey` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) | [`Buffer`](/api/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) * `encoding` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The [encoding][] of the `publicKey` string. @@ -1053,9 +1053,9 @@ Sets the Diffie-Hellman public key. If the `encoding` argument is provided, to be a string. If no `encoding` is provided, `publicKey` is expected to be a [`Buffer`][], `TypedArray`, or `DataView`. -#### `diffieHellman.verifyError` +#### `diffieHellman.verifyError` - + A bit field containing any warnings and/or errors resulting from a check performed during initialization of the `DiffieHellman` object. @@ -1067,9 +1067,9 @@ The following values are valid for this property (as defined in `node:constants` * `DH_UNABLE_TO_CHECK_GENERATOR` * `DH_NOT_SUITABLE_GENERATOR` -### `DiffieHellmanGroup` +### `DiffieHellmanGroup` - + The `DiffieHellmanGroup` class takes a well-known modp group as its argument. It works the same as `DiffieHellman`, except that it does not allow changing @@ -1097,9 +1097,9 @@ The following groups are supported: * `'modp17'` (6144 bits, [RFC 3526][] Section 6) * `'modp18'` (8192 bits, [RFC 3526][] Section 7) -### `ECDH` +### `ECDH` - + The `ECDH` class is a utility for creating Elliptic Curve Diffie-Hellman (ECDH) key exchanges. @@ -1155,14 +1155,14 @@ assert.strictEqual(aliceSecret.toString('hex'), bobSecret.toString('hex')); #### Static method: `ECDH.convertKey(key, curve[, inputEncoding[, outputEncoding[, format]]])` - + * `key` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) | [`Buffer`](/api/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) * `curve` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) * `inputEncoding` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The [encoding][] of the `key` string. * `outputEncoding` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The [encoding][] of the return value. * `format` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) **Default:** `'uncompressed'` -* Returns: {Buffer | string} +* Returns: [`Buffer`](/api/buffer#buffer) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) Converts the EC Diffie-Hellman public key specified by `key` and `curve` to the format specified by `format`. The `format` argument specifies point encoding @@ -1224,14 +1224,14 @@ const uncompressedKey = ECDH.convertKey(compressedKey, console.log(uncompressedKey === ecdh.getPublicKey('hex')); ``` -#### `ecdh.computeSecret(otherPublicKey[, inputEncoding][, outputEncoding])` +#### `ecdh.computeSecret(otherPublicKey[, inputEncoding][, outputEncoding])` - + * `otherPublicKey` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) | [`Buffer`](/api/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) * `inputEncoding` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The [encoding][] of the `otherPublicKey` string. * `outputEncoding` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The [encoding][] of the return value. -* Returns: {Buffer | string} +* Returns: [`Buffer`](/api/buffer#buffer) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) Computes the shared secret using `otherPublicKey` as the other party's public key and returns the computed shared secret. The supplied @@ -1250,13 +1250,13 @@ lies outside of the elliptic curve. Since `otherPublicKey` is usually supplied from a remote user over an insecure network, be sure to handle this exception accordingly. -#### `ecdh.generateKeys([encoding[, format]])` +#### `ecdh.generateKeys([encoding[, format]])` - + * `encoding` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The [encoding][] of the return value. * `format` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) **Default:** `'uncompressed'` -* Returns: {Buffer | string} +* Returns: [`Buffer`](/api/buffer#buffer) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) Generates private and public EC Diffie-Hellman key values, and returns the public key in the specified `format` and `encoding`. This key should be @@ -1269,23 +1269,23 @@ The `format` argument specifies point encoding and can be `'compressed'` or If `encoding` is provided a string is returned; otherwise a [`Buffer`][] is returned. -#### `ecdh.getPrivateKey([encoding])` +#### `ecdh.getPrivateKey([encoding])` - + * `encoding` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The [encoding][] of the return value. -* Returns: {Buffer | string} The EC Diffie-Hellman in the specified `encoding`. +* Returns: [`Buffer`](/api/buffer#buffer) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The EC Diffie-Hellman in the specified `encoding`. If `encoding` is specified, a string is returned; otherwise a [`Buffer`][] is returned. -#### `ecdh.getPublicKey([encoding][, format])` +#### `ecdh.getPublicKey([encoding][, format])` - + * `encoding` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The [encoding][] of the return value. * `format` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) **Default:** `'uncompressed'` -* Returns: {Buffer | string} The EC Diffie-Hellman public key in the specified +* Returns: [`Buffer`](/api/buffer#buffer) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The EC Diffie-Hellman public key in the specified `encoding` and `format`. The `format` argument specifies point encoding and can be `'compressed'` or @@ -1295,9 +1295,9 @@ The `format` argument specifies point encoding and can be `'compressed'` or If `encoding` is specified, a string is returned; otherwise a [`Buffer`][] is returned. -#### `ecdh.setPrivateKey(privateKey[, encoding])` +#### `ecdh.setPrivateKey(privateKey[, encoding])` - + * `privateKey` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) | [`Buffer`](/api/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) * `encoding` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The [encoding][] of the `privateKey` string. @@ -1311,11 +1311,11 @@ If `privateKey` is not valid for the curve specified when the `ECDH` object was created, an error is thrown. Upon setting the private key, the associated public point (key) is also generated and set in the `ECDH` object. -#### `ecdh.setPublicKey(publicKey[, encoding])` +#### `ecdh.setPublicKey(publicKey[, encoding])` - + - + * `publicKey` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) | [`Buffer`](/api/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) * `encoding` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The [encoding][] of the `publicKey` string. @@ -1387,9 +1387,9 @@ const bobSecret = bob.computeSecret(alice.getPublicKey(), null, 'hex'); console.log(aliceSecret === bobSecret); ``` -### `Hash` +### `Hash` - + * Extends: [`stream.Transform`](/api/stream#streamtransform) @@ -1502,9 +1502,9 @@ console.log(hash.digest('hex')); // 6a2da20943931e9834fc12cfe5bb47bbd9ae43489a30726962b576f4e3993e50 ``` -#### `hash.copy([options])` +#### `hash.copy([options])` - + * `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) [`stream.transform` options][] * Returns: [`Hash`](/api/crypto#hash) @@ -1559,12 +1559,12 @@ console.log(hash.copy().digest('hex')); // Etc. ``` -#### `hash.digest([encoding])` +#### `hash.digest([encoding])` - + * `encoding` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The [encoding][] of the return value. -* Returns: {Buffer | string} +* Returns: [`Buffer`](/api/buffer#buffer) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) Calculates the digest of all of the data passed to be hashed (using the [`hash.update()`][] method). @@ -1574,9 +1574,9 @@ a [`Buffer`][] is returned. The `Hash` object can not be used again after `hash.digest()` method has been called. Multiple calls will cause an error to be thrown. -#### `hash.update(data[, inputEncoding])` +#### `hash.update(data[, inputEncoding])` - + * `data` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) * `inputEncoding` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The [encoding][] of the `data` string. @@ -1589,9 +1589,9 @@ encoding of `'utf8'` is enforced. If `data` is a [`Buffer`][], `TypedArray`, or This can be called many times with new data as it is streamed. -### `Hmac` +### `Hmac` - + * Extends: [`stream.Transform`](/api/stream#streamtransform) @@ -1710,12 +1710,12 @@ console.log(hmac.digest('hex')); // 7fd04df92f636fd450bc841c9418e5825c17f33ad9c87c518115a45971f7f77e ``` -#### `hmac.digest([encoding])` +#### `hmac.digest([encoding])` - + * `encoding` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The [encoding][] of the return value. -* Returns: {Buffer | string} +* Returns: [`Buffer`](/api/buffer#buffer) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) Calculates the HMAC digest of all of the data passed using [`hmac.update()`][]. If `encoding` is @@ -1724,9 +1724,9 @@ provided a string is returned; otherwise a [`Buffer`][] is returned; The `Hmac` object can not be used again after `hmac.digest()` has been called. Multiple calls to `hmac.digest()` will result in an error being thrown. -#### `hmac.update(data[, inputEncoding])` +#### `hmac.update(data[, inputEncoding])` - + * `data` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) * `inputEncoding` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The [encoding][] of the `data` string. @@ -1739,9 +1739,9 @@ encoding of `'utf8'` is enforced. If `data` is a [`Buffer`][], `TypedArray`, or This can be called many times with new data as it is streamed. -### `KeyObject` +### `KeyObject` - + Node.js uses a `KeyObject` class to represent a symmetric or asymmetric key, and each kind of key exposes different functions. The @@ -1759,7 +1759,7 @@ be listed in the `transferList` argument. #### Static method: `KeyObject.from(key)` - + * `key` [`CryptoKey`](/api/webcrypto#cryptokey) * Returns: [`KeyObject`](/api/crypto#keyobject) @@ -1802,9 +1802,9 @@ const { })(); ``` -#### `keyObject.asymmetricKeyDetails` +#### `keyObject.asymmetricKeyDetails` - + * [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) * `modulusLength`: [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Key size in bits (RSA, DSA). @@ -1827,9 +1827,9 @@ set. Other key details might be exposed via this API using additional attributes. -#### `keyObject.asymmetricKeyType` +#### `keyObject.asymmetricKeyType` - + * [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) @@ -1849,12 +1849,12 @@ types are: This property is `undefined` for unrecognized `KeyObject` types and symmetric keys. -#### `keyObject.export([options])` +#### `keyObject.export([options])` - + * `options`: [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) -* Returns: {string | Buffer | Object} +* Returns: [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) For symmetric keys, the following encoding options can be used: @@ -1873,7 +1873,7 @@ For private keys, the following encoding options can be used: * `cipher`: [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) If specified, the private key will be encrypted with the given `cipher` and `passphrase` using PKCS#5 v2.0 password based encryption. -* `passphrase`: {string | Buffer} The passphrase to use for encryption, see +* `passphrase`: [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) The passphrase to use for encryption, see `cipher`. The result type depends on the selected encoding format, when PEM the @@ -1893,9 +1893,9 @@ encryption mechanism, PEM-level encryption is not supported when encrypting a PKCS#8 key. See [RFC 5208][] for PKCS#8 encryption and [RFC 1421][] for PKCS#1 and SEC1 encryption. -#### `keyObject.equals(otherKeyObject)` +#### `keyObject.equals(otherKeyObject)` - + * `otherKeyObject`: [`KeyObject`](/api/crypto#keyobject) A `KeyObject` with which to compare `keyObject`. @@ -1905,18 +1905,18 @@ Returns `true` or `false` depending on whether the keys have exactly the same type, value, and parameters. This method is not [constant time](https://en.wikipedia.org/wiki/Timing_attack). -#### `keyObject.symmetricKeySize` +#### `keyObject.symmetricKeySize` - + * [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) For secret keys, this property represents the size of the key in bytes. This property is `undefined` for asymmetric keys. -#### `keyObject.type` +#### `keyObject.type` - + * [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) @@ -1924,9 +1924,9 @@ Depending on the type of this `KeyObject`, this property is either `'secret'` for secret (symmetric) keys, `'public'` for public (asymmetric) keys or `'private'` for private (asymmetric) keys. -### `Sign` +### `Sign` - + * Extends: [`stream.Writable`](/api/stream#streamwritable) @@ -2038,9 +2038,9 @@ console.log(verify.verify(publicKey, signature)); // Prints: true ``` -#### `sign.sign(privateKey[, outputEncoding])` +#### `sign.sign(privateKey[, outputEncoding])` - + @@ -2049,7 +2049,7 @@ console.log(verify.verify(publicKey, signature)); * `padding` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) * `saltLength` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) * `outputEncoding` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The [encoding][] of the return value. -* Returns: {Buffer | string} +* Returns: [`Buffer`](/api/buffer#buffer) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) @@ -2085,9 +2085,9 @@ is returned. The `Sign` object can not be again used after `sign.sign()` method has been called. Multiple calls to `sign.sign()` will result in an error being thrown. -#### `sign.update(data[, inputEncoding])` +#### `sign.update(data[, inputEncoding])` - + * `data` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) * `inputEncoding` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The [encoding][] of the `data` string. @@ -2100,9 +2100,9 @@ encoding of `'utf8'` is enforced. If `data` is a [`Buffer`][], `TypedArray`, or This can be called many times with new data as it is streamed. -### `Verify` +### `Verify` - + * Extends: [`stream.Writable`](/api/stream#streamwritable) @@ -2119,9 +2119,9 @@ The [`crypto.createVerify()`][] method is used to create `Verify` instances. See [`Sign`][] for examples. -#### `verify.update(data[, inputEncoding])` +#### `verify.update(data[, inputEncoding])` - + * `data` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) * `inputEncoding` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The [encoding][] of the `data` string. @@ -2134,9 +2134,9 @@ encoding of `'utf8'` is enforced. If `data` is a [`Buffer`][], `TypedArray`, or This can be called many times with new data as it is streamed. -#### `verify.verify(object, signature[, signatureEncoding])` +#### `verify.verify(object, signature[, signatureEncoding])` - + @@ -2189,9 +2189,9 @@ thrown. Because public keys can be derived from private keys, a private key may be passed instead of a public key. -### `X509Certificate` +### `X509Certificate` - + Encapsulates an X509 certificate and provides read-only access to its information. @@ -2212,23 +2212,23 @@ const x509 = new X509Certificate('{... pem encoded cert ...}'); console.log(x509.subject); ``` -#### `new X509Certificate(buffer)` +#### `new X509Certificate(buffer)` - + * `buffer` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`Buffer`](/api/buffer#buffer) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) A PEM or DER encoded X509 Certificate. -#### `x509.ca` +#### `x509.ca` - + * Type: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) Will be `true` if this is a Certificate Authority (CA) certificate. -#### `x509.checkEmail(email[, options])` +#### `x509.checkEmail(email[, options])` - + * `email` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) * `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) @@ -2250,9 +2250,9 @@ address, the certificate subject is considered. If the `'subject'` option is set to `'never'`, the certificate subject is never considered, even if the certificate contains no subject alternative names. -#### `x509.checkHost(name[, options])` +#### `x509.checkHost(name[, options])` - + * `name` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) * `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) @@ -2285,9 +2285,9 @@ the certificate subject is considered. If the `'subject'` option is set to `'never'`, the certificate subject is never considered, even if the certificate contains no subject alternative names. -#### `x509.checkIP(ip)` +#### `x509.checkIP(ip)` - + * `ip` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) * Returns: [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`undefined`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type) Returns `ip` if the certificate matches, @@ -2299,18 +2299,18 @@ Only [RFC 5280][] `iPAddress` subject alternative names are considered, and they must match the given `ip` address exactly. Other subject alternative names as well as the subject field of the certificate are ignored. -#### `x509.checkIssued(otherCert)` +#### `x509.checkIssued(otherCert)` - + -* `otherCert` {X509Certificate} +* `otherCert` [`X509Certificate`](/api/crypto#x509certificate) * Returns: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) Checks whether this certificate was issued by the given `otherCert`. -#### `x509.checkPrivateKey(privateKey)` +#### `x509.checkPrivateKey(privateKey)` - + * `privateKey` [`KeyObject`](/api/crypto#keyobject) A private key. * Returns: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) @@ -2318,9 +2318,9 @@ Checks whether this certificate was issued by the given `otherCert`. Checks whether the public key for this certificate is consistent with the given private key. -#### `x509.fingerprint` +#### `x509.fingerprint` - + * Type: [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) @@ -2330,17 +2330,17 @@ Because SHA-1 is cryptographically broken and because the security of SHA-1 is significantly worse than that of algorithms that are commonly used to sign certificates, consider using [`x509.fingerprint256`][] instead. -#### `x509.fingerprint256` +#### `x509.fingerprint256` - + * Type: [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The SHA-256 fingerprint of this certificate. -#### `x509.fingerprint512` +#### `x509.fingerprint512` - + * Type: [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) @@ -2352,9 +2352,9 @@ a better choice. While SHA-512 presumably provides a higher level of security in general, the security of SHA-256 matches that of most algorithms that are commonly used to sign certificates. -#### `x509.infoAccess` +#### `x509.infoAccess` - + * Type: [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) @@ -2371,50 +2371,50 @@ value is a JSON string literal. For backward compatibility, Node.js only uses JSON string literals within this property when necessary to avoid ambiguity. Third-party code should be prepared to handle both possible entry formats. -#### `x509.issuer` +#### `x509.issuer` - + * Type: [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The issuer identification included in this certificate. -#### `x509.issuerCertificate` +#### `x509.issuerCertificate` - + -* Type: {X509Certificate} +* Type: [`X509Certificate`](/api/crypto#x509certificate) The issuer certificate or `undefined` if the issuer certificate is not available. -#### `x509.keyUsage` +#### `x509.keyUsage` - + * Type: string\[] An array detailing the key usages for this certificate. -#### `x509.publicKey` +#### `x509.publicKey` - + * Type: [`KeyObject`](/api/crypto#keyobject) The public key [`KeyObject`](/api/crypto#keyobject) for this certificate. -#### `x509.raw` +#### `x509.raw` - + * Type: [`Buffer`](/api/buffer#buffer) A `Buffer` containing the DER encoding of this certificate. -#### `x509.serialNumber` +#### `x509.serialNumber` - + * Type: [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) @@ -2424,17 +2424,17 @@ Serial numbers are assigned by certificate authorities and do not uniquely identify certificates. Consider using [`x509.fingerprint256`][] as a unique identifier instead. -#### `x509.subject` +#### `x509.subject` - + * Type: [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The complete subject of this certificate. -#### `x509.subjectAltName` +#### `x509.subjectAltName` - + * Type: [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) @@ -2455,9 +2455,9 @@ For backward compatibility, Node.js only uses JSON string literals within this property when necessary to avoid ambiguity. Third-party code should be prepared to handle both possible entry formats. -#### `x509.toJSON()` +#### `x509.toJSON()` - + * Type: [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) @@ -2465,42 +2465,42 @@ There is no standard JSON encoding for X509 certificates. The `toJSON()` method returns a string containing the PEM encoded certificate. -#### `x509.toLegacyObject()` +#### `x509.toLegacyObject()` - + * Type: [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) Returns information about this certificate using the legacy [certificate object][] encoding. -#### `x509.toString()` +#### `x509.toString()` - + * Type: [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) Returns the PEM-encoded certificate. -#### `x509.validFrom` +#### `x509.validFrom` - + * Type: [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The date/time from which this certificate is considered valid. -#### `x509.validTo` +#### `x509.validTo` - + * Type: [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The date/time until which this certificate is considered valid. -#### `x509.verify(publicKey)` +#### `x509.verify(publicKey)` - + * `publicKey` [`KeyObject`](/api/crypto#keyobject) A public key. * Returns: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) @@ -2508,21 +2508,23 @@ The date/time until which this certificate is considered valid. Verifies that this certificate was signed by the given public key. Does not perform any other validation checks on the certificate. -### `node:crypto` module methods and properties +### `node:crypto` module methods and properties -#### `crypto.constants` +#### `crypto.constants` - + -* Returns: [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) An object containing commonly used constants for crypto and - security related operations. The specific constants currently defined are - described in [Crypto constants][]. +* [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) + +An object containing commonly used constants for crypto and security related +operations. The specific constants currently defined are described in +[Crypto constants][]. -#### `crypto.DEFAULT_ENCODING` +#### `crypto.DEFAULT_ENCODING` - + - + The default encoding to use for functions that can take either strings or [buffers][`Buffer`]. The default value is `'buffer'`, which makes methods @@ -2535,11 +2537,11 @@ New applications should expect the default to be `'buffer'`. This property is deprecated. -#### `crypto.fips` +#### `crypto.fips` - + - + Property for checking and controlling whether a FIPS compliant crypto provider is currently in use. Setting to true requires a FIPS build of Node.js. @@ -2547,9 +2549,9 @@ is currently in use. Setting to true requires a FIPS build of Node.js. This property is deprecated. Please use `crypto.setFips()` and `crypto.getFips()` instead. -#### `crypto.checkPrime(candidate[, options], callback)` +#### `crypto.checkPrime(candidate[, options], callback)` - + * `candidate` [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) | [`SharedArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`Buffer`](/api/buffer#buffer) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) | [`bigint`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt) A possible prime encoded as a sequence of big endian octets of arbitrary @@ -2568,9 +2570,9 @@ This property is deprecated. Please use `crypto.setFips()` and Checks the primality of the `candidate`. -#### `crypto.checkPrimeSync(candidate[, options])` +#### `crypto.checkPrimeSync(candidate[, options])` - + * `candidate` [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) | [`SharedArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`Buffer`](/api/buffer#buffer) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) | [`bigint`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt) A possible prime encoded as a sequence of big endian octets of arbitrary @@ -2587,11 +2589,11 @@ Checks the primality of the `candidate`. Checks the primality of the `candidate`. -#### `crypto.createCipher(algorithm, password[, options])` +#### `crypto.createCipher(algorithm, password[, options])` - + - + * `algorithm` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) * `password` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) | [`Buffer`](/api/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) @@ -2633,9 +2635,9 @@ they are used in order to avoid the risk of IV reuse that causes vulnerabilities. For the case when IV is reused in GCM, see [Nonce-Disrespecting Adversaries][] for details. -#### `crypto.createCipheriv(algorithm, key, iv[, options])` +#### `crypto.createCipheriv(algorithm, key, iv[, options])` - + * `algorithm` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) * `key` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) | [`Buffer`](/api/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) | [`KeyObject`](/api/crypto#keyobject) | [`CryptoKey`](/api/webcrypto#cryptokey) @@ -2674,11 +2676,11 @@ something has to be unpredictable and unique, but does not have to be secret; remember that an attacker must not be able to predict ahead of time what a given IV will be. -#### `crypto.createDecipher(algorithm, password[, options])` +#### `crypto.createDecipher(algorithm, password[, options])` - + - + * `algorithm` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) * `password` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) | [`Buffer`](/api/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) @@ -2706,9 +2708,9 @@ In line with OpenSSL's recommendation to use a more modern algorithm instead of their own using [`crypto.scrypt()`][] and to use [`crypto.createDecipheriv()`][] to create the `Decipher` object. -#### `crypto.createDecipheriv(algorithm, key, iv[, options])` +#### `crypto.createDecipheriv(algorithm, key, iv[, options])` - + * `algorithm` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) * `key` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) | [`Buffer`](/api/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) | [`KeyObject`](/api/crypto#keyobject) | [`CryptoKey`](/api/webcrypto#cryptokey) @@ -2747,9 +2749,9 @@ something has to be unpredictable and unique, but does not have to be secret; remember that an attacker must not be able to predict ahead of time what a given IV will be. -#### `crypto.createDiffieHellman(prime[, primeEncoding][, generator][, generatorEncoding])` +#### `crypto.createDiffieHellman(prime[, primeEncoding][, generator][, generatorEncoding])` - + * `prime` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) | [`Buffer`](/api/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) * `primeEncoding` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The [encoding][] of the `prime` string. @@ -2770,9 +2772,9 @@ a [`Buffer`][], `TypedArray`, or `DataView` is expected. If `generatorEncoding` is specified, `generator` is expected to be a string; otherwise a number, [`Buffer`][], `TypedArray`, or `DataView` is expected. -#### `crypto.createDiffieHellman(primeLength[, generator])` +#### `crypto.createDiffieHellman(primeLength[, generator])` - + * `primeLength` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) * `generator` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) **Default:** `2` @@ -2782,18 +2784,18 @@ Creates a `DiffieHellman` key exchange object and generates a prime of `primeLength` bits using an optional specific numeric `generator`. If `generator` is not specified, the value `2` is used. -#### `crypto.createDiffieHellmanGroup(name)` +#### `crypto.createDiffieHellmanGroup(name)` - + * `name` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) * Returns: [`DiffieHellmanGroup`](/api/crypto#diffiehellmangroup) An alias for [`crypto.getDiffieHellman()`][] -#### `crypto.createECDH(curveName)` +#### `crypto.createECDH(curveName)` - + * `curveName` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) * Returns: [`ECDH`](/api/crypto#ecdh) @@ -2804,9 +2806,9 @@ predefined curve specified by the `curveName` string. Use OpenSSL releases, `openssl ecparam -list_curves` will also display the name and description of each available elliptic curve. -#### `crypto.createHash(algorithm[, options])` +#### `crypto.createHash(algorithm[, options])` - + * `algorithm` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) * `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) [`stream.transform` options][] @@ -2845,7 +2847,7 @@ input.on('readable', () => { if (data) hash.update(data); else { - console.log(`${hash.digest('hex')} $filename`); + console.log(`${hash.digest('hex')} ${filename}`); } }); ``` @@ -2871,14 +2873,14 @@ input.on('readable', () => { if (data) hash.update(data); else { - console.log(`${hash.digest('hex')} $filename`); + console.log(`${hash.digest('hex')} ${filename}`); } }); ``` -#### `crypto.createHmac(algorithm, key[, options])` +#### `crypto.createHmac(algorithm, key[, options])` - + * `algorithm` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) * `key` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) | [`Buffer`](/api/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) | [`KeyObject`](/api/crypto#keyobject) | [`CryptoKey`](/api/webcrypto#cryptokey) @@ -2920,7 +2922,7 @@ input.on('readable', () => { if (data) hmac.update(data); else { - console.log(`${hmac.digest('hex')} $filename`); + console.log(`${hmac.digest('hex')} ${filename}`); } }); ``` @@ -2946,14 +2948,14 @@ input.on('readable', () => { if (data) hmac.update(data); else { - console.log(`${hmac.digest('hex')} $filename`); + console.log(`${hmac.digest('hex')} ${filename}`); } }); ``` -#### `crypto.createPrivateKey(key)` +#### `crypto.createPrivateKey(key)` - + @@ -2964,7 +2966,7 @@ input.on('readable', () => { **Default:** `'pem'`. * `type`: [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) Must be `'pkcs1'`, `'pkcs8'` or `'sec1'`. This option is required only if the `format` is `'der'` and ignored otherwise. - * `passphrase`: {string | Buffer} The passphrase to use for decryption. + * `passphrase`: [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) The passphrase to use for decryption. * `encoding`: [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The string encoding to use when `key` is a string. * Returns: [`KeyObject`](/api/crypto#keyobject) @@ -2977,9 +2979,9 @@ must be an object with the properties described above. If the private key is encrypted, a `passphrase` must be specified. The length of the passphrase is limited to 1024 bytes. -#### `crypto.createPublicKey(key)` +#### `crypto.createPublicKey(key)` - + @@ -3010,9 +3012,9 @@ extracted from the returned `KeyObject`. Similarly, if a `KeyObject` with type `'private'` is given, a new `KeyObject` with type `'public'` will be returned and it will be impossible to extract the private key from the returned object. -#### `crypto.createSecretKey(key[, encoding])` +#### `crypto.createSecretKey(key[, encoding])` - + * `key` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) | [`Buffer`](/api/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) * `encoding` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The string encoding when `key` is a string. @@ -3021,9 +3023,9 @@ and it will be impossible to extract the private key from the returned object. Creates and returns a new key object containing a secret key for symmetric encryption or `Hmac`. -#### `crypto.createSign(algorithm[, options])` +#### `crypto.createSign(algorithm[, options])` - + * `algorithm` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) * `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) [`stream.Writable` options][] @@ -3039,9 +3041,9 @@ the corresponding digest algorithm. This does not work for all signature algorithms, such as `'ecdsa-with-SHA256'`, so it is best to always use digest algorithm names. -#### `crypto.createVerify(algorithm[, options])` +#### `crypto.createVerify(algorithm[, options])` - + * `algorithm` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) * `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) [`stream.Writable` options][] @@ -3058,9 +3060,9 @@ the corresponding digest algorithm. This does not work for all signature algorithms, such as `'ecdsa-with-SHA256'`, so it is best to always use digest algorithm names. -#### `crypto.diffieHellman(options)` +#### `crypto.diffieHellman(options)` - + * `options`: [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) * `privateKey`: [`KeyObject`](/api/crypto#keyobject) @@ -3071,9 +3073,9 @@ Computes the Diffie-Hellman secret based on a `privateKey` and a `publicKey`. Both keys must have the same `asymmetricKeyType`, which must be one of `'dh'` (for Diffie-Hellman), `'ec'` (for ECDH), `'x448'`, or `'x25519'` (for ECDH-ES). -#### `crypto.generateKey(type, options, callback)` +#### `crypto.generateKey(type, options, callback)` - + * `type`: [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The intended use of the generated secret key. Currently accepted values are `'hmac'` and `'aes'`. @@ -3113,9 +3115,9 @@ generateKey('hmac', { length: 64 }, (err, key) => { }); ``` -#### `crypto.generateKeyPair(type, options, callback)` +#### `crypto.generateKeyPair(type, options, callback)` - + * `type`: [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) Must be `'rsa'`, `'rsa-pss'`, `'dsa'`, `'ec'`, `'ed25519'`, `'ed448'`, `'x25519'`, `'x448'`, or `'dh'`. @@ -3137,8 +3139,8 @@ generateKey('hmac', { length: 64 }, (err, key) => { * `privateKeyEncoding`: [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) See [`keyObject.export()`][]. * `callback`: [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) * `err`: [`Error`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error) - * `publicKey`: {string | Buffer | KeyObject} - * `privateKey`: {string | Buffer | KeyObject} + * `publicKey`: [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`KeyObject`](/api/crypto#keyobject) + * `privateKey`: [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`KeyObject`](/api/crypto#keyobject) Generates a new asymmetric key pair of the given `type`. RSA, RSA-PSS, DSA, EC, Ed25519, Ed448, X25519, X448, and DH are currently supported. @@ -3200,9 +3202,9 @@ On completion, `callback` will be called with `err` set to `undefined` and If this method is invoked as its [`util.promisify()`][]ed version, it returns a `Promise` for an `Object` with `publicKey` and `privateKey` properties. -#### `crypto.generateKeyPairSync(type, options)` +#### `crypto.generateKeyPairSync(type, options)` - + * `type`: [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) Must be `'rsa'`, `'rsa-pss'`, `'dsa'`, `'ec'`, `'ed25519'`, `'ed448'`, `'x25519'`, `'x448'`, or `'dh'`. @@ -3223,8 +3225,8 @@ a `Promise` for an `Object` with `publicKey` and `privateKey` properties. * `publicKeyEncoding`: [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) See [`keyObject.export()`][]. * `privateKeyEncoding`: [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) See [`keyObject.export()`][]. * Returns: [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) - * `publicKey`: {string | Buffer | KeyObject} - * `privateKey`: {string | Buffer | KeyObject} + * `publicKey`: [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`KeyObject`](/api/crypto#keyobject) + * `privateKey`: [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`KeyObject`](/api/crypto#keyobject) Generates a new asymmetric key pair of the given `type`. RSA, RSA-PSS, DSA, EC, Ed25519, Ed448, X25519, X448, and DH are currently supported. @@ -3283,13 +3285,13 @@ const { }); ``` -The return value `{ publicKey, privateKey }` represents the generated key pair. +The return value ````{ publicKey, privateKey }```` represents the generated key pair. When PEM encoding was selected, the respective key will be a string, otherwise it will be a buffer containing the data encoded as DER. -#### `crypto.generateKeySync(type, options)` +#### `crypto.generateKeySync(type, options)` - + * `type`: [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The intended use of the generated secret key. Currently accepted values are `'hmac'` and `'aes'`. @@ -3322,9 +3324,9 @@ const key = generateKeySync('hmac', { length: 64 }); console.log(key.export().toString('hex')); // e89..........41e ``` -#### `crypto.generatePrime(size[, options[, callback]])` +#### `crypto.generatePrime(size[, options[, callback]])` - + * `size` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The size (in bits) of the prime to generate. * `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) @@ -3363,9 +3365,9 @@ By default, the prime is encoded as a big-endian sequence of octets in an [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer). If the `bigint` option is `true`, then a [`bigint`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt) is provided. -#### `crypto.generatePrimeSync(size[, options])` +#### `crypto.generatePrimeSync(size[, options])` - + * `size` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The size (in bits) of the prime to generate. * `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) @@ -3402,9 +3404,9 @@ By default, the prime is encoded as a big-endian sequence of octets in an [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer). If the `bigint` option is `true`, then a [`bigint`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt) is provided. -#### `crypto.getCipherInfo(nameOrNid[, options])` +#### `crypto.getCipherInfo(nameOrNid[, options])` - + * `nameOrNid`: [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The name or nid of the cipher to query. * `options`: [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) @@ -3430,9 +3432,9 @@ ciphers. To test if a given key length or iv length is acceptable for given cipher, use the `keyLength` and `ivLength` options. If the given values are unacceptable, `undefined` will be returned. -#### `crypto.getCiphers()` +#### `crypto.getCiphers()` - + * Returns: string\[] An array with the names of the supported cipher algorithms. @@ -3453,9 +3455,9 @@ const { console.log(getCiphers()); // ['aes-128-cbc', 'aes-128-ccm', ...] ``` -#### `crypto.getCurves()` +#### `crypto.getCurves()` - + * Returns: string\[] An array with the names of the supported elliptic curves. @@ -3475,9 +3477,9 @@ const { console.log(getCurves()); // ['Oakley-EC2N-3', 'Oakley-EC2N-4', ...] ``` -#### `crypto.getDiffieHellman(groupName)` +#### `crypto.getDiffieHellman(groupName)` - + * `groupName` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) * Returns: [`DiffieHellmanGroup`](/api/crypto#diffiehellmangroup) @@ -3530,17 +3532,17 @@ const bobSecret = bob.computeSecret(alice.getPublicKey(), null, 'hex'); console.log(aliceSecret === bobSecret); ``` -#### `crypto.getFips()` +#### `crypto.getFips()` - + * Returns: [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) `1` if and only if a FIPS compliant crypto provider is currently in use, `0` otherwise. A future semver-major release may change the return type of this API to a [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type). -#### `crypto.getHashes()` +#### `crypto.getHashes()` - + * Returns: string\[] An array of the names of the supported hash algorithms, such as `'RSA-SHA256'`. Hash algorithms are also called "digest" algorithms. @@ -3561,9 +3563,9 @@ const { console.log(getHashes()); // ['DSA', 'DSA-SHA', 'DSA-SHA1', ...] ``` -#### `crypto.getRandomValues(typedArray)` +#### `crypto.getRandomValues(typedArray)` - + * `typedArray` [`Buffer`](/api/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) | [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) * Returns: [`Buffer`](/api/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) | [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) Returns `typedArray`. @@ -3572,9 +3574,9 @@ A convenient alias for [`crypto.webcrypto.getRandomValues()`][]. This implementation is not compliant with the Web Crypto spec, to write web-compatible code use [`crypto.webcrypto.getRandomValues()`][] instead. -#### `crypto.hkdf(digest, ikm, salt, info, keylen, callback)` +#### `crypto.hkdf(digest, ikm, salt, info, keylen, callback)` - + * `digest` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The digest algorithm to use. * `ikm` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) | [`Buffer`](/api/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) | [`KeyObject`](/api/crypto#keyobject) The input @@ -3624,9 +3626,9 @@ hkdf('sha512', 'key', 'salt', 'info', 64, (err, derivedKey) => { }); ``` -#### `crypto.hkdfSync(digest, ikm, salt, info, keylen)` +#### `crypto.hkdfSync(digest, ikm, salt, info, keylen)` - + * `digest` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The digest algorithm to use. * `ikm` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) | [`Buffer`](/api/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) | [`KeyObject`](/api/crypto#keyobject) The input @@ -3670,9 +3672,9 @@ const derivedKey = hkdfSync('sha512', 'key', 'salt', 'info', 64); console.log(Buffer.from(derivedKey).toString('hex')); // '24156e2...5391653' ``` -#### `crypto.pbkdf2(password, salt, iterations, keylen, digest, callback)` +#### `crypto.pbkdf2(password, salt, iterations, keylen, digest, callback)` - + * `password` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) | [`Buffer`](/api/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) * `salt` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) | [`Buffer`](/api/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) @@ -3758,9 +3760,9 @@ This API uses libuv's threadpool, which can have surprising and negative performance implications for some applications; see the [`UV_THREADPOOL_SIZE`][] documentation for more information. -#### `crypto.pbkdf2Sync(password, salt, iterations, keylen, digest)` +#### `crypto.pbkdf2Sync(password, salt, iterations, keylen, digest)` - + * `password` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) * `salt` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) @@ -3829,9 +3831,9 @@ console.log(key); // '3745e48...aa39b34' An array of supported digest functions can be retrieved using [`crypto.getHashes()`][]. -#### `crypto.privateDecrypt(privateKey, buffer)` +#### `crypto.privateDecrypt(privateKey, buffer)` - + @@ -3857,9 +3859,9 @@ If `privateKey` is not a [`KeyObject`][], this function behaves as if object, the `padding` property can be passed. Otherwise, this function uses `RSA_PKCS1_OAEP_PADDING`. -#### `crypto.privateEncrypt(privateKey, buffer)` +#### `crypto.privateEncrypt(privateKey, buffer)` - + @@ -3886,9 +3888,9 @@ If `privateKey` is not a [`KeyObject`][], this function behaves as if object, the `padding` property can be passed. Otherwise, this function uses `RSA_PKCS1_PADDING`. -#### `crypto.publicDecrypt(key, buffer)` +#### `crypto.publicDecrypt(key, buffer)` - + @@ -3916,9 +3918,9 @@ object, the `padding` property can be passed. Otherwise, this function uses Because RSA public keys can be derived from private keys, a private key may be passed instead of a public key. -#### `crypto.publicEncrypt(key, buffer)` +#### `crypto.publicEncrypt(key, buffer)` - + @@ -3954,9 +3956,9 @@ object, the `padding` property can be passed. Otherwise, this function uses Because RSA public keys can be derived from private keys, a private key may be passed instead of a public key. -#### `crypto.randomBytes(size[, callback])` +#### `crypto.randomBytes(size[, callback])` - + * `size` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The number of bytes to generate. The `size` must not be larger than `2**31 - 1`. @@ -3981,7 +3983,7 @@ const { randomBytes(256, (err, buf) => { if (err) throw err; - console.log(`$buf.length bytes of random data: ${buf.toString('hex')}`); + console.log(`${buf.length} bytes of random data: ${buf.toString('hex')}`); }); ``` @@ -3993,7 +3995,7 @@ const { randomBytes(256, (err, buf) => { if (err) throw err; - console.log(`$buf.length bytes of random data: ${buf.toString('hex')}`); + console.log(`${buf.length} bytes of random data: ${buf.toString('hex')}`); }); ``` @@ -4009,7 +4011,7 @@ const { const buf = randomBytes(256); console.log( - `$buf.length bytes of random data: ${buf.toString('hex')}`); + `${buf.length} bytes of random data: ${buf.toString('hex')}`); ``` ```cjs @@ -4020,7 +4022,7 @@ const { const buf = randomBytes(256); console.log( - `$buf.length bytes of random data: ${buf.toString('hex')}`); + `${buf.length} bytes of random data: ${buf.toString('hex')}`); ``` The `crypto.randomBytes()` method will not complete until there is @@ -4038,9 +4040,9 @@ threadpool request. To minimize threadpool task length variation, partition large `randomBytes` requests when doing so as part of fulfilling a client request. -#### `crypto.randomFillSync(buffer[, offset][, size])` +#### `crypto.randomFillSync(buffer[, offset][, size])` - + * `buffer` [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) | [`Buffer`](/api/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) Must be supplied. The size of the provided `buffer` must not be larger than `2**31 - 1`. @@ -4117,9 +4119,9 @@ const c = new ArrayBuffer(10); console.log(Buffer.from(randomFillSync(c)).toString('hex')); ``` -#### `crypto.randomFill(buffer[, offset][, size], callback)` +#### `crypto.randomFill(buffer[, offset][, size], callback)` - + * `buffer` [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) | [`Buffer`](/api/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) Must be supplied. The size of the provided `buffer` must not be larger than `2**31 - 1`. @@ -4246,9 +4248,9 @@ threadpool request. To minimize threadpool task length variation, partition large `randomFill` requests when doing so as part of fulfilling a client request. -#### `crypto.randomInt([min, ]max[, callback])` +#### `crypto.randomInt([min, ]max[, callback])` - + * `min` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Start of random range (inclusive). **Default:** `0`. * `max` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) End of random range (exclusive). @@ -4271,7 +4273,7 @@ const { randomInt(3, (err, n) => { if (err) throw err; - console.log(`Random number chosen from (0, 1, 2): $n`); + console.log(`Random number chosen from (0, 1, 2): ${n}`); }); ``` @@ -4283,7 +4285,7 @@ const { randomInt(3, (err, n) => { if (err) throw err; - console.log(`Random number chosen from (0, 1, 2): $n`); + console.log(`Random number chosen from (0, 1, 2): ${n}`); }); ``` @@ -4294,7 +4296,7 @@ const { } = await import('node:crypto'); const n = randomInt(3); -console.log(`Random number chosen from (0, 1, 2): $n`); +console.log(`Random number chosen from (0, 1, 2): ${n}`); ``` ```cjs @@ -4304,7 +4306,7 @@ const { } = require('node:crypto'); const n = randomInt(3); -console.log(`Random number chosen from (0, 1, 2): $n`); +console.log(`Random number chosen from (0, 1, 2): ${n}`); ``` ```mjs @@ -4314,7 +4316,7 @@ const { } = await import('node:crypto'); const n = randomInt(1, 7); -console.log(`The dice rolled: $n`); +console.log(`The dice rolled: ${n}`); ``` ```cjs @@ -4324,12 +4326,12 @@ const { } = require('node:crypto'); const n = randomInt(1, 7); -console.log(`The dice rolled: $n`); +console.log(`The dice rolled: ${n}`); ``` -#### `crypto.randomUUID([options])` +#### `crypto.randomUUID([options])` - + * `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) * `disableEntropyCache` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) By default, to improve performance, @@ -4342,9 +4344,9 @@ console.log(`The dice rolled: $n`); Generates a random [RFC 4122][] version 4 UUID. The UUID is generated using a cryptographic pseudorandom number generator. -#### `crypto.scrypt(password, salt, keylen[, options], callback)` +#### `crypto.scrypt(password, salt, keylen[, options], callback)` - + * `password` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) | [`Buffer`](/api/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) * `salt` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) | [`Buffer`](/api/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) @@ -4414,9 +4416,9 @@ scrypt('password', 'salt', 64, { N: 1024 }, (err, derivedKey) => { }); ``` -#### `crypto.scryptSync(password, salt, keylen[, options])` +#### `crypto.scryptSync(password, salt, keylen[, options])` - + * `password` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) * `salt` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) @@ -4475,9 +4477,9 @@ const key2 = scryptSync('password', 'salt', 64, { N: 1024 }); console.log(key2.toString('hex')); // '3745e48...aa39b34' ``` -#### `crypto.secureHeapUsed()` +#### `crypto.secureHeapUsed()` - + * Returns: [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) * `total` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The total allocated secure heap size as specified @@ -4489,9 +4491,9 @@ console.log(key2.toString('hex')); // '3745e48...aa39b34' * `utilization` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The calculated ratio of `used` to `total` allocated bytes. -#### `crypto.setEngine(engine[, flags])` +#### `crypto.setEngine(engine[, flags])` - + * `engine` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) * `flags` [`crypto.constants`](/api/crypto#cryptoconstants) **Default:** `crypto.constants.ENGINE_METHOD_ALL` @@ -4522,22 +4524,22 @@ The flags below are deprecated in OpenSSL-1.1.0. * `crypto.constants.ENGINE_METHOD_ECDSA` * `crypto.constants.ENGINE_METHOD_STORE` -#### `crypto.setFips(bool)` +#### `crypto.setFips(bool)` - + * `bool` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) `true` to enable FIPS mode. Enables the FIPS compliant crypto provider in a FIPS-enabled Node.js build. Throws an error if FIPS mode is not available. -#### `crypto.sign(algorithm, data, key[, callback])` +#### `crypto.sign(algorithm, data, key[, callback])` - + -* `algorithm` {string | null | undefined} +* `algorithm` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`null`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type) | [`undefined`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type) * `data` [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) | [`Buffer`](/api/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) * `key` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) | [`Buffer`](/api/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) | [`KeyObject`](/api/crypto#keyobject) | [`CryptoKey`](/api/webcrypto#cryptokey) * `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) @@ -4574,17 +4576,17 @@ additional properties can be passed: If the `callback` function is provided this function uses libuv's threadpool. -#### `crypto.subtle` +#### `crypto.subtle` - + * Type: [`SubtleCrypto`](/api/webcrypto#subtlecrypto) A convenient alias for [`crypto.webcrypto.subtle`][]. -#### `crypto.timingSafeEqual(a, b)` +#### `crypto.timingSafeEqual(a, b)` - + * `a` [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) | [`Buffer`](/api/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) * `b` [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) | [`Buffer`](/api/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) @@ -4617,14 +4619,14 @@ Use of `crypto.timingSafeEqual` does not guarantee that the _surrounding_ code is timing-safe. Care should be taken to ensure that the surrounding code does not introduce timing vulnerabilities. -#### `crypto.verify(algorithm, data, key, signature[, callback])` +#### `crypto.verify(algorithm, data, key, signature[, callback])` - + * `algorithm` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`null`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type) | [`undefined`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type) -* `data` {ArrayBuffer| Buffer|TypedArray|DataView} +* `data` [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) | [`Buffer`](/api/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) * `key` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) | [`Buffer`](/api/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) | [`KeyObject`](/api/crypto#keyobject) | [`CryptoKey`](/api/webcrypto#cryptokey) * `signature` [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) | [`Buffer`](/api/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) * `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) @@ -4668,9 +4670,9 @@ key may be passed for `key`. If the `callback` function is provided this function uses libuv's threadpool. -#### `crypto.webcrypto` +#### `crypto.webcrypto` - + Type: [`Crypto`](/api/webcrypto#crypto) An implementation of the Web Crypto API standard. diff --git a/content/api/v18/debugger.en.md b/content/api/v18/debugger.en.md index 8d780ce990..ae5ed6f0b7 100644 --- a/content/api/v18/debugger.en.md +++ b/content/api/v18/debugger.en.md @@ -2,15 +2,15 @@ title: 'debugger' displayTitle: 'Debugger' category: 'api' -editPage: 'https://github.com/nodejs/node/blob/v18.8.0/doc/api/debugger.md' +editPage: 'https://github.com/nodejs/node/blob/v18.9.0/doc/api/debugger.md' version: 'v18' --- - + - + - + Node.js includes a command-line debugging utility. The Node.js debugger client is not a full-featured debugger, but simple stepping and inspection are diff --git a/content/api/v18/deprecations.en.md b/content/api/v18/deprecations.en.md index ec70d4e794..aa31319f0b 100644 --- a/content/api/v18/deprecations.en.md +++ b/content/api/v18/deprecations.en.md @@ -2,13 +2,13 @@ title: 'deprecations' displayTitle: 'Deprecated APIs' category: 'api' -editPage: 'https://github.com/nodejs/node/blob/v18.8.0/doc/api/deprecations.md' +editPage: 'https://github.com/nodejs/node/blob/v18.9.0/doc/api/deprecations.md' version: 'v18' --- - + - + Node.js APIs might be deprecated for any of the following reasons: @@ -49,7 +49,7 @@ However, the deprecation identifier will not be modified. #### DEP0001: `http.OutgoingMessage.prototype.flush` - + Type: End-of-Life @@ -58,7 +58,7 @@ Type: End-of-Life #### DEP0002: `require('_linklist')` - + Type: End-of-Life @@ -66,7 +66,7 @@ The `_linklist` module is deprecated. Please use a userland alternative. #### DEP0003: `_writableState.buffer` - + Type: End-of-Life @@ -75,7 +75,7 @@ instead. #### DEP0004: `CryptoStream.prototype.readyState` - + Type: End-of-Life @@ -83,7 +83,7 @@ The `CryptoStream.prototype.readyState` property was removed. #### DEP0005: `Buffer()` constructor - + Type: Runtime (supports [`--pending-deprecation`][]) @@ -113,7 +113,7 @@ warning results no matter where the `Buffer()` usage occurs. #### DEP0006: `child_process` `options.customFds` - + Type: End-of-Life @@ -123,7 +123,7 @@ option should be used instead. #### DEP0007: Replace `cluster` `worker.suicide` with `worker.exitedAfterDisconnect` - + Type: End-of-Life @@ -136,7 +136,7 @@ precisely describe the actual semantics and was unnecessarily emotion-laden. #### DEP0008: `require('node:constants')` - + Type: Documentation-only @@ -147,7 +147,7 @@ to the `constants` property exposed by the relevant module. For instance, #### DEP0009: `crypto.pbkdf2` without digest - + Type: End-of-Life @@ -165,7 +165,7 @@ Now, however, passing either `undefined` or `null` will throw a `TypeError`. #### DEP0010: `crypto.createCredentials` - + Type: End-of-Life @@ -174,7 +174,7 @@ The `crypto.createCredentials()` API was removed. Please use #### DEP0011: `crypto.Credentials` - + Type: End-of-Life @@ -183,7 +183,7 @@ instead. #### DEP0012: `Domain.dispose` - + Type: End-of-Life @@ -192,16 +192,16 @@ explicitly via error event handlers set on the domain instead. #### DEP0013: `fs` asynchronous function without callback - + Type: End-of-Life Calling an asynchronous function without a callback throws a `TypeError` -in Node.js 10.0.0 onwards. See . +in Node.js 10.0.0 onwards. See (https://github.com/nodejs/node/pull/12562)[https://github.com/nodejs/node/pull/12562]. #### DEP0014: `fs.read` legacy String interface - + Type: End-of-Life @@ -210,7 +210,7 @@ API as mentioned in the documentation instead. #### DEP0015: `fs.readSync` legacy String interface - + Type: End-of-Life @@ -219,7 +219,7 @@ The [`fs.readSync()`][] legacy `String` interface is deprecated. Use the #### DEP0016: `GLOBAL`/`root` - + Type: End-of-Life @@ -228,7 +228,7 @@ in Node.js 6.0.0 and have since been removed. #### DEP0017: `Intl.v8BreakIterator` - + Type: End-of-Life @@ -237,7 +237,7 @@ See [`Intl.Segmenter`](https://github.com/tc39/proposal-intl-segmenter). #### DEP0018: Unhandled promise rejections - + Type: End-of-Life @@ -248,7 +248,7 @@ code. To change the way Node.js treats unhandled rejections, use the #### DEP0019: `require('.')` resolved outside directory - + Type: End-of-Life @@ -257,7 +257,7 @@ This behavior has been removed. #### DEP0020: `Server.connections` - + Type: End-of-Life @@ -266,16 +266,16 @@ been removed. Please use the [`Server.getConnections()`][] method instead. #### DEP0021: `Server.listenFD` - + Type: End-of-Life The `Server.listenFD()` method was deprecated and removed. Please use -[`Server.listen({fd: })`][] instead. +[`Server.listen(```{fd: }```)`][] instead. #### DEP0022: `os.tmpDir()` - + Type: End-of-Life @@ -284,7 +284,7 @@ removed. Please use [`os.tmpdir()`][] instead. #### DEP0023: `os.getNetworkInterfaces()` - + Type: End-of-Life @@ -293,7 +293,7 @@ The `os.getNetworkInterfaces()` method is deprecated. Please use the #### DEP0024: `REPLServer.prototype.convertToContext()` - + Type: End-of-Life @@ -301,7 +301,7 @@ The `REPLServer.prototype.convertToContext()` API has been removed. #### DEP0025: `require('node:sys')` - + Type: Runtime @@ -309,7 +309,7 @@ The `node:sys` module is deprecated. Please use the [`util`][] module instead. #### DEP0026: `util.print()` - + Type: End-of-Life @@ -317,7 +317,7 @@ Type: End-of-Life #### DEP0027: `util.puts()` - + Type: End-of-Life @@ -325,7 +325,7 @@ Type: End-of-Life #### DEP0028: `util.debug()` - + Type: End-of-Life @@ -333,7 +333,7 @@ Type: End-of-Life #### DEP0029: `util.error()` - + Type: End-of-Life @@ -341,7 +341,7 @@ Type: End-of-Life #### DEP0030: `SlowBuffer` - + Type: Documentation-only @@ -350,7 +350,7 @@ The [`SlowBuffer`][] class is deprecated. Please use #### DEP0031: `ecdh.setPublicKey()` - + Type: Documentation-only @@ -359,7 +359,7 @@ API is not useful. #### DEP0032: `node:domain` module - + Type: Documentation-only @@ -367,7 +367,7 @@ The [`domain`][] module is deprecated and should not be used. #### DEP0033: `EventEmitter.listenerCount()` - + Type: Documentation-only @@ -376,7 +376,7 @@ deprecated. Please use [`emitter.listenerCount(eventName)`][] instead. #### DEP0034: `fs.exists(path, callback)` - + Type: Documentation-only @@ -385,7 +385,7 @@ The [`fs.exists(path, callback)`][] API is deprecated. Please use #### DEP0035: `fs.lchmod(path, mode, callback)` - + Type: Documentation-only @@ -393,7 +393,7 @@ The [`fs.lchmod(path, mode, callback)`][] API is deprecated. #### DEP0036: `fs.lchmodSync(path, mode)` - + Type: Documentation-only @@ -401,7 +401,7 @@ The [`fs.lchmodSync(path, mode)`][] API is deprecated. #### DEP0037: `fs.lchown(path, uid, gid, callback)` - + Type: Deprecation revoked @@ -411,7 +411,7 @@ libuv. #### DEP0038: `fs.lchownSync(path, uid, gid)` - + Type: Deprecation revoked @@ -420,7 +420,7 @@ revoked because the requisite supporting APIs were added in libuv. #### DEP0039: `require.extensions` - + Type: Documentation-only @@ -428,7 +428,7 @@ The [`require.extensions`][] property is deprecated. #### DEP0040: `node:punycode` module - + Type: Documentation-only (supports [`--pending-deprecation`][]) @@ -437,7 +437,7 @@ instead. #### DEP0041: `NODE_REPL_HISTORY_FILE` environment variable - + Type: End-of-Life @@ -446,7 +446,7 @@ The `NODE_REPL_HISTORY_FILE` environment variable was removed. Please use #### DEP0042: `tls.CryptoStream` - + Type: End-of-Life @@ -455,7 +455,7 @@ The [`tls.CryptoStream`][] class was removed. Please use #### DEP0043: `tls.SecurePair` - + Type: Documentation-only @@ -464,7 +464,7 @@ The [`tls.SecurePair`][] class is deprecated. Please use #### DEP0044: `util.isArray()` - + Type: Documentation-only @@ -473,7 +473,7 @@ instead. #### DEP0045: `util.isBoolean()` - + Type: Documentation-only @@ -481,7 +481,7 @@ The [`util.isBoolean()`][] API is deprecated. #### DEP0046: `util.isBuffer()` - + Type: Documentation-only @@ -490,7 +490,7 @@ The [`util.isBuffer()`][] API is deprecated. Please use #### DEP0047: `util.isDate()` - + Type: Documentation-only @@ -498,7 +498,7 @@ The [`util.isDate()`][] API is deprecated. #### DEP0048: `util.isError()` - + Type: Documentation-only @@ -506,7 +506,7 @@ The [`util.isError()`][] API is deprecated. #### DEP0049: `util.isFunction()` - + Type: Documentation-only @@ -514,7 +514,7 @@ The [`util.isFunction()`][] API is deprecated. #### DEP0050: `util.isNull()` - + Type: Documentation-only @@ -522,7 +522,7 @@ The [`util.isNull()`][] API is deprecated. #### DEP0051: `util.isNullOrUndefined()` - + Type: Documentation-only @@ -530,7 +530,7 @@ The [`util.isNullOrUndefined()`][] API is deprecated. #### DEP0052: `util.isNumber()` - + Type: Documentation-only @@ -538,7 +538,7 @@ The [`util.isNumber()`][] API is deprecated. #### DEP0053: `util.isObject()` - + Type: Documentation-only @@ -546,7 +546,7 @@ The [`util.isObject()`][] API is deprecated. #### DEP0054: `util.isPrimitive()` - + Type: Documentation-only @@ -554,7 +554,7 @@ The [`util.isPrimitive()`][] API is deprecated. #### DEP0055: `util.isRegExp()` - + Type: Documentation-only @@ -562,7 +562,7 @@ The [`util.isRegExp()`][] API is deprecated. #### DEP0056: `util.isString()` - + Type: Documentation-only @@ -570,7 +570,7 @@ The [`util.isString()`][] API is deprecated. #### DEP0057: `util.isSymbol()` - + Type: Documentation-only @@ -578,7 +578,7 @@ The [`util.isSymbol()`][] API is deprecated. #### DEP0058: `util.isUndefined()` - + Type: Documentation-only @@ -586,7 +586,7 @@ The [`util.isUndefined()`][] API is deprecated. #### DEP0059: `util.log()` - + Type: Documentation-only @@ -594,7 +594,7 @@ The [`util.log()`][] API is deprecated. #### DEP0060: `util._extend()` - + Type: Documentation-only @@ -602,7 +602,7 @@ The [`util._extend()`][] API is deprecated. #### DEP0061: `fs.SyncWriteStream` - + Type: End-of-Life @@ -612,7 +612,7 @@ alternative. #### DEP0062: `node --debug` - + Type: End-of-Life @@ -622,7 +622,7 @@ instead. #### DEP0063: `ServerResponse.prototype.writeHeader()` - + Type: Documentation-only @@ -634,7 +634,7 @@ officially supported API. #### DEP0064: `tls.createSecurePair()` - + Type: Runtime @@ -643,7 +643,7 @@ The `tls.createSecurePair()` API was deprecated in documentation in Node.js #### DEP0065: `repl.REPL_MODE_MAGIC` and `NODE_REPL_MODE=magic` - + Type: End-of-Life @@ -658,7 +658,7 @@ removed. Please use `sloppy` instead. #### DEP0066: `OutgoingMessage.prototype._headers, OutgoingMessage.prototype._headerNames` - + Type: Runtime @@ -678,7 +678,7 @@ officially supported properties. #### DEP0067: `OutgoingMessage.prototype._renderHeaders` - + Type: Documentation-only @@ -690,7 +690,7 @@ an officially supported API. #### DEP0068: `node debug` - + Type: End-of-Life @@ -699,7 +699,7 @@ a V8-inspector based CLI debugger available through `node inspect`. #### DEP0069: `vm.runInDebugContext(string)` - + Type: End-of-Life @@ -709,7 +709,7 @@ DebugContext was an experimental API. #### DEP0070: `async_hooks.currentId()` - + Type: End-of-Life @@ -720,7 +720,7 @@ This change was made while `async_hooks` was an experimental API. #### DEP0071: `async_hooks.triggerId()` - + Type: End-of-Life @@ -731,7 +731,7 @@ This change was made while `async_hooks` was an experimental API. #### DEP0072: `async_hooks.AsyncResource.triggerId()` - + Type: End-of-Life @@ -742,7 +742,7 @@ This change was made while `async_hooks` was an experimental API. #### DEP0073: Several internal properties of `net.Server` - + Type: End-of-Life @@ -754,7 +754,7 @@ code, no replacement API is provided. #### DEP0074: `REPLServer.bufferedCommand` - + Type: End-of-Life @@ -763,7 +763,7 @@ The `REPLServer.bufferedCommand` property was deprecated in favor of #### DEP0075: `REPLServer.parseREPLKeyword()` - + Type: End-of-Life @@ -771,7 +771,7 @@ Type: End-of-Life #### DEP0076: `tls.parseCertString()` - + Type: End-of-Life @@ -785,7 +785,7 @@ not handle all certificate subjects correctly and should not be used. #### DEP0077: `Module._debug()` - + Type: Runtime @@ -796,7 +796,7 @@ supported API. #### DEP0078: `REPLServer.turnOffEditorMode()` - + Type: End-of-Life @@ -804,7 +804,7 @@ Type: End-of-Life #### DEP0079: Custom inspection function on objects via `.inspect()` - + Type: End-of-Life @@ -815,7 +815,7 @@ can be specified. #### DEP0080: `path._makeLong()` - + Type: Documentation-only @@ -825,7 +825,7 @@ and replaced with an identical, public `path.toNamespacedPath()` method. #### DEP0081: `fs.truncate()` using a file descriptor - + Type: Runtime @@ -835,7 +835,7 @@ file descriptors. #### DEP0082: `REPLServer.prototype.memory()` - + Type: End-of-Life @@ -844,7 +844,7 @@ the `REPLServer` itself. Do not use this function. #### DEP0083: Disabling ECDH by setting `ecdhCurve` to `false` - + Type: End-of-Life. @@ -855,7 +855,7 @@ the client and is now unsupported. Use the `ciphers` parameter instead. #### DEP0084: requiring bundled internal dependencies - + Type: End-of-Life @@ -887,22 +887,22 @@ code modification is necessary if that is done. #### DEP0085: AsyncHooks sensitive API - + Type: End-of-Life The AsyncHooks sensitive API was never documented and had various minor issues. Use the `AsyncResource` API instead. See -. +(https://github.com/nodejs/node/issues/15572)[https://github.com/nodejs/node/issues/15572]. #### DEP0086: Remove `runInAsyncIdScope` - + Type: End-of-Life `runInAsyncIdScope` doesn't emit the `'before'` or `'after'` event and can thus -cause a lot of issues. See . +cause a lot of issues. See (https://github.com/nodejs/node/issues/14328)[https://github.com/nodejs/node/issues/14328]. @@ -910,7 +910,7 @@ cause a lot of issues. See . #### DEP0089: `require('node:assert')` - + Type: Deprecation revoked @@ -921,7 +921,7 @@ confusion. #### DEP0090: Invalid GCM authentication tag lengths - + Type: End-of-Life @@ -933,7 +933,7 @@ bits are allowed. Authentication tags of other lengths are invalid per #### DEP0091: `crypto.DEFAULT_ENCODING` - + Type: Runtime @@ -941,7 +941,7 @@ The [`crypto.DEFAULT_ENCODING`][] property is deprecated. #### DEP0092: Top-level `this` bound to `module.exports` - + Type: Documentation-only @@ -951,7 +951,7 @@ or `module.exports` instead. #### DEP0093: `crypto.fips` is deprecated and replaced - + Type: Documentation-only @@ -960,7 +960,7 @@ and `crypto.getFips()` instead. #### DEP0094: Using `assert.fail()` with more than one argument - + Type: Runtime @@ -970,7 +970,7 @@ method. #### DEP0095: `timers.enroll()` - + Type: Runtime @@ -979,7 +979,7 @@ Type: Runtime #### DEP0096: `timers.unenroll()` - + Type: Runtime @@ -988,7 +988,7 @@ Type: Runtime #### DEP0097: `MakeCallback` with `domain` property - + Type: Runtime @@ -998,7 +998,7 @@ should start using the `async_context` variant of `MakeCallback` or #### DEP0098: AsyncHooks embedder `AsyncResource.emitBefore` and `AsyncResource.emitAfter` APIs - + Type: End-of-Life @@ -1008,11 +1008,11 @@ to unrecoverable errors. Use [`asyncResource.runInAsyncScope()`][] API instead which provides a much safer, and more convenient, alternative. See -. +(https://github.com/nodejs/node/pull/18513)[https://github.com/nodejs/node/pull/18513]. #### DEP0099: Async context-unaware `node::MakeCallback` C++ APIs - + Type: Compile-time @@ -1022,7 +1022,7 @@ parameter. #### DEP0100: `process.assert()` - + Type: Runtime @@ -1032,7 +1032,7 @@ This was never a documented feature. #### DEP0101: `--with-lttng` - + Type: End-of-Life @@ -1040,7 +1040,7 @@ The `--with-lttng` compile-time option has been removed. #### DEP0102: Using `noAssert` in `Buffer#(read|write)` operations - + Type: End-of-Life @@ -1050,7 +1050,7 @@ could lead to hard-to-find errors and crashes. #### DEP0103: `process.binding('util').is[...]` typechecks - + Type: Documentation-only (supports [`--pending-deprecation`][]) @@ -1062,7 +1062,7 @@ This deprecation has been superseded by the deprecation of the #### DEP0104: `process.env` string coercion - + Type: Documentation-only (supports [`--pending-deprecation`][]) @@ -1074,7 +1074,7 @@ assigning it to `process.env`. #### DEP0105: `decipher.finaltol` - + Type: End-of-Life @@ -1084,7 +1084,7 @@ Type: End-of-Life #### DEP0106: `crypto.createCipher` and `crypto.createDecipher` - + Type: Runtime @@ -1097,7 +1097,7 @@ initialization vectors. It is recommended to derive a key using #### DEP0107: `tls.convertNPNProtocols()` - + Type: End-of-Life @@ -1106,7 +1106,7 @@ core and obsoleted by the removal of NPN (Next Protocol Negotiation) support. #### DEP0108: `zlib.bytesRead` - + Type: Runtime @@ -1117,7 +1117,7 @@ expose values under these names. #### DEP0109: `http`, `https`, and `tls` support for invalid URLs - + Type: End-of-Life @@ -1130,7 +1130,7 @@ deprecated and support will be removed in the future. #### DEP0110: `vm.Script` cached data - + Type: Documentation-only @@ -1139,7 +1139,7 @@ The `produceCachedData` option is deprecated. Use #### DEP0111: `process.binding()` - + Type: Documentation-only (supports [`--pending-deprecation`][]) @@ -1147,7 +1147,7 @@ Type: Documentation-only (supports [`--pending-deprecation`][]) #### DEP0112: `dgram` private APIs - + Type: Runtime @@ -1160,7 +1160,7 @@ to accessed outside of Node.js core: `Socket.prototype._handle`, #### DEP0113: `Cipher.setAuthTag()`, `Decipher.getAuthTag()` - + Type: End-of-Life @@ -1169,7 +1169,7 @@ were never documented and would throw when called. #### DEP0114: `crypto._toBuf()` - + Type: End-of-Life @@ -1180,7 +1180,7 @@ of Node.js core and was removed. #### DEP0115: `crypto.prng()`, `crypto.pseudoRandomBytes()`, `crypto.rng()` - + Type: Documentation-only (supports [`--pending-deprecation`][]) @@ -1194,7 +1194,7 @@ future release. #### DEP0116: Legacy URL API - + Type: Deprecation revoked @@ -1204,7 +1204,7 @@ use the [WHATWG URL API][] instead. #### DEP0117: Native crypto handles - + Type: End-of-Life @@ -1216,7 +1216,7 @@ object can lead to crashing the application. #### DEP0118: `dns.lookup()` support for a falsy host name - + Type: Runtime @@ -1227,7 +1227,7 @@ It will become an error in future versions of Node.js. #### DEP0119: `process.binding('uv').errname()` private API - + Type: Documentation-only (supports [`--pending-deprecation`][]) @@ -1236,7 +1236,7 @@ Type: Documentation-only (supports [`--pending-deprecation`][]) #### DEP0120: Windows Performance Counter support - + Type: End-of-Life @@ -1248,7 +1248,7 @@ undocumented `COUNTER_NET_SERVER_CONNECTION()`, #### DEP0121: `net._setSimultaneousAccepts()` - + Type: Runtime @@ -1256,11 +1256,11 @@ The undocumented `net._setSimultaneousAccepts()` function was originally intended for debugging and performance tuning when using the `node:child_process` and `node:cluster` modules on Windows. The function is not generally useful and is being removed. See discussion here: - +(https://github.com/nodejs/node/issues/18391)[https://github.com/nodejs/node/issues/18391] #### DEP0122: `tls` `Server.prototype.setOptions()` - + Type: Runtime @@ -1268,7 +1268,7 @@ Please use `Server.prototype.setSecureContext()` instead. #### DEP0123: setting the TLS ServerName to an IP address - + Type: Runtime @@ -1277,7 +1277,7 @@ Setting the TLS ServerName to an IP address is not permitted by #### DEP0124: using `REPLServer.rli` - + Type: End-of-Life @@ -1285,7 +1285,7 @@ This property is a reference to the instance itself. #### DEP0125: `require('node:_stream_wrap')` - + Type: Runtime @@ -1293,7 +1293,7 @@ The `node:_stream_wrap` module is deprecated. #### DEP0126: `timers.active()` - + Type: Runtime @@ -1304,7 +1304,7 @@ with no performance impact since Node.js 10. #### DEP0127: `timers._unrefActive()` - + Type: Runtime @@ -1315,7 +1315,7 @@ with no performance impact since Node.js 10. #### DEP0128: modules with an invalid `main` entry and an `index.js` file - + Type: Runtime @@ -1326,7 +1326,7 @@ Node.js versions. #### DEP0129: `ChildProcess._channel` - + Type: Runtime @@ -1336,7 +1336,7 @@ instead. #### DEP0130: `Module.createRequireFromPath()` - + Type: End-of-Life @@ -1344,7 +1344,7 @@ Use [`module.createRequire()`][] instead. #### DEP0131: Legacy HTTP parser - + Type: End-of-Life @@ -1355,7 +1355,7 @@ legacy parser. #### DEP0132: `worker.terminate()` with callback - + Type: Runtime @@ -1364,7 +1364,7 @@ Passing a callback to [`worker.terminate()`][] is deprecated. Use the returned #### DEP0133: `http` `connection` - + Type: Documentation-only @@ -1373,7 +1373,7 @@ Prefer [`response.socket`][] over [`response.connection`][] and #### DEP0134: `process._tickCallback` - + Type: Documentation-only (supports [`--pending-deprecation`][]) @@ -1382,7 +1382,7 @@ an officially supported API. #### DEP0135: `WriteStream.open()` and `ReadStream.open()` are internal - + Type: Runtime @@ -1393,7 +1393,7 @@ and [`fs.createReadStream()`][]) or by passing a file descriptor in options. #### DEP0136: `http` `finished` - + Type: Documentation-only @@ -1409,7 +1409,7 @@ To maintain existing behavior `response.finished` should be replaced with #### DEP0137: Closing fs.FileHandle on garbage collection - + Type: Runtime @@ -1435,7 +1435,7 @@ async function openAndClose() { #### DEP0138: `process.mainModule` - + Type: Documentation-only @@ -1448,7 +1448,7 @@ purpose and is only available on CommonJS environment. #### DEP0139: `process.umask()` with no arguments - + Type: Documentation-only @@ -1459,7 +1459,7 @@ API. #### DEP0140: Use `request.destroy()` instead of `request.abort()` - + Type: Documentation-only @@ -1467,7 +1467,7 @@ Use [`request.destroy()`][] instead of [`request.abort()`][]. #### DEP0141: `repl.inputStream` and `repl.outputStream` - + Type: Documentation-only (supports [`--pending-deprecation`][]) @@ -1476,7 +1476,7 @@ instead of `.inputStream` and `.output` instead of `.outputStream`. #### DEP0142: `repl._builtinLibs` - + Type: Documentation-only @@ -1486,7 +1486,7 @@ upon `require('node:module').builtinModules`. #### DEP0143: `Transform._transformState` - + Type: Runtime `Transform._transformState` will be removed in future versions where it is @@ -1494,7 +1494,7 @@ no longer required due to simplification of the implementation. #### DEP0144: `module.parent` - + Type: Documentation-only (supports [`--pending-deprecation`][]) @@ -1522,7 +1522,7 @@ const moduleParents = Object.values(require.cache) #### DEP0145: `socket.bufferSize` - + Type: Documentation-only @@ -1530,7 +1530,7 @@ Type: Documentation-only #### DEP0146: `new crypto.Certificate()` - + Type: Documentation-only @@ -1539,20 +1539,20 @@ The [`crypto.Certificate()` constructor][] is deprecated. Use #### DEP0147: `fs.rmdir(path, { recursive: true })` - + Type: Runtime In future versions of Node.js, `recursive` option will be ignored for `fs.rmdir`, `fs.rmdirSync`, and `fs.promises.rmdir`. -Use `fs.rm(path, { recursive: true, force: true })`, -`fs.rmSync(path, { recursive: true, force: true })` or -`fs.promises.rm(path, { recursive: true, force: true })` instead. +Use `fs.rm(path, ```{ recursive: true, force: true }```)`, +`fs.rmSync(path, ```{ recursive: true, force: true }```)` or +`fs.promises.rm(path, ```{ recursive: true, force: true }```)` instead. #### DEP0148: Folder mappings in `"exports"` (trailing `"/"`) - + Type: Runtime @@ -1562,7 +1562,7 @@ Using a trailing `"/"` to define subpath folder mappings in the #### DEP0149: `http.IncomingMessage#connection` - + Type: Documentation-only. @@ -1570,7 +1570,7 @@ Prefer [`message.socket`][] over [`message.connection`][]. #### DEP0150: Changing the value of `process.config` - + Type: Runtime @@ -1580,7 +1580,7 @@ to change the value will be removed in a future version of Node.js. #### DEP0151: Main index lookup and extension searching - + Type: Runtime @@ -1592,7 +1592,7 @@ an explicit [`"exports"` or `"main"` entry][] with the exact file extension. #### DEP0152: Extension PerformanceEntry properties - + Type: Runtime @@ -1604,7 +1604,7 @@ deprecated and should no longer be used. #### DEP0153: `dns.lookup` and `dnsPromises.lookup` options type coercion - + Type: End-of-Life @@ -1616,7 +1616,7 @@ option, or a non-nullish non-boolean value for `verbatim` option in #### DEP0154: RSA-PSS generate key pair options - + Type: Documentation-only (supports [`--pending-deprecation`][]) @@ -1625,7 +1625,7 @@ and `'mgf1HashAlgorithm'`. #### DEP0155: Trailing slashes in pattern specifier resolutions - + Type: Runtime @@ -1634,7 +1634,7 @@ for package `"exports"` and `"imports"` pattern resolutions. #### DEP0156: `.aborted` property and `'abort'`, `'aborted'` event in `http` - + Type: Documentation-only @@ -1652,7 +1652,7 @@ it was an aborted or graceful destroy. #### DEP0157: Thenable support in streams - + Type: End-of-Life @@ -1675,7 +1675,7 @@ const w = new Writable({ #### DEP0158: `buffer.slice(start, end)` - + Type: Documentation-only @@ -1686,7 +1686,7 @@ Use [`buffer.subarray`][] which does the same thing instead. #### DEP0159: `ERR_INVALID_CALLBACK` - + Type: End-of-Life @@ -1695,7 +1695,7 @@ the errors used for value type validation. #### DEP0160: `process.on('multipleResolves', handler)` - + Type: Runtime. @@ -1704,7 +1704,7 @@ which diminished its usefulness. #### DEP0161: `process._getActiveRequests()` and `process._getActiveHandles()` - + Type: Documentation-only @@ -1717,7 +1717,7 @@ resources and not the actual references. #### DEP0162: `fs.write()`, `fs.writeFileSync()` coercion to string - + Type: Runtime @@ -1728,7 +1728,7 @@ Convert them to primitive strings. #### DEP0163: `channel.subscribe(onMessage)`, `channel.unsubscribe(onMessage)` - + Type: Documentation-only @@ -1741,7 +1741,7 @@ thing instead. #### DEP0164: `process.exit([code])` coercion to integer - + Type: Documentation-only @@ -1750,7 +1750,7 @@ strings (e.g., '1') are deprecated as parameter in [`process.exit()`][]. #### DEP0165: `--trace-atomics-wait` - + Type: Documentation-only @@ -1774,7 +1774,7 @@ The [`--trace-atomics-wait`][] flag is deprecated. [`REPLServer.clearBufferedCommand()`]: (/api/repl#replserverclearbufferedcommand) [`ReadStream.open()`]: (/api/fs#class-fsreadstream) [`Server.getConnections()`]: (/api/net#servergetconnectionscallback) -[`Server.listen({fd: })`]: (/api/net#serverlistenhandle-backlog-callback) +[`Server.listen(```{fd: }```)`]: (/api/net#serverlistenhandle-backlog-callback) [`SlowBuffer`]: (/api/buffer#class-slowbuffer) [`WriteStream.open()`]: (/api/fs#class-fswritestream) [`assert`]: (/api/assert) diff --git a/content/api/v18/dgram.en.md b/content/api/v18/dgram.en.md index c936942621..1633e4463e 100644 --- a/content/api/v18/dgram.en.md +++ b/content/api/v18/dgram.en.md @@ -2,17 +2,17 @@ title: 'dgram' displayTitle: 'UDP/datagram sockets' category: 'api' -editPage: 'https://github.com/nodejs/node/blob/v18.8.0/doc/api/dgram.md' +editPage: 'https://github.com/nodejs/node/blob/v18.9.0/doc/api/dgram.md' version: 'v18' --- - + - + - + - + The `node:dgram` module provides an implementation of UDP datagram sockets. @@ -22,17 +22,17 @@ import dgram from 'node:dgram'; const server = dgram.createSocket('udp4'); server.on('error', (err) => { - console.log(`server error:\n$err.stack`); + console.log(`server error:\n${err.stack}`); server.close(); }); server.on('message', (msg, rinfo) => { - console.log(`server got: $msg from $rinfo.address:$rinfo.port`); + console.log(`server got: ${msg} from ${rinfo.address}:${rinfo.port}`); }); server.on('listening', () => { const address = server.address(); - console.log(`server listening $address.address:$address.port`); + console.log(`server listening ${address.address}:${address.port}`); }); server.bind(41234); @@ -44,26 +44,26 @@ const dgram = require('node:dgram'); const server = dgram.createSocket('udp4'); server.on('error', (err) => { - console.log(`server error:\n$err.stack`); + console.log(`server error:\n${err.stack}`); server.close(); }); server.on('message', (msg, rinfo) => { - console.log(`server got: $msg from $rinfo.address:$rinfo.port`); + console.log(`server got: ${msg} from ${rinfo.address}:${rinfo.port}`); }); server.on('listening', () => { const address = server.address(); - console.log(`server listening $address.address:$address.port`); + console.log(`server listening ${address.address}:${address.port}`); }); server.bind(41234); // Prints: server listening 0.0.0.0:41234 ``` -### `dgram.Socket` +### `dgram.Socket` - + * Extends: [`EventEmitter`](/api/events#eventemitter) @@ -72,32 +72,32 @@ Encapsulates the datagram functionality. New instances of `dgram.Socket` are created using [`dgram.createSocket()`][]. The `new` keyword is not to be used to create `dgram.Socket` instances. -#### `'close'` +#### `'close'` - + The `'close'` event is emitted after a socket is closed with [`close()`][]. Once triggered, no new `'message'` events will be emitted on this socket. -#### `'connect'` +#### `'connect'` - + The `'connect'` event is emitted after a socket is associated to a remote address as a result of a successful [`connect()`][] call. -#### `'error'` +#### `'error'` - + * `exception` [`Error`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error) The `'error'` event is emitted whenever any error occurs. The event handler function is passed a single `Error` object. -#### `'listening'` +#### `'listening'` - + The `'listening'` event is emitted once the `dgram.Socket` is addressable and can receive data. This happens either explicitly with `socket.bind()` or @@ -105,9 +105,9 @@ implicitly the first time data is sent using `socket.send()`. Until the `dgram.Socket` is listening, the underlying system resources do not exist and calls such as `socket.address()` and `socket.setTTL()` will fail. -#### `'message'` +#### `'message'` - + The `'message'` event is emitted when a new datagram is available on a socket. The event handler function is passed two arguments: `msg` and `rinfo`. @@ -125,9 +125,9 @@ example, a packet received on the `en0` interface might have the address field set to `'fe80::2618:1234:ab11:3b9c%en0'`, where `'%en0'` is the interface name as a zone ID suffix. -#### `socket.addMembership(multicastAddress[, multicastInterface])` +#### `socket.addMembership(multicastAddress[, multicastInterface])` - + * `multicastAddress` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) * `multicastInterface` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) @@ -175,9 +175,9 @@ if (cluster.isPrimary) { } ``` -#### `socket.addSourceSpecificMembership(sourceAddress, groupAddress[, multicastInterface])` +#### `socket.addSourceSpecificMembership(sourceAddress, groupAddress[, multicastInterface])` - + * `sourceAddress` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) * `groupAddress` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) @@ -193,9 +193,9 @@ membership to it. To add membership to every available interface, call When called on an unbound socket, this method will implicitly bind to a random port, listening on all interfaces. -#### `socket.address()` +#### `socket.address()` - + * Returns: [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) @@ -205,9 +205,9 @@ properties. This method throws `EBADF` if called on an unbound socket. -#### `socket.bind([port][, address][, callback])` +#### `socket.bind([port][, address][, callback])` - + * `port` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) * `address` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) @@ -239,17 +239,17 @@ import dgram from 'node:dgram'; const server = dgram.createSocket('udp4'); server.on('error', (err) => { - console.log(`server error:\n$err.stack`); + console.log(`server error:\n${err.stack}`); server.close(); }); server.on('message', (msg, rinfo) => { - console.log(`server got: $msg from $rinfo.address:$rinfo.port`); + console.log(`server got: ${msg} from ${rinfo.address}:${rinfo.port}`); }); server.on('listening', () => { const address = server.address(); - console.log(`server listening $address.address:$address.port`); + console.log(`server listening ${address.address}:${address.port}`); }); server.bind(41234); @@ -261,26 +261,26 @@ const dgram = require('node:dgram'); const server = dgram.createSocket('udp4'); server.on('error', (err) => { - console.log(`server error:\n$err.stack`); + console.log(`server error:\n${err.stack}`); server.close(); }); server.on('message', (msg, rinfo) => { - console.log(`server got: $msg from $rinfo.address:$rinfo.port`); + console.log(`server got: ${msg} from ${rinfo.address}:${rinfo.port}`); }); server.on('listening', () => { const address = server.address(); - console.log(`server listening $address.address:$address.port`); + console.log(`server listening ${address.address}:${address.port}`); }); server.bind(41234); // Prints: server listening 0.0.0.0:41234 ``` -#### `socket.bind(options[, callback])` +#### `socket.bind(options[, callback])` - + * `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) Required. Supports the following properties: * `port` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) @@ -330,18 +330,18 @@ socket.bind({ }); ``` -#### `socket.close([callback])` +#### `socket.close([callback])` - + * `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) Called when the socket has been closed. Close the underlying socket and stop listening for data on it. If a callback is provided, it is added as a listener for the [`'close'`][] event. -#### `socket.connect(port[, address][, callback])` +#### `socket.connect(port[, address][, callback])` - + * `port` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) * `address` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) @@ -357,18 +357,18 @@ will be used by default. Once the connection is complete, a `'connect'` event is emitted and the optional `callback` function is called. In case of failure, the `callback` is called or, failing this, an `'error'` event is emitted. -#### `socket.disconnect()` +#### `socket.disconnect()` - + A synchronous function that disassociates a connected `dgram.Socket` from its remote address. Trying to call `disconnect()` on an unbound or already disconnected socket will result in an [`ERR_SOCKET_DGRAM_NOT_CONNECTED`][] exception. -#### `socket.dropMembership(multicastAddress[, multicastInterface])` +#### `socket.dropMembership(multicastAddress[, multicastInterface])` - + * `multicastAddress` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) * `multicastInterface` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) @@ -381,9 +381,9 @@ never have reason to call this. If `multicastInterface` is not specified, the operating system will attempt to drop membership on all valid interfaces. -#### `socket.dropSourceSpecificMembership(sourceAddress, groupAddress[, multicastInterface])` +#### `socket.dropSourceSpecificMembership(sourceAddress, groupAddress[, multicastInterface])` - + * `sourceAddress` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) * `groupAddress` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) @@ -398,38 +398,38 @@ reason to call this. If `multicastInterface` is not specified, the operating system will attempt to drop membership on all valid interfaces. -#### `socket.getRecvBufferSize()` +#### `socket.getRecvBufferSize()` - + * Returns: [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) the `SO_RCVBUF` socket receive buffer size in bytes. This method throws [`ERR_SOCKET_BUFFER_SIZE`][] if called on an unbound socket. -#### `socket.getSendBufferSize()` +#### `socket.getSendBufferSize()` - + * Returns: [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) the `SO_SNDBUF` socket send buffer size in bytes. This method throws [`ERR_SOCKET_BUFFER_SIZE`][] if called on an unbound socket. -#### `socket.getSendQueueSize()` +#### `socket.getSendQueueSize()` - + * Returns: [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number of bytes queued for sending. -#### `socket.getSendQueueCount()` +#### `socket.getSendQueueCount()` - + * Returns: [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number of send requests currently in the queue awaiting to be processed. -#### `socket.ref()` +#### `socket.ref()` - + * Returns: [`dgram.Socket`](/api/dgram#dgramsocket) @@ -444,9 +444,9 @@ Calling `socket.ref()` multiples times will have no additional effect. The `socket.ref()` method returns a reference to the socket so calls can be chained. -#### `socket.remoteAddress()` +#### `socket.remoteAddress()` - + * Returns: [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) @@ -454,9 +454,9 @@ Returns an object containing the `address`, `family`, and `port` of the remote endpoint. This method throws an [`ERR_SOCKET_DGRAM_NOT_CONNECTED`][] exception if the socket is not connected. -#### `socket.send(msg[, offset, length][, port][, address][, callback])` +#### `socket.send(msg[, offset, length][, port][, address][, callback])` - + * `msg` [`Buffer`](/api/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array) Message to be sent. * `offset` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Offset in the buffer where the message starts. @@ -618,9 +618,9 @@ a packet might travel. Sending a datagram greater than the receiver `MTU` will not work because the packet will get silently dropped without informing the source that the data did not reach its intended recipient. -#### `socket.setBroadcast(flag)` +#### `socket.setBroadcast(flag)` - + * `flag` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) @@ -629,9 +629,9 @@ packets may be sent to a local interface's broadcast address. This method throws `EBADF` if called on an unbound socket. -#### `socket.setMulticastInterface(multicastInterface)` +#### `socket.setMulticastInterface(multicastInterface)` - + * `multicastInterface` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) @@ -709,9 +709,9 @@ A socket's address family's ANY address (IPv4 `'0.0.0.0'` or IPv6 `'::'`) can be used to return control of the sockets default outgoing interface to the system for future multicast packets. -#### `socket.setMulticastLoopback(flag)` +#### `socket.setMulticastLoopback(flag)` - + * `flag` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) @@ -720,9 +720,9 @@ multicast packets will also be received on the local interface. This method throws `EBADF` if called on an unbound socket. -#### `socket.setMulticastTTL(ttl)` +#### `socket.setMulticastTTL(ttl)` - + * `ttl` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) @@ -736,9 +736,9 @@ The `ttl` argument may be between 0 and 255. The default on most systems is `1`. This method throws `EBADF` if called on an unbound socket. -#### `socket.setRecvBufferSize(size)` +#### `socket.setRecvBufferSize(size)` - + * `size` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) @@ -747,9 +747,9 @@ in bytes. This method throws [`ERR_SOCKET_BUFFER_SIZE`][] if called on an unbound socket. -#### `socket.setSendBufferSize(size)` +#### `socket.setSendBufferSize(size)` - + * `size` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) @@ -758,9 +758,9 @@ in bytes. This method throws [`ERR_SOCKET_BUFFER_SIZE`][] if called on an unbound socket. -#### `socket.setTTL(ttl)` +#### `socket.setTTL(ttl)` - + * `ttl` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) @@ -775,9 +775,9 @@ is 64. This method throws `EBADF` if called on an unbound socket. -#### `socket.unref()` +#### `socket.unref()` - + * Returns: [`dgram.Socket`](/api/dgram#dgramsocket) @@ -792,11 +792,11 @@ Calling `socket.unref()` multiple times will have no addition effect. The `socket.unref()` method returns a reference to the socket so calls can be chained. -### `node:dgram` module functions +### `node:dgram` module functions -#### `dgram.createSocket(options[, callback])` +#### `dgram.createSocket(options[, callback])` - + * `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) Available options are: * `type` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The family of socket. Must be either `'udp4'` or `'udp6'`. @@ -830,15 +830,15 @@ const controller = new AbortController(); const { signal } = controller; const server = dgram.createSocket({ type: 'udp4', signal }); server.on('message', (msg, rinfo) => { - console.log(`server got: $msg from $rinfo.address:$rinfo.port`); + console.log(`server got: ${msg} from ${rinfo.address}:${rinfo.port}`); }); // Later, when you want to close the server. controller.abort(); ``` -#### `dgram.createSocket(type[, callback])` +#### `dgram.createSocket(type[, callback])` - + * `type` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) Either `'udp4'` or `'udp6'`. * `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) Attached as a listener to `'message'` events. diff --git a/content/api/v18/diagnostics_channel.en.md b/content/api/v18/diagnostics_channel.en.md index 3f304d3c50..5860178647 100644 --- a/content/api/v18/diagnostics_channel.en.md +++ b/content/api/v18/diagnostics_channel.en.md @@ -2,15 +2,15 @@ title: 'diagnostics_channel' displayTitle: 'Diagnostics Channel' category: 'api' -editPage: 'https://github.com/nodejs/node/blob/v18.8.0/doc/api/diagnostics_channel.md' +editPage: 'https://github.com/nodejs/node/blob/v18.9.0/doc/api/diagnostics_channel.md' version: 'v18' --- - + - + - + The `node:diagnostics_channel` module provides an API to create named channels to report arbitrary message data for diagnostics purposes. @@ -93,9 +93,9 @@ if (channel.hasSubscribers) { diagnostics_channel.unsubscribe('my-channel', onMessage); ``` -##### `diagnostics_channel.hasSubscribers(name)` +##### `diagnostics_channel.hasSubscribers(name)` - + * `name` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`symbol`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Symbol_type) The channel name * Returns: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) If there are active subscribers @@ -122,9 +122,9 @@ if (diagnostics_channel.hasSubscribers('my-channel')) { } ``` -##### `diagnostics_channel.channel(name)` +##### `diagnostics_channel.channel(name)` - + * `name` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`symbol`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Symbol_type) The channel name * Returns: [`Channel`](/api/diagnostics_channel#channel) The named channel object @@ -145,9 +145,9 @@ const diagnostics_channel = require('node:diagnostics_channel'); const channel = diagnostics_channel.channel('my-channel'); ``` -##### `diagnostics_channel.subscribe(name, onMessage)` +##### `diagnostics_channel.subscribe(name, onMessage)` - + * `name` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`symbol`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Symbol_type) The channel name * `onMessage` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) The handler to receive channel messages @@ -174,9 +174,9 @@ diagnostics_channel.subscribe('my-channel', (message, name) => { }); ``` -##### `diagnostics_channel.unsubscribe(name, onMessage)` +##### `diagnostics_channel.unsubscribe(name, onMessage)` - + * `name` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`symbol`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Symbol_type) The channel name * `onMessage` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) The previous subscribed handler to remove @@ -209,9 +209,9 @@ diagnostics_channel.subscribe('my-channel', onMessage); diagnostics_channel.unsubscribe('my-channel', onMessage); ``` -#### `Channel` +#### `Channel` - + The class `Channel` represents an individual named channel within the data pipeline. It is used to track subscribers and to publish messages when there @@ -221,9 +221,9 @@ for heavy use while incurring very minimal cost. Channels are created with [`diagnostics_channel.channel(name)`][], constructing a channel directly with `new Channel(name)` is not supported. -##### `channel.hasSubscribers` +##### `channel.hasSubscribers` - + * Returns: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) If there are active subscribers @@ -253,9 +253,9 @@ if (channel.hasSubscribers) { } ``` -##### `channel.publish(message)` +##### `channel.publish(message)` - + * `message` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) The message to send to the channel subscribers @@ -282,11 +282,11 @@ channel.publish({ }); ``` -##### `channel.subscribe(onMessage)` +##### `channel.subscribe(onMessage)` - + - + * `onMessage` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) The handler to receive channel messages * `message` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) The message data @@ -316,11 +316,11 @@ channel.subscribe((message, name) => { }); ``` -##### `channel.unsubscribe(onMessage)` +##### `channel.unsubscribe(onMessage)` - + - + * `onMessage` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) The previous subscribed handler to remove * Returns: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) `true` if the handler was found, `false` otherwise. diff --git a/content/api/v18/dns.en.md b/content/api/v18/dns.en.md index 908ef2d8bd..946237d921 100644 --- a/content/api/v18/dns.en.md +++ b/content/api/v18/dns.en.md @@ -2,15 +2,15 @@ title: 'dns' displayTitle: 'DNS' category: 'api' -editPage: 'https://github.com/nodejs/node/blob/v18.8.0/doc/api/dns.md' +editPage: 'https://github.com/nodejs/node/blob/v18.9.0/doc/api/dns.md' version: 'v18' --- - + - + - + The `node:dns` module enables name resolution. For example, use it to look up IP addresses of host names. @@ -49,7 +49,7 @@ dns.resolve4('archive.org', (err, addresses) => { if (err) { throw err; } - console.log(`reverse for $a: ${JSON.stringify(hostnames)}`); + console.log(`reverse for ${a}: ${JSON.stringify(hostnames)}`); }); }); }); @@ -57,9 +57,9 @@ dns.resolve4('archive.org', (err, addresses) => { See the [Implementation considerations section][] for more information. -### `dns.Resolver` +### `dns.Resolver` - + An independent resolver for DNS requests. @@ -98,9 +98,9 @@ The following methods from the `node:dns` module are available: * [`resolver.reverse()`][`dns.reverse()`] * [`resolver.setServers()`][`dns.setServers()`] -#### `Resolver([options])` +#### `Resolver([options])` - + Create a new resolver. @@ -110,16 +110,16 @@ Create a new resolver. * `tries` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The number of tries the resolver will try contacting each name server before giving up. **Default:** `4` -#### `resolver.cancel()` +#### `resolver.cancel()` - + Cancel all outstanding DNS queries made by this resolver. The corresponding callbacks will be called with an error with code `ECANCELLED`. -#### `resolver.setLocalAddress([ipv4][, ipv6])` +#### `resolver.setLocalAddress([ipv4][, ipv6])` - + * `ipv4` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) A string representation of an IPv4 address. **Default:** `'0.0.0.0'` @@ -137,9 +137,9 @@ The resolver will use the v4 local address when making requests to IPv4 DNS servers, and the v6 local address when making requests to IPv6 DNS servers. The `rrtype` of resolution requests has no impact on the local address used. -### `dns.getServers()` +### `dns.getServers()` - + * Returns: string\[] @@ -158,12 +158,12 @@ section if a custom port is used. ] ``` -### `dns.lookup(hostname[, options], callback)` +### `dns.lookup(hostname[, options], callback)` - + * `hostname` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) -* `options` {integer | Object} +* `options` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) | [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) * `family` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The record family. Must be `4`, `6`, or `0`. For backward compatibility reasons,`'IPv4'` and `'IPv6'` are interpreted as `4` and `6` respectively. The value `0` indicates that IPv4 and IPv6 addresses @@ -231,7 +231,7 @@ is not set to `true`, it returns a `Promise` for an `Object` with `address` and #### Supported getaddrinfo flags - + The following flags can be passed as hints to [`dns.lookup()`][]. @@ -244,9 +244,9 @@ The following flags can be passed as hints to [`dns.lookup()`][]. * `dns.ALL`: If `dns.V4MAPPED` is specified, return resolved IPv6 addresses as well as IPv4 mapped IPv6 addresses. -### `dns.lookupService(address, port, callback)` +### `dns.lookupService(address, port, callback)` - + * `address` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) * `port` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) @@ -275,15 +275,15 @@ dns.lookupService('127.0.0.1', 22, (err, hostname, service) => { If this method is invoked as its [`util.promisify()`][]ed version, it returns a `Promise` for an `Object` with `hostname` and `service` properties. -### `dns.resolve(hostname[, rrtype], callback)` +### `dns.resolve(hostname[, rrtype], callback)` - + * `hostname` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) Host name to resolve. * `rrtype` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) Resource record type. **Default:** `'A'`. * `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) * `err` [`Error`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error) - * `records` {string\[] | Object\[] | Object} + * `records` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) Uses the DNS protocol to resolve a host name (e.g. `'nodejs.org'`) into an array of the resource records. The `callback` function has arguments @@ -308,46 +308,46 @@ records. The type and structure of individual results varies based on `rrtype`: On error, `err` is an [`Error`][] object, where `err.code` is one of the [DNS error codes][]. -### `dns.resolve4(hostname[, options], callback)` +### `dns.resolve4(hostname[, options], callback)` - + * `hostname` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) Host name to resolve. * `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) * `ttl` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) Retrieves the Time-To-Live value (TTL) of each record. When `true`, the callback receives an array of - `{ address: '1.2.3.4', ttl: 60 }` objects rather than an array of strings, + ````{ address: '1.2.3.4', ttl: 60 }```` objects rather than an array of strings, with the TTL expressed in seconds. * `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) * `err` [`Error`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error) - * `addresses` {string\[] | Object\[]} + * `addresses` string\[] | Object\[] Uses the DNS protocol to resolve a IPv4 addresses (`A` records) for the `hostname`. The `addresses` argument passed to the `callback` function will contain an array of IPv4 addresses (e.g. `['74.125.79.104', '74.125.79.105', '74.125.79.106']`). -### `dns.resolve6(hostname[, options], callback)` +### `dns.resolve6(hostname[, options], callback)` - + * `hostname` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) Host name to resolve. * `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) * `ttl` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) Retrieve the Time-To-Live value (TTL) of each record. When `true`, the callback receives an array of - `{ address: '0:1:2:3:4:5:6:7', ttl: 60 }` objects rather than an array of + ````{ address: '0:1:2:3:4:5:6:7', ttl: 60 }```` objects rather than an array of strings, with the TTL expressed in seconds. * `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) * `err` [`Error`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error) - * `addresses` {string\[] | Object\[]} + * `addresses` string\[] | Object\[] Uses the DNS protocol to resolve IPv6 addresses (`AAAA` records) for the `hostname`. The `addresses` argument passed to the `callback` function will contain an array of IPv6 addresses. -### `dns.resolveAny(hostname, callback)` +### `dns.resolveAny(hostname, callback)` - + * `hostname` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) * `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) @@ -371,7 +371,7 @@ will be present on the object: | `'PTR'` | `value` | | `'SOA'` | Refer to [`dns.resolveSoa()`][] | | `'SRV'` | Refer to [`dns.resolveSrv()`][] | -| `'TXT'` | This type of record contains an array property called `entries` which refers to [`dns.resolveTxt()`][], e.g. `{ entries: ['...'], type: 'TXT' }` | +| `'TXT'` | This type of record contains an array property called `entries` which refers to [`dns.resolveTxt()`][], e.g. ````{ entries: ['...'], type: 'TXT' }```` | Here is an example of the `ret` object passed to the callback: @@ -397,9 +397,9 @@ DNS server operators may choose not to respond to `ANY` queries. It may be better to call individual methods like [`dns.resolve4()`][], [`dns.resolveMx()`][], and so on. For more details, see [RFC 8482][]. -### `dns.resolveCname(hostname, callback)` +### `dns.resolveCname(hostname, callback)` - + * `hostname` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) * `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) @@ -411,9 +411,9 @@ Uses the DNS protocol to resolve `CNAME` records for the `hostname`. The will contain an array of canonical name records available for the `hostname` (e.g. `['bar.example.com']`). -### `dns.resolveCaa(hostname, callback)` +### `dns.resolveCaa(hostname, callback)` - + * `hostname` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) * `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) @@ -424,11 +424,11 @@ Uses the DNS protocol to resolve `CAA` records for the `hostname`. The `addresses` argument passed to the `callback` function will contain an array of certification authority authorization records available for the `hostname` (e.g. `[{critical: 0, iodef: -'mailto:pki@example.com'}, {critical: 128, issue: 'pki.example.com'}]`). +'mailto:pki@example.com'}, ```{critical: 128, issue: 'pki.example.com'}```]`). -### `dns.resolveMx(hostname, callback)` +### `dns.resolveMx(hostname, callback)` - + * `hostname` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) * `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) @@ -438,11 +438,11 @@ available for the `hostname` (e.g. `[{critical: 0, iodef: Uses the DNS protocol to resolve mail exchange records (`MX` records) for the `hostname`. The `addresses` argument passed to the `callback` function will contain an array of objects containing both a `priority` and `exchange` -property (e.g. `[{priority: 10, exchange: 'mx.example.com'}, ...]`). +property (e.g. `[```{priority: 10, exchange: 'mx.example.com'}```, ...]`). -### `dns.resolveNaptr(hostname, callback)` +### `dns.resolveNaptr(hostname, callback)` - + * `hostname` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) * `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) @@ -473,9 +473,9 @@ function will contain an array of objects with the following properties: } ``` -### `dns.resolveNs(hostname, callback)` +### `dns.resolveNs(hostname, callback)` - + * `hostname` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) * `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) @@ -487,9 +487,9 @@ Uses the DNS protocol to resolve name server records (`NS` records) for the contain an array of name server records available for `hostname` (e.g. `['ns1.example.com', 'ns2.example.com']`). -### `dns.resolvePtr(hostname, callback)` +### `dns.resolvePtr(hostname, callback)` - + * `hostname` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) * `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) @@ -500,9 +500,9 @@ Uses the DNS protocol to resolve pointer records (`PTR` records) for the `hostname`. The `addresses` argument passed to the `callback` function will be an array of strings containing the reply records. -### `dns.resolveSoa(hostname, callback)` +### `dns.resolveSoa(hostname, callback)` - + * `hostname` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) * `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) @@ -535,9 +535,9 @@ be an object with the following properties: } ``` -### `dns.resolveSrv(hostname, callback)` +### `dns.resolveSrv(hostname, callback)` - + * `hostname` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) * `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) @@ -564,9 +564,9 @@ be an array of objects with the following properties: } ``` -### `dns.resolveTxt(hostname, callback)` +### `dns.resolveTxt(hostname, callback)` - + @@ -584,9 +584,9 @@ two-dimensional array of the text records available for `hostname` (e.g. one record. Depending on the use case, these could be either joined together or treated separately. -### `dns.reverse(ip, callback)` +### `dns.reverse(ip, callback)` - + * `ip` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) * `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) @@ -599,9 +599,9 @@ array of host names. On error, `err` is an [`Error`][] object, where `err.code` is one of the [DNS error codes][]. -### `dns.setDefaultResultOrder(order)` +### `dns.setDefaultResultOrder(order)` - + * `order` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) must be `'ipv4first'` or `'verbatim'`. @@ -616,9 +616,9 @@ priority than [`--dns-result-order`][]. When using [worker threads][], [`dns.setDefaultResultOrder()`][] from the main thread won't affect the default dns orders in workers. -### `dns.setServers(servers)` +### `dns.setServers(servers)` - + * `servers` string\[] array of [RFC 5952][] formatted addresses @@ -653,15 +653,15 @@ earlier ones time out or result in some other error. ### DNS promises API - + The `dns.promises` API provides an alternative set of asynchronous DNS methods that return `Promise` objects rather than using callbacks. The API is accessible via `require('node:dns').promises` or `require('node:dns/promises')`. -#### `dnsPromises.Resolver` +#### `dnsPromises.Resolver` - + An independent resolver for DNS requests. @@ -705,16 +705,16 @@ The following methods from the `dnsPromises` API are available: * [`resolver.reverse()`][`dnsPromises.reverse()`] * [`resolver.setServers()`][`dnsPromises.setServers()`] -#### `resolver.cancel()` +#### `resolver.cancel()` - + Cancel all outstanding DNS queries made by this resolver. The corresponding promises will be rejected with an error with the code `ECANCELLED`. -#### `dnsPromises.getServers()` +#### `dnsPromises.getServers()` - + * Returns: string\[] @@ -733,12 +733,12 @@ section if a custom port is used. ] ``` -#### `dnsPromises.lookup(hostname[, options])` +#### `dnsPromises.lookup(hostname[, options])` - + * `hostname` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) -* `options` {integer | Object} +* `options` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) | [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) * `family` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The record family. Must be `4`, `6`, or `0`. The value `0` indicates that IPv4 and IPv6 addresses are both returned. **Default:** `0`. @@ -752,7 +752,7 @@ section if a custom port is used. **Default:** currently `false` (addresses are reordered) but this is expected to change in the not too distant future. Default value is configurable using [`dns.setDefaultResultOrder()`][] or - [`--dns-result-order`][]. New code should use `{ verbatim: true }`. + [`--dns-result-order`][]. New code should use ````{ verbatim: true }````. Resolves a host name (e.g. `'nodejs.org'`) into the first found A (IPv4) or AAAA (IPv6) record. All `option` properties are optional. If `options` is an @@ -798,9 +798,9 @@ dnsPromises.lookup('example.com', options).then((result) => { }); ``` -#### `dnsPromises.lookupService(address, port)` +#### `dnsPromises.lookupService(address, port)` - + * `address` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) * `port` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) @@ -823,9 +823,9 @@ dnsPromises.lookupService('127.0.0.1', 22).then((result) => { }); ``` -#### `dnsPromises.resolve(hostname[, rrtype])` +#### `dnsPromises.resolve(hostname[, rrtype])` - + * `hostname` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) Host name to resolve. * `rrtype` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) Resource record type. **Default:** `'A'`. @@ -853,39 +853,39 @@ based on `rrtype`: On error, the `Promise` is rejected with an [`Error`][] object, where `err.code` is one of the [DNS error codes][]. -#### `dnsPromises.resolve4(hostname[, options])` +#### `dnsPromises.resolve4(hostname[, options])` - + * `hostname` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) Host name to resolve. * `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) * `ttl` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) Retrieve the Time-To-Live value (TTL) of each record. When `true`, the `Promise` is resolved with an array of - `{ address: '1.2.3.4', ttl: 60 }` objects rather than an array of strings, + ````{ address: '1.2.3.4', ttl: 60 }```` objects rather than an array of strings, with the TTL expressed in seconds. Uses the DNS protocol to resolve IPv4 addresses (`A` records) for the `hostname`. On success, the `Promise` is resolved with an array of IPv4 addresses (e.g. `['74.125.79.104', '74.125.79.105', '74.125.79.106']`). -#### `dnsPromises.resolve6(hostname[, options])` +#### `dnsPromises.resolve6(hostname[, options])` - + * `hostname` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) Host name to resolve. * `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) * `ttl` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) Retrieve the Time-To-Live value (TTL) of each record. When `true`, the `Promise` is resolved with an array of - `{ address: '0:1:2:3:4:5:6:7', ttl: 60 }` objects rather than an array of + ````{ address: '0:1:2:3:4:5:6:7', ttl: 60 }```` objects rather than an array of strings, with the TTL expressed in seconds. Uses the DNS protocol to resolve IPv6 addresses (`AAAA` records) for the `hostname`. On success, the `Promise` is resolved with an array of IPv6 addresses. -#### `dnsPromises.resolveAny(hostname)` +#### `dnsPromises.resolveAny(hostname)` - + * `hostname` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) @@ -906,7 +906,7 @@ present on the object: | `'PTR'` | `value` | | `'SOA'` | Refer to [`dnsPromises.resolveSoa()`][] | | `'SRV'` | Refer to [`dnsPromises.resolveSrv()`][] | -| `'TXT'` | This type of record contains an array property called `entries` which refers to [`dnsPromises.resolveTxt()`][], e.g. `{ entries: ['...'], type: 'TXT' }` | +| `'TXT'` | This type of record contains an array property called `entries` which refers to [`dnsPromises.resolveTxt()`][], e.g. ````{ entries: ['...'], type: 'TXT' }```` | Here is an example of the result object: @@ -928,21 +928,21 @@ Here is an example of the result object: minttl: 60 } ] ``` -#### `dnsPromises.resolveCaa(hostname)` +#### `dnsPromises.resolveCaa(hostname)` - + * `hostname` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) Uses the DNS protocol to resolve `CAA` records for the `hostname`. On success, the `Promise` is resolved with an array of objects containing available certification authority authorization records available for the `hostname` -(e.g. `[{critical: 0, iodef: 'mailto:pki@example.com'},{critical: 128, issue: +(e.g. `[```{critical: 0, iodef: 'mailto:pki@example.com'}```,{critical: 128, issue: 'pki.example.com'}]`). -#### `dnsPromises.resolveCname(hostname)` +#### `dnsPromises.resolveCname(hostname)` - + * `hostname` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) @@ -950,20 +950,20 @@ Uses the DNS protocol to resolve `CNAME` records for the `hostname`. On success, the `Promise` is resolved with an array of canonical name records available for the `hostname` (e.g. `['bar.example.com']`). -#### `dnsPromises.resolveMx(hostname)` +#### `dnsPromises.resolveMx(hostname)` - + * `hostname` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) Uses the DNS protocol to resolve mail exchange records (`MX` records) for the `hostname`. On success, the `Promise` is resolved with an array of objects containing both a `priority` and `exchange` property (e.g. -`[{priority: 10, exchange: 'mx.example.com'}, ...]`). +`[```{priority: 10, exchange: 'mx.example.com'}```, ...]`). -#### `dnsPromises.resolveNaptr(hostname)` +#### `dnsPromises.resolveNaptr(hostname)` - + * `hostname` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) @@ -991,9 +991,9 @@ of objects with the following properties: } ``` -#### `dnsPromises.resolveNs(hostname)` +#### `dnsPromises.resolveNs(hostname)` - + * `hostname` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) @@ -1002,9 +1002,9 @@ Uses the DNS protocol to resolve name server records (`NS` records) for the records available for `hostname` (e.g. `['ns1.example.com', 'ns2.example.com']`). -#### `dnsPromises.resolvePtr(hostname)` +#### `dnsPromises.resolvePtr(hostname)` - + * `hostname` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) @@ -1012,9 +1012,9 @@ Uses the DNS protocol to resolve pointer records (`PTR` records) for the `hostname`. On success, the `Promise` is resolved with an array of strings containing the reply records. -#### `dnsPromises.resolveSoa(hostname)` +#### `dnsPromises.resolveSoa(hostname)` - + * `hostname` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) @@ -1044,9 +1044,9 @@ following properties: } ``` -#### `dnsPromises.resolveSrv(hostname)` +#### `dnsPromises.resolveSrv(hostname)` - + * `hostname` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) @@ -1070,9 +1070,9 @@ the following properties: } ``` -#### `dnsPromises.resolveTxt(hostname)` +#### `dnsPromises.resolveTxt(hostname)` - + * `hostname` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) @@ -1083,9 +1083,9 @@ of the text records available for `hostname` (e.g. one record. Depending on the use case, these could be either joined together or treated separately. -#### `dnsPromises.reverse(ip)` +#### `dnsPromises.reverse(ip)` - + * `ip` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) @@ -1095,9 +1095,9 @@ array of host names. On error, the `Promise` is rejected with an [`Error`][] object, where `err.code` is one of the [DNS error codes][]. -#### `dnsPromises.setDefaultResultOrder(order)` +#### `dnsPromises.setDefaultResultOrder(order)` - + * `order` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) must be `'ipv4first'` or `'verbatim'`. @@ -1112,9 +1112,9 @@ higher priority than [`--dns-result-order`][]. When using [worker threads][], [`dnsPromises.setDefaultResultOrder()`][] from the main thread won't affect the default dns orders in workers. -#### `dnsPromises.setServers(servers)` +#### `dnsPromises.setServers(servers)` - + * `servers` string\[] array of [RFC 5952][] formatted addresses @@ -1182,7 +1182,7 @@ address (or vice versa), their behavior is quite different. These differences can have subtle but significant consequences on the behavior of Node.js programs. -#### `dns.lookup()` +#### `dns.lookup()` Under the hood, [`dns.lookup()`][] uses the same operating system facilities as most other programs. For instance, [`dns.lookup()`][] will almost always @@ -1204,7 +1204,7 @@ using `dns.resolve()` and using the address instead of a host name. Also, some networking APIs (such as [`socket.connect()`][] and [`dgram.createSocket()`][]) allow the default resolver, `dns.lookup()`, to be replaced. -#### `dns.resolve()`, `dns.resolve*()`, and `dns.reverse()` +#### `dns.resolve()`, `dns.resolve*()`, and `dns.reverse()` These functions are implemented quite differently than [`dns.lookup()`][]. They do not use getaddrinfo(3) and they _always_ perform a DNS query on the diff --git a/content/api/v18/documentation.en.md b/content/api/v18/documentation.en.md index e20361be72..7fa501349c 100644 --- a/content/api/v18/documentation.en.md +++ b/content/api/v18/documentation.en.md @@ -2,13 +2,13 @@ title: 'documentation' displayTitle: 'About this documentation' category: 'api' -editPage: 'https://github.com/nodejs/node/blob/v18.8.0/doc/api/documentation.md' +editPage: 'https://github.com/nodejs/node/blob/v18.9.0/doc/api/documentation.md' version: 'v18' --- - + - + Welcome to the official API reference documentation for Node.js! @@ -21,7 +21,7 @@ Report errors in this documentation in [the issue tracker][]. See ### Stability index - + Throughout the documentation are indications of a section's stability. Some APIs are so proven and so relied upon that they are unlikely to ever change at all. @@ -29,19 +29,19 @@ Others are brand new and experimental, or known to be hazardous. The stability indices are as follows: - compatibility is not guaranteed."}}} /> + - [semantic versioning][] rules. Non-backward compatible changes or removal may\n> occur in any future release. Use of the feature is not recommended in\n> production environments."}}} /> + occur in any future release. Use of the feature is not recommended in\n> production environments."}}} /> - priority."}}} /> + - still covered by semantic versioning guarantees, it is no longer actively\n> maintained, and other alternatives are available."}}} /> + maintained, and other alternatives are available."}}} /> Features are marked as legacy rather than being deprecated if their use does no harm, and they are widely relied upon within the npm ecosystem. Bugs found in @@ -61,7 +61,7 @@ a command-line flag. Experimental features may also emit a [warning][]. ### JSON output - + Every `.html` document has a corresponding `.json` document. This is for IDEs and other utilities that consume the documentation. diff --git a/content/api/v18/domain.en.md b/content/api/v18/domain.en.md index 1a3b3226cd..ea4a46dde1 100644 --- a/content/api/v18/domain.en.md +++ b/content/api/v18/domain.en.md @@ -2,17 +2,17 @@ title: 'domain' displayTitle: 'Domain' category: 'api' -editPage: 'https://github.com/nodejs/node/blob/v18.8.0/doc/api/domain.md' +editPage: 'https://github.com/nodejs/node/blob/v18.9.0/doc/api/domain.md' version: 'v18' --- - + - + - + - + **This module is pending deprecation.** Once a replacement API has been finalized, this module will be fully deprecated. Most developers should @@ -30,7 +30,7 @@ exit immediately with an error code. ### Warning: Don't ignore errors! - + Domain error handlers are not a substitute for closing down a process when an error occurs. @@ -65,7 +65,7 @@ d.on('error', (er) => { // Though we've prevented abrupt process restarting, we are leaking // a lot of resources if this ever happens. // This is no better than process.on('uncaughtException')! - console.log(`error, but oh well $er.message`); + console.log(`error, but oh well ${er.message}`); }); d.run(() => { require('node:http').createServer((req, res) => { @@ -118,7 +118,7 @@ if (cluster.isPrimary) { const server = require('node:http').createServer((req, res) => { const d = domain.create(); d.on('error', (er) => { - console.error(`error $er.stack`); + console.error(`error ${er.stack}`); // We're in dangerous territory! // By definition, something unexpected occurred, @@ -184,7 +184,7 @@ function handleRequest(req, res) { ### Additions to `Error` objects - + Any time an `Error` object is routed through a domain, a few extra fields are added to it. @@ -199,7 +199,7 @@ are added to it. ### Implicit binding - + If domains are in use, then all **new** `EventEmitter` objects (including Stream objects, requests, responses, etc.) will be implicitly bound to @@ -225,7 +225,7 @@ Implicit binding only takes care of thrown errors and `'error'` events. ### Explicit binding - + Sometimes, the domain in use is not the one that ought to be used for a specific event emitter. Or, the event emitter could have been created @@ -265,11 +265,11 @@ serverDomain.run(() => { }); ``` -### `domain.create()` +### `domain.create()` * Returns: [`Domain`](/api/domain#domain) -### `Domain` +### `Domain` * Extends: [`EventEmitter`](/api/events#eventemitter) @@ -278,14 +278,14 @@ uncaught exceptions to the active `Domain` object. To handle the errors that it catches, listen to its `'error'` event. -#### `domain.members` +#### `domain.members` * [`Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array) An array of timers and event emitters that have been explicitly added to the domain. -#### `domain.add(emitter)` +#### `domain.add(emitter)` * `emitter` [`EventEmitter`](/api/events#eventemitter) | [`Timer`](/api/timers#timers) emitter or timer to be added to the domain @@ -301,7 +301,7 @@ the domain `'error'` handler. If the Timer or `EventEmitter` was already bound to a domain, it is removed from that one, and bound to this one instead. -#### `domain.bind(callback)` +#### `domain.bind(callback)` * `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) The callback function * Returns: [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) The bound function @@ -326,7 +326,7 @@ d.on('error', (er) => { }); ``` -#### `domain.enter()` +#### `domain.enter()` The `enter()` method is plumbing used by the `run()`, `bind()`, and `intercept()` methods to set the active domain. It sets `domain.active` and @@ -339,7 +339,7 @@ Calling `enter()` changes only the active domain, and does not alter the domain itself. `enter()` and `exit()` can be called an arbitrary number of times on a single domain. -#### `domain.exit()` +#### `domain.exit()` The `exit()` method exits the current domain, popping it off the domain stack. Any time execution is going to switch to the context of a different chain of @@ -354,7 +354,7 @@ Calling `exit()` changes only the active domain, and does not alter the domain itself. `enter()` and `exit()` can be called an arbitrary number of times on a single domain. -#### `domain.intercept(callback)` +#### `domain.intercept(callback)` * `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) The callback function * Returns: [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) The intercepted function @@ -389,14 +389,14 @@ d.on('error', (er) => { }); ``` -#### `domain.remove(emitter)` +#### `domain.remove(emitter)` * `emitter` [`EventEmitter`](/api/events#eventemitter) | [`Timer`](/api/timers#timers) emitter or timer to be removed from the domain The opposite of [`domain.add(emitter)`][]. Removes domain handling from the specified emitter. -#### `domain.run(fn[, ...args])` +#### `domain.run(fn[, ...args])` * `fn` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) * `...args` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) diff --git a/content/api/v18/embedding.en.md b/content/api/v18/embedding.en.md index 6d3703cf16..1330ec8c6d 100644 --- a/content/api/v18/embedding.en.md +++ b/content/api/v18/embedding.en.md @@ -2,11 +2,11 @@ title: 'embedding' displayTitle: 'C++ embedder API' category: 'api' -editPage: 'https://github.com/nodejs/node/blob/v18.8.0/doc/api/embedding.md' +editPage: 'https://github.com/nodejs/node/blob/v18.9.0/doc/api/embedding.md' version: 'v18' --- - + Node.js provides a number of C++ APIs that can be used to execute JavaScript in a Node.js environment from other C++ software. @@ -74,7 +74,7 @@ int main(int argc, char** argv) { #### Per-instance state - + Node.js has a concept of a “Node.js instance”, that is commonly being referred to as `node::Environment`. Each `node::Environment` is associated with: diff --git a/content/api/v18/errors.en.md b/content/api/v18/errors.en.md index 36ef452252..18502069b7 100644 --- a/content/api/v18/errors.en.md +++ b/content/api/v18/errors.en.md @@ -2,13 +2,13 @@ title: 'errors' displayTitle: 'Errors' category: 'api' -editPage: 'https://github.com/nodejs/node/blob/v18.8.0/doc/api/errors.md' +editPage: 'https://github.com/nodejs/node/blob/v18.9.0/doc/api/errors.md' version: 'v18' --- - + - + Applications running in Node.js will generally experience four categories of errors: @@ -29,7 +29,7 @@ to provide _at least_ the properties available on that class. ### Error propagation and interception - + Node.js supports several mechanisms for propagating and handling errors that occur while an application is running. How these errors are reported and @@ -133,7 +133,7 @@ exactly how errors raised by those methods are propagated. #### Error-first callbacks - + Most asynchronous methods exposed by the Node.js core API follow an idiomatic pattern referred to as an _error-first callback_. With this pattern, a callback @@ -185,9 +185,9 @@ Throwing an error inside the callback **can crash the Node.js process** in most cases. If [domains][] are enabled, or a handler has been registered with `process.on('uncaughtException')`, such errors can be intercepted. -### `Error` +### `Error` - + A generic JavaScript [`Error`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error) object that does not denote any specific circumstance of why the error occurred. `Error` objects capture a "stack trace" @@ -197,7 +197,7 @@ provide a text description of the error. All errors generated by Node.js, including all system and JavaScript errors, will either be instances of, or inherit from, the `Error` class. -#### `new Error(message[, options])` +#### `new Error(message[, options])` * `message` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) * `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) @@ -212,7 +212,7 @@ are dependent on [V8's stack trace API][]. Stack traces extend only to either (a) the beginning of _synchronous code execution_, or (b) the number of frames given by the property `Error.stackTraceLimit`, whichever is smaller. -#### `Error.captureStackTrace(targetObject[, constructorOpt])` +#### `Error.captureStackTrace(targetObject[, constructorOpt])` * `targetObject` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) * `constructorOpt` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) @@ -248,7 +248,7 @@ function MyError() { new MyError().stack; ``` -#### `Error.stackTraceLimit` +#### `Error.stackTraceLimit` * [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) @@ -262,9 +262,9 @@ will affect any stack trace captured _after_ the value has been changed. If set to a non-number value, or set to a negative number, stack traces will not capture any frames. -#### `error.cause` +#### `error.cause` - + * [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) @@ -273,7 +273,7 @@ It is used when catching an error and throwing a new one with a different message or code in order to still have access to the original error. The `error.cause` property is typically set by calling -`new Error(message, { cause })`. It is not set by the constructor if the +`new Error(message, cause )`. It is not set by the constructor if the `cause` option is not provided. This property allows errors to be chained. When serializing `Error` objects, @@ -303,7 +303,7 @@ console.log(symptom); // at [_line] [as _line] (node:internal/readline/interface:886:18) ``` -#### `error.code` +#### `error.code` * [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) @@ -313,7 +313,7 @@ between major versions of Node.js. In contrast, `error.message` strings may change between any versions of Node.js. See [Node.js error codes][] for details about specific codes. -#### `error.message` +#### `error.message` * [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) @@ -330,7 +330,7 @@ console.error(err.message); // Prints: The message ``` -#### `error.stack` +#### `error.stack` * [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) @@ -406,14 +406,14 @@ The number of frames captured by the stack trace is bounded by the smaller of `Error.stackTraceLimit` or the number of available frames on the current event loop tick. -### `AssertionError` +### `AssertionError` * Extends: [`errors.Error`](/api/errors#error) Indicates the failure of an assertion. For details, see [`Class: assert.AssertionError`][]. -### `RangeError` +### `RangeError` * Extends: [`errors.Error`](/api/errors#error) @@ -429,7 +429,7 @@ require('node:net').connect(-1); Node.js will generate and throw `RangeError` instances _immediately_ as a form of argument validation. -### `ReferenceError` +### `ReferenceError` * Extends: [`errors.Error`](/api/errors#error) @@ -448,7 +448,7 @@ doesNotExist; Unless an application is dynamically generating and running code, `ReferenceError` instances indicate a bug in the code or its dependencies. -### `SyntaxError` +### `SyntaxError` * Extends: [`errors.Error`](/api/errors#error) @@ -468,7 +468,7 @@ try { `SyntaxError` instances are unrecoverable in the context that created them – they may only be caught by other contexts. -### `SystemError` +### `SystemError` * Extends: [`errors.Error`](/api/errors#error) @@ -489,27 +489,27 @@ attempts to read a file that does not exist. * `port` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) If present, the network connection port that is not available * `syscall` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The name of the system call that triggered the error -#### `error.address` +#### `error.address` * [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) If present, `error.address` is a string describing the address to which a network connection failed. -#### `error.code` +#### `error.code` * [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The `error.code` property is a string representing the error code. -#### `error.dest` +#### `error.dest` * [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) If present, `error.dest` is the file path destination when reporting a file system error. -#### `error.errno` +#### `error.errno` * [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) @@ -521,31 +521,31 @@ On Windows the error number provided by the system will be normalized by libuv. To get the string representation of the error code, use [`util.getSystemErrorName(error.errno)`][]. -#### `error.info` +#### `error.info` * [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) If present, `error.info` is an object with details about the error condition. -#### `error.message` +#### `error.message` * [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) `error.message` is a system-provided human-readable description of the error. -#### `error.path` +#### `error.path` * [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) If present, `error.path` is a string containing a relevant invalid pathname. -#### `error.port` +#### `error.port` * [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) If present, `error.port` is the network connection port that is not available. -#### `error.syscall` +#### `error.syscall` * [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) @@ -612,7 +612,7 @@ program. For a comprehensive list, see the [`errno`(3) man page][]. encountered by [`http`][] or [`net`][]. Often a sign that a `socket.end()` was not properly called. -### `TypeError` +### `TypeError` * Extends [`errors.Error`](/api/errors#error) @@ -629,7 +629,7 @@ of argument validation. ### Exceptions vs. errors - + A JavaScript exception is a value that is thrown as a result of an invalid operation or as the target of a `throw` statement. While it is not required @@ -647,20 +647,20 @@ Errors originating in `crypto` or `tls` are of class `Error`, and in addition to the standard `.code` and `.message` properties, may have some additional OpenSSL-specific properties. -#### `error.opensslErrorStack` +#### `error.opensslErrorStack` An array of errors that can give context to where in the OpenSSL library an error originates from. -#### `error.function` +#### `error.function` The OpenSSL function the error originates in. -#### `error.library` +#### `error.library` The OpenSSL library the error originates in. -#### `error.reason` +#### `error.reason` A human-readable string describing the reason for the error. @@ -670,9 +670,9 @@ A human-readable string describing the reason for the error. -#### `ABORT_ERR` +#### `ABORT_ERR` - + Used when an operation has been aborted (typically using an `AbortController`). @@ -683,7 +683,7 @@ order to be compatible with the web platform's `AbortError`. -#### `ERR_AMBIGUOUS_ARGUMENT` +#### `ERR_AMBIGUOUS_ARGUMENT` A function argument is being used in a way that suggests that the function signature may be misunderstood. This is thrown by the `node:assert` module when @@ -694,14 +694,14 @@ will display if `block` does not throw. -#### `ERR_ARG_NOT_ITERABLE` +#### `ERR_ARG_NOT_ITERABLE` An iterable argument (i.e. a value that works with `for...of` loops) was required, but not provided to a Node.js API. -#### `ERR_ASSERTION` +#### `ERR_ASSERTION` A special type of error that can be triggered whenever Node.js detects an exceptional logic violation that should never occur. These are raised typically @@ -709,40 +709,40 @@ by the `node:assert` module. -#### `ERR_ASSERT_SNAPSHOT_NOT_SUPPORTED` +#### `ERR_ASSERT_SNAPSHOT_NOT_SUPPORTED` An attempt was made to use `assert.snapshot()` in an environment that does not support snapshots, such as the REPL, or when using `node --eval`. -#### `ERR_ASYNC_CALLBACK` +#### `ERR_ASYNC_CALLBACK` An attempt was made to register something that is not a function as an `AsyncHooks` callback. -#### `ERR_ASYNC_TYPE` +#### `ERR_ASYNC_TYPE` The type of an asynchronous resource was invalid. Users are also able to define their own types if using the public embedder API. -#### `ERR_BROTLI_COMPRESSION_FAILED` +#### `ERR_BROTLI_COMPRESSION_FAILED` Data passed to a Brotli stream was not successfully compressed. -#### `ERR_BROTLI_INVALID_PARAM` +#### `ERR_BROTLI_INVALID_PARAM` An invalid parameter key was passed during construction of a Brotli stream. -#### `ERR_BUFFER_CONTEXT_NOT_AVAILABLE` +#### `ERR_BUFFER_CONTEXT_NOT_AVAILABLE` An attempt was made to create a Node.js `Buffer` instance from addon or embedder code, while in a JS engine Context that is not associated with a Node.js @@ -756,75 +756,75 @@ Node.js core APIs where `Buffer`s are; they are available in all Contexts. -#### `ERR_BUFFER_OUT_OF_BOUNDS` +#### `ERR_BUFFER_OUT_OF_BOUNDS` An operation outside the bounds of a `Buffer` was attempted. -#### `ERR_BUFFER_TOO_LARGE` +#### `ERR_BUFFER_TOO_LARGE` An attempt has been made to create a `Buffer` larger than the maximum allowed size. -#### `ERR_CANNOT_WATCH_SIGINT` +#### `ERR_CANNOT_WATCH_SIGINT` Node.js was unable to watch for the `SIGINT` signal. -#### `ERR_CHILD_CLOSED_BEFORE_REPLY` +#### `ERR_CHILD_CLOSED_BEFORE_REPLY` A child process was closed before the parent received a reply. -#### `ERR_CHILD_PROCESS_IPC_REQUIRED` +#### `ERR_CHILD_PROCESS_IPC_REQUIRED` Used when a child process is being forked without specifying an IPC channel. -#### `ERR_CHILD_PROCESS_STDIO_MAXBUFFER` +#### `ERR_CHILD_PROCESS_STDIO_MAXBUFFER` Used when the main process is trying to read data from the child process's STDERR/STDOUT, and the data's length is longer than the `maxBuffer` option. -#### `ERR_CLOSED_MESSAGE_PORT` +#### `ERR_CLOSED_MESSAGE_PORT` - + There was an attempt to use a `MessagePort` instance in a closed state, usually after `.close()` has been called. -#### `ERR_CONSOLE_WRITABLE_STREAM` +#### `ERR_CONSOLE_WRITABLE_STREAM` `Console` was instantiated without `stdout` stream, or `Console` has a non-writable `stdout` or `stderr` stream. -#### `ERR_CONSTRUCT_CALL_INVALID` +#### `ERR_CONSTRUCT_CALL_INVALID` - + A class constructor was called that is not callable. -#### `ERR_CONSTRUCT_CALL_REQUIRED` +#### `ERR_CONSTRUCT_CALL_REQUIRED` A constructor for a class was called without `new`. -#### `ERR_CONTEXT_NOT_INITIALIZED` +#### `ERR_CONTEXT_NOT_INITIALIZED` The vm context passed into the API is not yet initialized. This could happen when an error occurs (and is caught) during the creation of the @@ -833,21 +833,21 @@ size is reached when the context is created. -#### `ERR_CRYPTO_CUSTOM_ENGINE_NOT_SUPPORTED` +#### `ERR_CRYPTO_CUSTOM_ENGINE_NOT_SUPPORTED` A client certificate engine was requested that is not supported by the version of OpenSSL being used. -#### `ERR_CRYPTO_ECDH_INVALID_FORMAT` +#### `ERR_CRYPTO_ECDH_INVALID_FORMAT` An invalid value for the `format` argument was passed to the `crypto.ECDH()` class `getPublicKey()` method. -#### `ERR_CRYPTO_ECDH_INVALID_PUBLIC_KEY` +#### `ERR_CRYPTO_ECDH_INVALID_PUBLIC_KEY` An invalid value for the `key` argument has been passed to the `crypto.ECDH()` class `computeSecret()` method. It means that the public @@ -855,306 +855,306 @@ key lies outside of the elliptic curve. -#### `ERR_CRYPTO_ENGINE_UNKNOWN` +#### `ERR_CRYPTO_ENGINE_UNKNOWN` An invalid crypto engine identifier was passed to [`require('node:crypto').setEngine()`][]. -#### `ERR_CRYPTO_FIPS_FORCED` +#### `ERR_CRYPTO_FIPS_FORCED` The [`--force-fips`][] command-line argument was used but there was an attempt to enable or disable FIPS mode in the `node:crypto` module. -#### `ERR_CRYPTO_FIPS_UNAVAILABLE` +#### `ERR_CRYPTO_FIPS_UNAVAILABLE` An attempt was made to enable or disable FIPS mode, but FIPS mode was not available. -#### `ERR_CRYPTO_HASH_FINALIZED` +#### `ERR_CRYPTO_HASH_FINALIZED` [`hash.digest()`][] was called multiple times. The `hash.digest()` method must be called no more than one time per instance of a `Hash` object. -#### `ERR_CRYPTO_HASH_UPDATE_FAILED` +#### `ERR_CRYPTO_HASH_UPDATE_FAILED` [`hash.update()`][] failed for any reason. This should rarely, if ever, happen. -#### `ERR_CRYPTO_INCOMPATIBLE_KEY` +#### `ERR_CRYPTO_INCOMPATIBLE_KEY` The given crypto keys are incompatible with the attempted operation. -#### `ERR_CRYPTO_INCOMPATIBLE_KEY_OPTIONS` +#### `ERR_CRYPTO_INCOMPATIBLE_KEY_OPTIONS` The selected public or private key encoding is incompatible with other options. -#### `ERR_CRYPTO_INITIALIZATION_FAILED` +#### `ERR_CRYPTO_INITIALIZATION_FAILED` - + Initialization of the crypto subsystem failed. -#### `ERR_CRYPTO_INVALID_AUTH_TAG` +#### `ERR_CRYPTO_INVALID_AUTH_TAG` - + An invalid authentication tag was provided. -#### `ERR_CRYPTO_INVALID_COUNTER` +#### `ERR_CRYPTO_INVALID_COUNTER` - + An invalid counter was provided for a counter-mode cipher. -#### `ERR_CRYPTO_INVALID_CURVE` +#### `ERR_CRYPTO_INVALID_CURVE` - + An invalid elliptic-curve was provided. -#### `ERR_CRYPTO_INVALID_DIGEST` +#### `ERR_CRYPTO_INVALID_DIGEST` An invalid [crypto digest algorithm][] was specified. -#### `ERR_CRYPTO_INVALID_IV` +#### `ERR_CRYPTO_INVALID_IV` - + An invalid initialization vector was provided. -#### `ERR_CRYPTO_INVALID_JWK` +#### `ERR_CRYPTO_INVALID_JWK` - + An invalid JSON Web Key was provided. -#### `ERR_CRYPTO_INVALID_KEY_OBJECT_TYPE` +#### `ERR_CRYPTO_INVALID_KEY_OBJECT_TYPE` The given crypto key object's type is invalid for the attempted operation. -#### `ERR_CRYPTO_INVALID_KEYLEN` +#### `ERR_CRYPTO_INVALID_KEYLEN` - + An invalid key length was provided. -#### `ERR_CRYPTO_INVALID_KEYPAIR` +#### `ERR_CRYPTO_INVALID_KEYPAIR` - + An invalid key pair was provided. -#### `ERR_CRYPTO_INVALID_KEYTYPE` +#### `ERR_CRYPTO_INVALID_KEYTYPE` - + An invalid key type was provided. -#### `ERR_CRYPTO_INVALID_MESSAGELEN` +#### `ERR_CRYPTO_INVALID_MESSAGELEN` - + An invalid message length was provided. -#### `ERR_CRYPTO_INVALID_SCRYPT_PARAMS` +#### `ERR_CRYPTO_INVALID_SCRYPT_PARAMS` - + Invalid scrypt algorithm parameters were provided. -#### `ERR_CRYPTO_INVALID_STATE` +#### `ERR_CRYPTO_INVALID_STATE` A crypto method was used on an object that was in an invalid state. For instance, calling [`cipher.getAuthTag()`][] before calling `cipher.final()`. -#### `ERR_CRYPTO_INVALID_TAG_LENGTH` +#### `ERR_CRYPTO_INVALID_TAG_LENGTH` - + An invalid authentication tag length was provided. -#### `ERR_CRYPTO_JOB_INIT_FAILED` +#### `ERR_CRYPTO_JOB_INIT_FAILED` - + Initialization of an asynchronous crypto operation failed. -#### `ERR_CRYPTO_JWK_UNSUPPORTED_CURVE` +#### `ERR_CRYPTO_JWK_UNSUPPORTED_CURVE` Key's Elliptic Curve is not registered for use in the [JSON Web Key Elliptic Curve Registry][]. -#### `ERR_CRYPTO_JWK_UNSUPPORTED_KEY_TYPE` +#### `ERR_CRYPTO_JWK_UNSUPPORTED_KEY_TYPE` Key's Asymmetric Key Type is not registered for use in the [JSON Web Key Types Registry][]. -#### `ERR_CRYPTO_OPERATION_FAILED` +#### `ERR_CRYPTO_OPERATION_FAILED` - + A crypto operation failed for an otherwise unspecified reason. -#### `ERR_CRYPTO_PBKDF2_ERROR` +#### `ERR_CRYPTO_PBKDF2_ERROR` The PBKDF2 algorithm failed for unspecified reasons. OpenSSL does not provide more details and therefore neither does Node.js. -#### `ERR_CRYPTO_SCRYPT_INVALID_PARAMETER` +#### `ERR_CRYPTO_SCRYPT_INVALID_PARAMETER` One or more [`crypto.scrypt()`][] or [`crypto.scryptSync()`][] parameters are outside their legal range. -#### `ERR_CRYPTO_SCRYPT_NOT_SUPPORTED` +#### `ERR_CRYPTO_SCRYPT_NOT_SUPPORTED` Node.js was compiled without `scrypt` support. Not possible with the official release binaries but can happen with custom builds, including distro builds. -#### `ERR_CRYPTO_SIGN_KEY_REQUIRED` +#### `ERR_CRYPTO_SIGN_KEY_REQUIRED` A signing `key` was not provided to the [`sign.sign()`][] method. -#### `ERR_CRYPTO_TIMING_SAFE_EQUAL_LENGTH` +#### `ERR_CRYPTO_TIMING_SAFE_EQUAL_LENGTH` [`crypto.timingSafeEqual()`][] was called with `Buffer`, `TypedArray`, or `DataView` arguments of different lengths. -#### `ERR_CRYPTO_UNKNOWN_CIPHER` +#### `ERR_CRYPTO_UNKNOWN_CIPHER` An unknown cipher was specified. -#### `ERR_CRYPTO_UNKNOWN_DH_GROUP` +#### `ERR_CRYPTO_UNKNOWN_DH_GROUP` An unknown Diffie-Hellman group name was given. See [`crypto.getDiffieHellman()`][] for a list of valid group names. -#### `ERR_CRYPTO_UNSUPPORTED_OPERATION` +#### `ERR_CRYPTO_UNSUPPORTED_OPERATION` - + An attempt to invoke an unsupported crypto operation was made. -#### `ERR_DEBUGGER_ERROR` +#### `ERR_DEBUGGER_ERROR` - + An error occurred with the [debugger][]. -#### `ERR_DEBUGGER_STARTUP_ERROR` +#### `ERR_DEBUGGER_STARTUP_ERROR` - + The [debugger][] timed out waiting for the required host/port to be free. -#### `ERR_DLOPEN_DISABLED` +#### `ERR_DLOPEN_DISABLED` - + Loading native addons has been disabled using [`--no-addons`][]. -#### `ERR_DLOPEN_FAILED` +#### `ERR_DLOPEN_FAILED` - + A call to `process.dlopen()` failed. -#### `ERR_DIR_CLOSED` +#### `ERR_DIR_CLOSED` The [`fs.Dir`][] was previously closed. -#### `ERR_DIR_CONCURRENT_OPERATION` +#### `ERR_DIR_CONCURRENT_OPERATION` - + A synchronous read or close call was attempted on an [`fs.Dir`][] which has ongoing asynchronous operations. -#### `ERR_DNS_SET_SERVERS_FAILED` +#### `ERR_DNS_SET_SERVERS_FAILED` `c-ares` failed to set the DNS server. -#### `ERR_DOMAIN_CALLBACK_NOT_AVAILABLE` +#### `ERR_DOMAIN_CALLBACK_NOT_AVAILABLE` The `node:domain` module was not usable since it could not establish the required error handling hooks, because @@ -1163,7 +1163,7 @@ earlier point in time. -#### `ERR_DOMAIN_CANNOT_SET_UNCAUGHT_EXCEPTION_CAPTURE` +#### `ERR_DOMAIN_CANNOT_SET_UNCAUGHT_EXCEPTION_CAPTURE` [`process.setUncaughtExceptionCaptureCallback()`][] could not be called because the `node:domain` module has been loaded at an earlier point in time. @@ -1173,40 +1173,40 @@ The stack trace is extended to include the point in time at which the -#### `ERR_DUPLICATE_STARTUP_SNAPSHOT_MAIN_FUNCTION` +#### `ERR_DUPLICATE_STARTUP_SNAPSHOT_MAIN_FUNCTION` [`v8.startupSnapshot.setDeserializeMainFunction()`][] could not be called because it had already been called before. -#### `ERR_ENCODING_INVALID_ENCODED_DATA` +#### `ERR_ENCODING_INVALID_ENCODED_DATA` Data provided to `TextDecoder()` API was invalid according to the encoding provided. -#### `ERR_ENCODING_NOT_SUPPORTED` +#### `ERR_ENCODING_NOT_SUPPORTED` Encoding provided to `TextDecoder()` API was not one of the [WHATWG Supported Encodings][]. -#### `ERR_EVAL_ESM_CANNOT_PRINT` +#### `ERR_EVAL_ESM_CANNOT_PRINT` `--print` cannot be used with ESM input. -#### `ERR_EVENT_RECURSION` +#### `ERR_EVENT_RECURSION` Thrown when an attempt is made to recursively dispatch an event on `EventTarget`. -#### `ERR_EXECUTION_ENVIRONMENT_NOT_AVAILABLE` +#### `ERR_EXECUTION_ENVIRONMENT_NOT_AVAILABLE` The JS execution context is not associated with a Node.js environment. This may occur when Node.js is used as an embedded library and some hooks @@ -1214,246 +1214,246 @@ for the JS engine are not set up properly. -#### `ERR_FALSY_VALUE_REJECTION` +#### `ERR_FALSY_VALUE_REJECTION` A `Promise` that was callbackified via `util.callbackify()` was rejected with a falsy value. -#### `ERR_FEATURE_UNAVAILABLE_ON_PLATFORM` +#### `ERR_FEATURE_UNAVAILABLE_ON_PLATFORM` - + Used when a feature that is not available to the current platform which is running Node.js is used. -#### `ERR_FS_CP_DIR_TO_NON_DIR` +#### `ERR_FS_CP_DIR_TO_NON_DIR` - + An attempt was made to copy a directory to a non-directory (file, symlink, etc.) using [`fs.cp()`][]. -#### `ERR_FS_CP_EEXIST` +#### `ERR_FS_CP_EEXIST` - + An attempt was made to copy over a file that already existed with [`fs.cp()`][], with the `force` and `errorOnExist` set to `true`. -#### `ERR_FS_CP_EINVAL` +#### `ERR_FS_CP_EINVAL` - + When using [`fs.cp()`][], `src` or `dest` pointed to an invalid path. -#### `ERR_FS_CP_FIFO_PIPE` +#### `ERR_FS_CP_FIFO_PIPE` - + An attempt was made to copy a named pipe with [`fs.cp()`][]. -#### `ERR_FS_CP_NON_DIR_TO_DIR` +#### `ERR_FS_CP_NON_DIR_TO_DIR` - + An attempt was made to copy a non-directory (file, symlink, etc.) to a directory using [`fs.cp()`][]. -#### `ERR_FS_CP_SOCKET` +#### `ERR_FS_CP_SOCKET` - + An attempt was made to copy to a socket with [`fs.cp()`][]. -#### `ERR_FS_CP_SYMLINK_TO_SUBDIRECTORY` +#### `ERR_FS_CP_SYMLINK_TO_SUBDIRECTORY` - + When using [`fs.cp()`][], a symlink in `dest` pointed to a subdirectory of `src`. -#### `ERR_FS_CP_UNKNOWN` +#### `ERR_FS_CP_UNKNOWN` - + An attempt was made to copy to an unknown file type with [`fs.cp()`][]. -#### `ERR_FS_EISDIR` +#### `ERR_FS_EISDIR` Path is a directory. -#### `ERR_FS_FILE_TOO_LARGE` +#### `ERR_FS_FILE_TOO_LARGE` An attempt has been made to read a file whose size is larger than the maximum allowed size for a `Buffer`. -#### `ERR_FS_INVALID_SYMLINK_TYPE` +#### `ERR_FS_INVALID_SYMLINK_TYPE` An invalid symlink type was passed to the [`fs.symlink()`][] or [`fs.symlinkSync()`][] methods. -#### `ERR_HTTP_HEADERS_SENT` +#### `ERR_HTTP_HEADERS_SENT` An attempt was made to add more headers after the headers had already been sent. -#### `ERR_HTTP_INVALID_HEADER_VALUE` +#### `ERR_HTTP_INVALID_HEADER_VALUE` An invalid HTTP header value was specified. -#### `ERR_HTTP_INVALID_STATUS_CODE` +#### `ERR_HTTP_INVALID_STATUS_CODE` Status code was outside the regular status code range (100-999). -#### `ERR_HTTP_REQUEST_TIMEOUT` +#### `ERR_HTTP_REQUEST_TIMEOUT` The client has not sent the entire request within the allowed time. -#### `ERR_HTTP_SOCKET_ENCODING` +#### `ERR_HTTP_SOCKET_ENCODING` Changing the socket encoding is not allowed per [RFC 7230 Section 3][]. -#### `ERR_HTTP_TRAILER_INVALID` +#### `ERR_HTTP_TRAILER_INVALID` The `Trailer` header was set even though the transfer encoding does not support that. -#### `ERR_HTTP2_ALTSVC_INVALID_ORIGIN` +#### `ERR_HTTP2_ALTSVC_INVALID_ORIGIN` HTTP/2 ALTSVC frames require a valid origin. -#### `ERR_HTTP2_ALTSVC_LENGTH` +#### `ERR_HTTP2_ALTSVC_LENGTH` HTTP/2 ALTSVC frames are limited to a maximum of 16,382 payload bytes. -#### `ERR_HTTP2_CONNECT_AUTHORITY` +#### `ERR_HTTP2_CONNECT_AUTHORITY` For HTTP/2 requests using the `CONNECT` method, the `:authority` pseudo-header is required. -#### `ERR_HTTP2_CONNECT_PATH` +#### `ERR_HTTP2_CONNECT_PATH` For HTTP/2 requests using the `CONNECT` method, the `:path` pseudo-header is forbidden. -#### `ERR_HTTP2_CONNECT_SCHEME` +#### `ERR_HTTP2_CONNECT_SCHEME` For HTTP/2 requests using the `CONNECT` method, the `:scheme` pseudo-header is forbidden. -#### `ERR_HTTP2_ERROR` +#### `ERR_HTTP2_ERROR` A non-specific HTTP/2 error has occurred. -#### `ERR_HTTP2_GOAWAY_SESSION` +#### `ERR_HTTP2_GOAWAY_SESSION` New HTTP/2 Streams may not be opened after the `Http2Session` has received a `GOAWAY` frame from the connected peer. -#### `ERR_HTTP2_HEADER_SINGLE_VALUE` +#### `ERR_HTTP2_HEADER_SINGLE_VALUE` Multiple values were provided for an HTTP/2 header field that was required to have only a single value. -#### `ERR_HTTP2_HEADERS_AFTER_RESPOND` +#### `ERR_HTTP2_HEADERS_AFTER_RESPOND` An additional headers was specified after an HTTP/2 response was initiated. -#### `ERR_HTTP2_HEADERS_SENT` +#### `ERR_HTTP2_HEADERS_SENT` An attempt was made to send multiple response headers. -#### `ERR_HTTP2_INFO_STATUS_NOT_ALLOWED` +#### `ERR_HTTP2_INFO_STATUS_NOT_ALLOWED` Informational HTTP status codes (`1xx`) may not be set as the response status code on HTTP/2 responses. -#### `ERR_HTTP2_INVALID_CONNECTION_HEADERS` +#### `ERR_HTTP2_INVALID_CONNECTION_HEADERS` HTTP/1 connection specific headers are forbidden to be used in HTTP/2 requests and responses. -#### `ERR_HTTP2_INVALID_HEADER_VALUE` +#### `ERR_HTTP2_INVALID_HEADER_VALUE` An invalid HTTP/2 header value was specified. -#### `ERR_HTTP2_INVALID_INFO_STATUS` +#### `ERR_HTTP2_INVALID_INFO_STATUS` An invalid HTTP informational status code has been specified. Informational status codes must be an integer between `100` and `199` (inclusive). -#### `ERR_HTTP2_INVALID_ORIGIN` +#### `ERR_HTTP2_INVALID_ORIGIN` HTTP/2 `ORIGIN` frames require a valid origin. -#### `ERR_HTTP2_INVALID_PACKED_SETTINGS_LENGTH` +#### `ERR_HTTP2_INVALID_PACKED_SETTINGS_LENGTH` Input `Buffer` and `Uint8Array` instances passed to the `http2.getUnpackedSettings()` API must have a length that is a multiple of @@ -1461,33 +1461,33 @@ six. -#### `ERR_HTTP2_INVALID_PSEUDOHEADER` +#### `ERR_HTTP2_INVALID_PSEUDOHEADER` Only valid HTTP/2 pseudoheaders (`:status`, `:path`, `:authority`, `:scheme`, and `:method`) may be used. -#### `ERR_HTTP2_INVALID_SESSION` +#### `ERR_HTTP2_INVALID_SESSION` An action was performed on an `Http2Session` object that had already been destroyed. -#### `ERR_HTTP2_INVALID_SETTING_VALUE` +#### `ERR_HTTP2_INVALID_SETTING_VALUE` An invalid value has been specified for an HTTP/2 setting. -#### `ERR_HTTP2_INVALID_STREAM` +#### `ERR_HTTP2_INVALID_STREAM` An operation was performed on a stream that had already been destroyed. -#### `ERR_HTTP2_MAX_PENDING_SETTINGS_ACK` +#### `ERR_HTTP2_MAX_PENDING_SETTINGS_ACK` Whenever an HTTP/2 `SETTINGS` frame is sent to a connected peer, the peer is required to send an acknowledgment that it has received and applied the new @@ -1497,80 +1497,80 @@ reached. -#### `ERR_HTTP2_NESTED_PUSH` +#### `ERR_HTTP2_NESTED_PUSH` An attempt was made to initiate a new push stream from within a push stream. Nested push streams are not permitted. -#### `ERR_HTTP2_NO_MEM` +#### `ERR_HTTP2_NO_MEM` Out of memory when using the `http2session.setLocalWindowSize(windowSize)` API. -#### `ERR_HTTP2_NO_SOCKET_MANIPULATION` +#### `ERR_HTTP2_NO_SOCKET_MANIPULATION` An attempt was made to directly manipulate (read, write, pause, resume, etc.) a socket attached to an `Http2Session`. -#### `ERR_HTTP2_ORIGIN_LENGTH` +#### `ERR_HTTP2_ORIGIN_LENGTH` HTTP/2 `ORIGIN` frames are limited to a length of 16382 bytes. -#### `ERR_HTTP2_OUT_OF_STREAMS` +#### `ERR_HTTP2_OUT_OF_STREAMS` The number of streams created on a single HTTP/2 session reached the maximum limit. -#### `ERR_HTTP2_PAYLOAD_FORBIDDEN` +#### `ERR_HTTP2_PAYLOAD_FORBIDDEN` A message payload was specified for an HTTP response code for which a payload is forbidden. -#### `ERR_HTTP2_PING_CANCEL` +#### `ERR_HTTP2_PING_CANCEL` An HTTP/2 ping was canceled. -#### `ERR_HTTP2_PING_LENGTH` +#### `ERR_HTTP2_PING_LENGTH` HTTP/2 ping payloads must be exactly 8 bytes in length. -#### `ERR_HTTP2_PSEUDOHEADER_NOT_ALLOWED` +#### `ERR_HTTP2_PSEUDOHEADER_NOT_ALLOWED` An HTTP/2 pseudo-header has been used inappropriately. Pseudo-headers are header key names that begin with the `:` prefix. -#### `ERR_HTTP2_PUSH_DISABLED` +#### `ERR_HTTP2_PUSH_DISABLED` An attempt was made to create a push stream, which had been disabled by the client. -#### `ERR_HTTP2_SEND_FILE` +#### `ERR_HTTP2_SEND_FILE` An attempt was made to use the `Http2Stream.prototype.responseWithFile()` API to send a directory. -#### `ERR_HTTP2_SEND_FILE_NOSEEK` +#### `ERR_HTTP2_SEND_FILE_NOSEEK` An attempt was made to use the `Http2Stream.prototype.responseWithFile()` API to send something other than a regular file, but `offset` or `length` options were @@ -1578,59 +1578,59 @@ provided. -#### `ERR_HTTP2_SESSION_ERROR` +#### `ERR_HTTP2_SESSION_ERROR` The `Http2Session` closed with a non-zero error code. -#### `ERR_HTTP2_SETTINGS_CANCEL` +#### `ERR_HTTP2_SETTINGS_CANCEL` The `Http2Session` settings canceled. -#### `ERR_HTTP2_SOCKET_BOUND` +#### `ERR_HTTP2_SOCKET_BOUND` An attempt was made to connect a `Http2Session` object to a `net.Socket` or `tls.TLSSocket` that had already been bound to another `Http2Session` object. -#### `ERR_HTTP2_SOCKET_UNBOUND` +#### `ERR_HTTP2_SOCKET_UNBOUND` An attempt was made to use the `socket` property of an `Http2Session` that has already been closed. -#### `ERR_HTTP2_STATUS_101` +#### `ERR_HTTP2_STATUS_101` Use of the `101` Informational status code is forbidden in HTTP/2. -#### `ERR_HTTP2_STATUS_INVALID` +#### `ERR_HTTP2_STATUS_INVALID` An invalid HTTP status code has been specified. Status codes must be an integer between `100` and `599` (inclusive). -#### `ERR_HTTP2_STREAM_CANCEL` +#### `ERR_HTTP2_STREAM_CANCEL` An `Http2Stream` was destroyed before any data was transmitted to the connected peer. -#### `ERR_HTTP2_STREAM_ERROR` +#### `ERR_HTTP2_STREAM_ERROR` A non-zero error code was been specified in an `RST_STREAM` frame. -#### `ERR_HTTP2_STREAM_SELF_DEPENDENCY` +#### `ERR_HTTP2_STREAM_SELF_DEPENDENCY` When setting the priority for an HTTP/2 stream, the stream may be marked as a dependency for a parent stream. This error code is used when an attempt is @@ -1638,22 +1638,22 @@ made to mark a stream and dependent of itself. -#### `ERR_HTTP2_TOO_MANY_INVALID_FRAMES` +#### `ERR_HTTP2_TOO_MANY_INVALID_FRAMES` - + The limit of acceptable invalid HTTP/2 protocol frames sent by the peer, as specified through the `maxSessionInvalidFrames` option, has been exceeded. -#### `ERR_HTTP2_TRAILERS_ALREADY_SENT` +#### `ERR_HTTP2_TRAILERS_ALREADY_SENT` Trailing headers have already been sent on the `Http2Stream`. -#### `ERR_HTTP2_TRAILERS_NOT_READY` +#### `ERR_HTTP2_TRAILERS_NOT_READY` The `http2stream.sendTrailers()` method cannot be called until after the `'wantTrailers'` event is emitted on an `Http2Stream` object. The @@ -1662,60 +1662,60 @@ is set for the `Http2Stream`. -#### `ERR_HTTP2_UNSUPPORTED_PROTOCOL` +#### `ERR_HTTP2_UNSUPPORTED_PROTOCOL` `http2.connect()` was passed a URL that uses any protocol other than `http:` or `https:`. -#### `ERR_ILLEGAL_CONSTRUCTOR` +#### `ERR_ILLEGAL_CONSTRUCTOR` An attempt was made to construct an object using a non-public constructor. -#### `ERR_IMPORT_ASSERTION_TYPE_FAILED` +#### `ERR_IMPORT_ASSERTION_TYPE_FAILED` - + An import assertion has failed, preventing the specified module to be imported. -#### `ERR_IMPORT_ASSERTION_TYPE_MISSING` +#### `ERR_IMPORT_ASSERTION_TYPE_MISSING` - + An import assertion is missing, preventing the specified module to be imported. -#### `ERR_IMPORT_ASSERTION_TYPE_UNSUPPORTED` +#### `ERR_IMPORT_ASSERTION_TYPE_UNSUPPORTED` - + An import assertion is not supported by this version of Node.js. -#### `ERR_INCOMPATIBLE_OPTION_PAIR` +#### `ERR_INCOMPATIBLE_OPTION_PAIR` An option pair is incompatible with each other and cannot be used at the same time. -#### `ERR_INPUT_TYPE_NOT_ALLOWED` +#### `ERR_INPUT_TYPE_NOT_ALLOWED` - + The `--input-type` flag was used to attempt to execute a file. This flag can only be used with input via `--eval`, `--print`, or `STDIN`. -#### `ERR_INSPECTOR_ALREADY_ACTIVATED` +#### `ERR_INSPECTOR_ALREADY_ACTIVATED` While using the `node:inspector` module, an attempt was made to activate the inspector when it already started to listen on a port. Use `inspector.close()` @@ -1723,117 +1723,117 @@ before activating it on a different address. -#### `ERR_INSPECTOR_ALREADY_CONNECTED` +#### `ERR_INSPECTOR_ALREADY_CONNECTED` While using the `node:inspector` module, an attempt was made to connect when the inspector was already connected. -#### `ERR_INSPECTOR_CLOSED` +#### `ERR_INSPECTOR_CLOSED` While using the `node:inspector` module, an attempt was made to use the inspector after the session had already closed. -#### `ERR_INSPECTOR_COMMAND` +#### `ERR_INSPECTOR_COMMAND` An error occurred while issuing a command via the `node:inspector` module. -#### `ERR_INSPECTOR_NOT_ACTIVE` +#### `ERR_INSPECTOR_NOT_ACTIVE` The `inspector` is not active when `inspector.waitForDebugger()` is called. -#### `ERR_INSPECTOR_NOT_AVAILABLE` +#### `ERR_INSPECTOR_NOT_AVAILABLE` The `node:inspector` module is not available for use. -#### `ERR_INSPECTOR_NOT_CONNECTED` +#### `ERR_INSPECTOR_NOT_CONNECTED` While using the `node:inspector` module, an attempt was made to use the inspector before it was connected. -#### `ERR_INSPECTOR_NOT_WORKER` +#### `ERR_INSPECTOR_NOT_WORKER` An API was called on the main thread that can only be used from the worker thread. -#### `ERR_INTERNAL_ASSERTION` +#### `ERR_INTERNAL_ASSERTION` There was a bug in Node.js or incorrect usage of Node.js internals. -To fix the error, open an issue at . +To fix the error, open an issue at (https://github.com/nodejs/node/issues)[https://github.com/nodejs/node/issues]. -#### `ERR_INVALID_ADDRESS_FAMILY` +#### `ERR_INVALID_ADDRESS_FAMILY` The provided address family is not understood by the Node.js API. -#### `ERR_INVALID_ARG_TYPE` +#### `ERR_INVALID_ARG_TYPE` An argument of the wrong type was passed to a Node.js API. -#### `ERR_INVALID_ARG_VALUE` +#### `ERR_INVALID_ARG_VALUE` An invalid or unsupported value was passed for a given argument. -#### `ERR_INVALID_ASYNC_ID` +#### `ERR_INVALID_ASYNC_ID` An invalid `asyncId` or `triggerAsyncId` was passed using `AsyncHooks`. An id less than -1 should never happen. -#### `ERR_INVALID_BUFFER_SIZE` +#### `ERR_INVALID_BUFFER_SIZE` A swap was performed on a `Buffer` but its size was not compatible with the operation. -#### `ERR_INVALID_CHAR` +#### `ERR_INVALID_CHAR` Invalid characters were detected in headers. -#### `ERR_INVALID_CURSOR_POS` +#### `ERR_INVALID_CURSOR_POS` A cursor on a given stream cannot be moved to a specified row without a specified column. -#### `ERR_INVALID_FD` +#### `ERR_INVALID_FD` A file descriptor ('fd') was not valid (e.g. it was a negative value). -#### `ERR_INVALID_FD_TYPE` +#### `ERR_INVALID_FD_TYPE` A file descriptor ('fd') type was not valid. -#### `ERR_INVALID_FILE_URL_HOST` +#### `ERR_INVALID_FILE_URL_HOST` A Node.js API that consumes `file:` URLs (such as certain functions in the [`fs`][] module) encountered a file URL with an incompatible host. This @@ -1842,7 +1842,7 @@ host is supported. -#### `ERR_INVALID_FILE_URL_PATH` +#### `ERR_INVALID_FILE_URL_PATH` A Node.js API that consumes `file:` URLs (such as certain functions in the [`fs`][] module) encountered a file URL with an incompatible path. The exact @@ -1850,7 +1850,7 @@ semantics for determining whether a path can be used is platform-dependent. -#### `ERR_INVALID_HANDLE_TYPE` +#### `ERR_INVALID_HANDLE_TYPE` An attempt was made to send an unsupported "handle" over an IPC communication channel to a child process. See [`subprocess.send()`][] and [`process.send()`][] @@ -1858,105 +1858,105 @@ for more information. -#### `ERR_INVALID_HTTP_TOKEN` +#### `ERR_INVALID_HTTP_TOKEN` An invalid HTTP token was supplied. -#### `ERR_INVALID_IP_ADDRESS` +#### `ERR_INVALID_IP_ADDRESS` An IP address is not valid. -#### `ERR_INVALID_MODULE` +#### `ERR_INVALID_MODULE` - + An attempt was made to load a module that does not exist or was otherwise not valid. -#### `ERR_INVALID_MODULE_SPECIFIER` +#### `ERR_INVALID_MODULE_SPECIFIER` The imported module string is an invalid URL, package name, or package subpath specifier. -#### `ERR_INVALID_OBJECT_DEFINE_PROPERTY` +#### `ERR_INVALID_OBJECT_DEFINE_PROPERTY` An error occurred while setting an invalid attribute on the property of an object. -#### `ERR_INVALID_PACKAGE_CONFIG` +#### `ERR_INVALID_PACKAGE_CONFIG` An invalid [`package.json`][] file failed parsing. -#### `ERR_INVALID_PACKAGE_TARGET` +#### `ERR_INVALID_PACKAGE_TARGET` The `package.json` [`"exports"`][] field contains an invalid target mapping value for the attempted module resolution. -#### `ERR_INVALID_PERFORMANCE_MARK` +#### `ERR_INVALID_PERFORMANCE_MARK` While using the Performance Timing API (`perf_hooks`), a performance mark is invalid. -#### `ERR_INVALID_PROTOCOL` +#### `ERR_INVALID_PROTOCOL` An invalid `options.protocol` was passed to `http.request()`. -#### `ERR_INVALID_REPL_EVAL_CONFIG` +#### `ERR_INVALID_REPL_EVAL_CONFIG` Both `breakEvalOnSigint` and `eval` options were set in the [`REPL`][] config, which is not supported. -#### `ERR_INVALID_REPL_INPUT` +#### `ERR_INVALID_REPL_INPUT` The input may not be used in the [`REPL`][]. The conditions under which this error is used are described in the [`REPL`][] documentation. -#### `ERR_INVALID_RETURN_PROPERTY` +#### `ERR_INVALID_RETURN_PROPERTY` Thrown in case a function option does not provide a valid value for one of its returned object properties on execution. -#### `ERR_INVALID_RETURN_PROPERTY_VALUE` +#### `ERR_INVALID_RETURN_PROPERTY_VALUE` Thrown in case a function option does not provide an expected value type for one of its returned object properties on execution. -#### `ERR_INVALID_RETURN_VALUE` +#### `ERR_INVALID_RETURN_VALUE` Thrown in case a function option does not return an expected value type on execution, such as when a function is expected to return a promise. -#### `ERR_INVALID_STATE` +#### `ERR_INVALID_STATE` - + Indicates that an operation cannot be completed due to an invalid state. For instance, an object may have already been destroyed, or may be @@ -1964,7 +1964,7 @@ performing another operation. -#### `ERR_INVALID_SYNC_FORK_INPUT` +#### `ERR_INVALID_SYNC_FORK_INPUT` A `Buffer`, `TypedArray`, `DataView`, or `string` was provided as stdio input to an asynchronous fork. See the documentation for the [`child_process`][] module @@ -1972,7 +1972,7 @@ for more information. -#### `ERR_INVALID_THIS` +#### `ERR_INVALID_THIS` A Node.js API function was called with an incompatible `this` value. @@ -1986,13 +1986,13 @@ urlSearchParams.has.call(buf, 'foo'); -#### `ERR_INVALID_TRANSFER_OBJECT` +#### `ERR_INVALID_TRANSFER_OBJECT` An invalid transfer object was passed to `postMessage()`. -#### `ERR_INVALID_TUPLE` +#### `ERR_INVALID_TUPLE` An element in the `iterable` provided to the [WHATWG][WHATWG URL API] [`URLSearchParams` constructor][`new URLSearchParams(iterable)`] did not @@ -2001,13 +2001,13 @@ does not consist of exactly two elements. -#### `ERR_INVALID_URI` +#### `ERR_INVALID_URI` An invalid URI was passed. -#### `ERR_INVALID_URL` +#### `ERR_INVALID_URL` An invalid URL was passed to the [WHATWG][WHATWG URL API] [`URL` constructor][`new URL(input)`] or the legacy [`url.parse()`][] to be parsed. @@ -2016,7 +2016,7 @@ contains the URL that failed to parse. -#### `ERR_INVALID_URL_SCHEME` +#### `ERR_INVALID_URL_SCHEME` An attempt was made to use a URL of an incompatible scheme (protocol) for a specific purpose. It is only used in the [WHATWG URL API][] support in the @@ -2025,13 +2025,13 @@ in other Node.js APIs as well in the future. -#### `ERR_IPC_CHANNEL_CLOSED` +#### `ERR_IPC_CHANNEL_CLOSED` An attempt was made to use an IPC communication channel that was already closed. -#### `ERR_IPC_DISCONNECTED` +#### `ERR_IPC_DISCONNECTED` An attempt was made to disconnect an IPC communication channel that was already disconnected. See the documentation for the [`child_process`][] module @@ -2039,7 +2039,7 @@ for more information. -#### `ERR_IPC_ONE_PIPE` +#### `ERR_IPC_ONE_PIPE` An attempt was made to create a child Node.js process using more than one IPC communication channel. See the documentation for the [`child_process`][] module @@ -2047,7 +2047,7 @@ for more information. -#### `ERR_IPC_SYNC_FORK` +#### `ERR_IPC_SYNC_FORK` An attempt was made to open an IPC communication channel with a synchronously forked Node.js process. See the documentation for the [`child_process`][] module @@ -2055,16 +2055,16 @@ for more information. -#### `ERR_LOADER_CHAIN_INCOMPLETE` +#### `ERR_LOADER_CHAIN_INCOMPLETE` - + An ESM loader hook returned without calling `next()` and without explicitly signaling a short circuit. -#### `ERR_MANIFEST_ASSERT_INTEGRITY` +#### `ERR_MANIFEST_ASSERT_INTEGRITY` An attempt was made to load a resource, but the resource did not match the integrity defined by the policy manifest. See the documentation for [policy][] @@ -2072,7 +2072,7 @@ manifests for more information. -#### `ERR_MANIFEST_DEPENDENCY_MISSING` +#### `ERR_MANIFEST_DEPENDENCY_MISSING` An attempt was made to load a resource, but the resource was not listed as a dependency from the location that attempted to load it. See the documentation @@ -2080,7 +2080,7 @@ for [policy][] manifests for more information. -#### `ERR_MANIFEST_INTEGRITY_MISMATCH` +#### `ERR_MANIFEST_INTEGRITY_MISMATCH` An attempt was made to load a policy manifest, but the manifest had multiple entries for a resource which did not match each other. Update the manifest @@ -2089,7 +2089,7 @@ entries to match in order to resolve this error. See the documentation for -#### `ERR_MANIFEST_INVALID_RESOURCE_FIELD` +#### `ERR_MANIFEST_INVALID_RESOURCE_FIELD` A policy manifest resource had an invalid value for one of its fields. Update the manifest entry to match in order to resolve this error. See the @@ -2097,7 +2097,7 @@ documentation for [policy][] manifests for more information. -#### `ERR_MANIFEST_INVALID_SPECIFIER` +#### `ERR_MANIFEST_INVALID_SPECIFIER` A policy manifest resource had an invalid value for one of its dependency mappings. Update the manifest entry to match to resolve this error. See the @@ -2105,37 +2105,37 @@ documentation for [policy][] manifests for more information. -#### `ERR_MANIFEST_PARSE_POLICY` +#### `ERR_MANIFEST_PARSE_POLICY` An attempt was made to load a policy manifest, but the manifest was unable to be parsed. See the documentation for [policy][] manifests for more information. -#### `ERR_MANIFEST_TDZ` +#### `ERR_MANIFEST_TDZ` An attempt was made to read from a policy manifest, but the manifest initialization has not yet taken place. This is likely a bug in Node.js. -#### `ERR_MANIFEST_UNKNOWN_ONERROR` +#### `ERR_MANIFEST_UNKNOWN_ONERROR` A policy manifest was loaded, but had an unknown value for its "onerror" behavior. See the documentation for [policy][] manifests for more information. -#### `ERR_MEMORY_ALLOCATION_FAILED` +#### `ERR_MEMORY_ALLOCATION_FAILED` An attempt was made to allocate memory (usually in the C++ layer) but it failed. -#### `ERR_MESSAGE_TARGET_CONTEXT_UNAVAILABLE` +#### `ERR_MESSAGE_TARGET_CONTEXT_UNAVAILABLE` - + A message posted to a [`MessagePort`][] could not be deserialized in the target [vm][] `Context`. Not all Node.js objects can be successfully instantiated in @@ -2144,13 +2144,13 @@ can fail on the receiving side in that case. -#### `ERR_METHOD_NOT_IMPLEMENTED` +#### `ERR_METHOD_NOT_IMPLEMENTED` A method is required but not implemented. -#### `ERR_MISSING_ARGS` +#### `ERR_MISSING_ARGS` A required argument of a Node.js API was not passed. This is only used for strict compliance with the API specification (which in some cases may accept @@ -2160,20 +2160,20 @@ strict compliance with the API specification (which in some cases may accept -#### `ERR_MISSING_OPTION` +#### `ERR_MISSING_OPTION` For APIs that accept options objects, some options might be mandatory. This code is thrown if a required option is missing. -#### `ERR_MISSING_PASSPHRASE` +#### `ERR_MISSING_PASSPHRASE` An attempt was made to read an encrypted key without specifying a passphrase. -#### `ERR_MISSING_PLATFORM_FOR_WORKER` +#### `ERR_MISSING_PLATFORM_FOR_WORKER` The V8 platform used by this instance of Node.js does not support creating Workers. This is caused by lack of embedder support for Workers. In particular, @@ -2181,9 +2181,9 @@ this error will not occur with standard builds of Node.js. -#### `ERR_MISSING_TRANSFERABLE_IN_TRANSFER_LIST` +#### `ERR_MISSING_TRANSFERABLE_IN_TRANSFER_LIST` - + An object that needs to be explicitly listed in the `transferList` argument is in the object passed to a [`postMessage()`][] call, but is not provided @@ -2196,14 +2196,14 @@ transferable object types has been expanded to cover more types than -#### `ERR_MODULE_NOT_FOUND` +#### `ERR_MODULE_NOT_FOUND` A module file could not be resolved by the ECMAScript modules loader while attempting an `import` operation or when loading the program entry point. -#### `ERR_MULTIPLE_CALLBACK` +#### `ERR_MULTIPLE_CALLBACK` A callback was called more than once. @@ -2213,48 +2213,48 @@ would be possible by calling a callback more than once. -#### `ERR_NAPI_CONS_FUNCTION` +#### `ERR_NAPI_CONS_FUNCTION` While using `Node-API`, a constructor passed was not a function. -#### `ERR_NAPI_INVALID_DATAVIEW_ARGS` +#### `ERR_NAPI_INVALID_DATAVIEW_ARGS` While calling `napi_create_dataview()`, a given `offset` was outside the bounds of the dataview or `offset + length` was larger than a length of given `buffer`. -#### `ERR_NAPI_INVALID_TYPEDARRAY_ALIGNMENT` +#### `ERR_NAPI_INVALID_TYPEDARRAY_ALIGNMENT` While calling `napi_create_typedarray()`, the provided `offset` was not a multiple of the element size. -#### `ERR_NAPI_INVALID_TYPEDARRAY_LENGTH` +#### `ERR_NAPI_INVALID_TYPEDARRAY_LENGTH` While calling `napi_create_typedarray()`, `(length * size_of_element) + byte_offset` was larger than the length of given `buffer`. -#### `ERR_NAPI_TSFN_CALL_JS` +#### `ERR_NAPI_TSFN_CALL_JS` An error occurred while invoking the JavaScript portion of the thread-safe function. -#### `ERR_NAPI_TSFN_GET_UNDEFINED` +#### `ERR_NAPI_TSFN_GET_UNDEFINED` An error occurred while attempting to retrieve the JavaScript `undefined` value. -#### `ERR_NAPI_TSFN_START_IDLE_LOOP` +#### `ERR_NAPI_TSFN_START_IDLE_LOOP` On the main thread, values are removed from the queue associated with the thread-safe function in an idle loop. This error indicates that an error @@ -2262,54 +2262,54 @@ has occurred when attempting to start the loop. -#### `ERR_NAPI_TSFN_STOP_IDLE_LOOP` +#### `ERR_NAPI_TSFN_STOP_IDLE_LOOP` Once no more items are left in the queue, the idle loop must be suspended. This error indicates that the idle loop has failed to stop. -#### `ERR_NOT_BUILDING_SNAPSHOT` +#### `ERR_NOT_BUILDING_SNAPSHOT` An attempt was made to use operations that can only be used when building V8 startup snapshot even though Node.js isn't building one. -#### `ERR_NO_CRYPTO` +#### `ERR_NO_CRYPTO` An attempt was made to use crypto features while Node.js was not compiled with OpenSSL crypto support. -#### `ERR_NO_ICU` +#### `ERR_NO_ICU` An attempt was made to use features that require [ICU][], but Node.js was not compiled with ICU support. -#### `ERR_NON_CONTEXT_AWARE_DISABLED` +#### `ERR_NON_CONTEXT_AWARE_DISABLED` A non-context-aware native addon was loaded in a process that disallows them. -#### `ERR_OUT_OF_RANGE` +#### `ERR_OUT_OF_RANGE` A given value is out of the accepted range. -#### `ERR_PACKAGE_IMPORT_NOT_DEFINED` +#### `ERR_PACKAGE_IMPORT_NOT_DEFINED` The `package.json` [`"imports"`][] field does not define the given internal package specifier mapping. -#### `ERR_PACKAGE_PATH_NOT_EXPORTED` +#### `ERR_PACKAGE_PATH_NOT_EXPORTED` The `package.json` [`"exports"`][] field does not export the requested subpath. Because exports are encapsulated, private internal modules that are not exported @@ -2317,9 +2317,9 @@ cannot be imported through the package resolution, unless using an absolute URL. -#### `ERR_PARSE_ARGS_INVALID_OPTION_VALUE` +#### `ERR_PARSE_ARGS_INVALID_OPTION_VALUE` - + When `strict` set to `true`, thrown by [`util.parseArgs()`][] if a [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) value is provided for an option of type [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type), or if a [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) @@ -2327,37 +2327,37 @@ value is provided for an option of type [`boolean`](https://developer.mozilla.or -#### `ERR_PARSE_ARGS_UNEXPECTED_POSITIONAL` +#### `ERR_PARSE_ARGS_UNEXPECTED_POSITIONAL` - + Thrown by [`util.parseArgs()`][], when a positional argument is provided and `allowPositionals` is set to `false`. -#### `ERR_PARSE_ARGS_UNKNOWN_OPTION` +#### `ERR_PARSE_ARGS_UNKNOWN_OPTION` - + When `strict` set to `true`, thrown by [`util.parseArgs()`][] if an argument is not configured in `options`. -#### `ERR_PERFORMANCE_INVALID_TIMESTAMP` +#### `ERR_PERFORMANCE_INVALID_TIMESTAMP` An invalid timestamp value was provided for a performance mark or measure. -#### `ERR_PERFORMANCE_MEASURE_INVALID_OPTIONS` +#### `ERR_PERFORMANCE_MEASURE_INVALID_OPTIONS` Invalid options were provided for a performance measure. -#### `ERR_PROTO_ACCESS` +#### `ERR_PROTO_ACCESS` Accessing `Object.prototype.__proto__` has been forbidden using [`--disable-proto=throw`][]. [`Object.getPrototypeOf`][] and @@ -2366,28 +2366,28 @@ object. -#### `ERR_REQUIRE_ESM` +#### `ERR_REQUIRE_ESM` - + An attempt was made to `require()` an [ES Module][]. -#### `ERR_SCRIPT_EXECUTION_INTERRUPTED` +#### `ERR_SCRIPT_EXECUTION_INTERRUPTED` Script execution was interrupted by `SIGINT` (For example, Ctrl+C was pressed.) -#### `ERR_SCRIPT_EXECUTION_TIMEOUT` +#### `ERR_SCRIPT_EXECUTION_TIMEOUT` Script execution timed out, possibly due to bugs in the script being executed. -#### `ERR_SERVER_ALREADY_LISTEN` +#### `ERR_SERVER_ALREADY_LISTEN` The [`server.listen()`][] method was called while a `net.Server` was already listening. This applies to all instances of `net.Server`, including HTTP, HTTPS, @@ -2395,7 +2395,7 @@ and HTTP/2 `Server` instances. -#### `ERR_SERVER_NOT_RUNNING` +#### `ERR_SERVER_NOT_RUNNING` The [`server.close()`][] method was called when a `net.Server` was not running. This applies to all instances of `net.Server`, including HTTP, HTTPS, @@ -2403,65 +2403,65 @@ and HTTP/2 `Server` instances. -#### `ERR_SOCKET_ALREADY_BOUND` +#### `ERR_SOCKET_ALREADY_BOUND` An attempt was made to bind a socket that has already been bound. -#### `ERR_SOCKET_BAD_BUFFER_SIZE` +#### `ERR_SOCKET_BAD_BUFFER_SIZE` An invalid (negative) size was passed for either the `recvBufferSize` or `sendBufferSize` options in [`dgram.createSocket()`][]. -#### `ERR_SOCKET_BAD_PORT` +#### `ERR_SOCKET_BAD_PORT` An API function expecting a port >= 0 and < 65536 received an invalid value. -#### `ERR_SOCKET_BAD_TYPE` +#### `ERR_SOCKET_BAD_TYPE` An API function expecting a socket type (`udp4` or `udp6`) received an invalid value. -#### `ERR_SOCKET_BUFFER_SIZE` +#### `ERR_SOCKET_BUFFER_SIZE` While using [`dgram.createSocket()`][], the size of the receive or send `Buffer` could not be determined. -#### `ERR_SOCKET_CLOSED` +#### `ERR_SOCKET_CLOSED` An attempt was made to operate on an already closed socket. -#### `ERR_SOCKET_DGRAM_IS_CONNECTED` +#### `ERR_SOCKET_DGRAM_IS_CONNECTED` A [`dgram.connect()`][] call was made on an already connected socket. -#### `ERR_SOCKET_DGRAM_NOT_CONNECTED` +#### `ERR_SOCKET_DGRAM_NOT_CONNECTED` A [`dgram.disconnect()`][] or [`dgram.remoteAddress()`][] call was made on a disconnected socket. -#### `ERR_SOCKET_DGRAM_NOT_RUNNING` +#### `ERR_SOCKET_DGRAM_NOT_RUNNING` A call was made and the UDP subsystem was not running. -#### `ERR_SRI_PARSE` +#### `ERR_SRI_PARSE` A string was provided for a Subresource Integrity check, but was unable to be parsed. Check the format of integrity attributes by looking at the @@ -2469,54 +2469,54 @@ parsed. Check the format of integrity attributes by looking at the -#### `ERR_STREAM_ALREADY_FINISHED` +#### `ERR_STREAM_ALREADY_FINISHED` A stream method was called that cannot complete because the stream was finished. -#### `ERR_STREAM_CANNOT_PIPE` +#### `ERR_STREAM_CANNOT_PIPE` An attempt was made to call [`stream.pipe()`][] on a [`Writable`][] stream. -#### `ERR_STREAM_DESTROYED` +#### `ERR_STREAM_DESTROYED` A stream method was called that cannot complete because the stream was destroyed using `stream.destroy()`. -#### `ERR_STREAM_NULL_VALUES` +#### `ERR_STREAM_NULL_VALUES` An attempt was made to call [`stream.write()`][] with a `null` chunk. -#### `ERR_STREAM_PREMATURE_CLOSE` +#### `ERR_STREAM_PREMATURE_CLOSE` An error returned by `stream.finished()` and `stream.pipeline()`, when a stream or a pipeline ends non gracefully with no explicit error. -#### `ERR_STREAM_PUSH_AFTER_EOF` +#### `ERR_STREAM_PUSH_AFTER_EOF` An attempt was made to call [`stream.push()`][] after a `null`(EOF) had been pushed to the stream. -#### `ERR_STREAM_UNSHIFT_AFTER_END_EVENT` +#### `ERR_STREAM_UNSHIFT_AFTER_END_EVENT` An attempt was made to call [`stream.unshift()`][] after the `'end'` event was emitted. -#### `ERR_STREAM_WRAP` +#### `ERR_STREAM_WRAP` Prevents an abort if a string decoder was set on the Socket or if the decoder is in `objectMode`. @@ -2530,28 +2530,28 @@ instance.setEncoding('utf8'); -#### `ERR_STREAM_WRITE_AFTER_END` +#### `ERR_STREAM_WRITE_AFTER_END` An attempt was made to call [`stream.write()`][] after `stream.end()` has been called. -#### `ERR_STRING_TOO_LONG` +#### `ERR_STRING_TOO_LONG` An attempt has been made to create a string longer than the maximum allowed length. -#### `ERR_SYNTHETIC` +#### `ERR_SYNTHETIC` An artificial error object used to capture the call stack for diagnostic reports. -#### `ERR_SYSTEM_ERROR` +#### `ERR_SYSTEM_ERROR` An unspecified or non-specific system error has occurred within the Node.js process. The error object will have an `err.info` object property with @@ -2559,7 +2559,7 @@ additional details. -#### `ERR_TEST_FAILURE` +#### `ERR_TEST_FAILURE` This error represents a failed test. Additional information about the failure is available via the `cause` property. The `failureType` property specifies @@ -2567,7 +2567,7 @@ what the test was doing when the failure occurred. -#### `ERR_TLS_CERT_ALTNAME_FORMAT` +#### `ERR_TLS_CERT_ALTNAME_FORMAT` This error is thrown by `checkServerIdentity` if a user-supplied `subjectaltname` property violates encoding rules. Certificate objects produced @@ -2576,14 +2576,14 @@ this error. -#### `ERR_TLS_CERT_ALTNAME_INVALID` +#### `ERR_TLS_CERT_ALTNAME_INVALID` While using TLS, the host name/IP of the peer did not match any of the `subjectAltNames` in its certificate. -#### `ERR_TLS_DH_PARAM_SIZE` +#### `ERR_TLS_DH_PARAM_SIZE` While using TLS, the parameter offered for the Diffie-Hellman (`DH`) key-agreement protocol is too small. By default, the key length must be greater @@ -2592,123 +2592,123 @@ recommended to use 2048 bits or larger for stronger security. -#### `ERR_TLS_HANDSHAKE_TIMEOUT` +#### `ERR_TLS_HANDSHAKE_TIMEOUT` A TLS/SSL handshake timed out. In this case, the server must also abort the connection. -#### `ERR_TLS_INVALID_CONTEXT` +#### `ERR_TLS_INVALID_CONTEXT` - + The context must be a `SecureContext`. -#### `ERR_TLS_INVALID_PROTOCOL_METHOD` +#### `ERR_TLS_INVALID_PROTOCOL_METHOD` The specified `secureProtocol` method is invalid. It is either unknown, or disabled because it is insecure. -#### `ERR_TLS_INVALID_PROTOCOL_VERSION` +#### `ERR_TLS_INVALID_PROTOCOL_VERSION` Valid TLS protocol versions are `'TLSv1'`, `'TLSv1.1'`, or `'TLSv1.2'`. -#### `ERR_TLS_INVALID_STATE` +#### `ERR_TLS_INVALID_STATE` - + The TLS socket must be connected and securely established. Ensure the 'secure' event is emitted before continuing. -#### `ERR_TLS_PROTOCOL_VERSION_CONFLICT` +#### `ERR_TLS_PROTOCOL_VERSION_CONFLICT` Attempting to set a TLS protocol `minVersion` or `maxVersion` conflicts with an attempt to set the `secureProtocol` explicitly. Use one mechanism or the other. -#### `ERR_TLS_PSK_SET_IDENTIY_HINT_FAILED` +#### `ERR_TLS_PSK_SET_IDENTIY_HINT_FAILED` Failed to set PSK identity hint. Hint may be too long. -#### `ERR_TLS_RENEGOTIATION_DISABLED` +#### `ERR_TLS_RENEGOTIATION_DISABLED` An attempt was made to renegotiate TLS on a socket instance with TLS disabled. -#### `ERR_TLS_REQUIRED_SERVER_NAME` +#### `ERR_TLS_REQUIRED_SERVER_NAME` While using TLS, the `server.addContext()` method was called without providing a host name in the first parameter. -#### `ERR_TLS_SESSION_ATTACK` +#### `ERR_TLS_SESSION_ATTACK` An excessive amount of TLS renegotiations is detected, which is a potential vector for denial-of-service attacks. -#### `ERR_TLS_SNI_FROM_SERVER` +#### `ERR_TLS_SNI_FROM_SERVER` An attempt was made to issue Server Name Indication from a TLS server-side socket, which is only valid from a client. -#### `ERR_TRACE_EVENTS_CATEGORY_REQUIRED` +#### `ERR_TRACE_EVENTS_CATEGORY_REQUIRED` The `trace_events.createTracing()` method requires at least one trace event category. -#### `ERR_TRACE_EVENTS_UNAVAILABLE` +#### `ERR_TRACE_EVENTS_UNAVAILABLE` The `node:trace_events` module could not be loaded because Node.js was compiled with the `--without-v8-platform` flag. -#### `ERR_TRANSFORM_ALREADY_TRANSFORMING` +#### `ERR_TRANSFORM_ALREADY_TRANSFORMING` A `Transform` stream finished while it was still transforming. -#### `ERR_TRANSFORM_WITH_LENGTH_0` +#### `ERR_TRANSFORM_WITH_LENGTH_0` A `Transform` stream finished with data still in the write buffer. -#### `ERR_TTY_INIT_FAILED` +#### `ERR_TTY_INIT_FAILED` The initialization of a TTY failed due to a system error. -#### `ERR_UNAVAILABLE_DURING_EXIT` +#### `ERR_UNAVAILABLE_DURING_EXIT` Function was called within a [`process.on('exit')`][] handler that shouldn't be called within [`process.on('exit')`][] handler. -#### `ERR_UNCAUGHT_EXCEPTION_CAPTURE_ALREADY_SET` +#### `ERR_UNCAUGHT_EXCEPTION_CAPTURE_ALREADY_SET` [`process.setUncaughtExceptionCaptureCallback()`][] was called twice, without first resetting the callback to `null`. @@ -2718,20 +2718,20 @@ from another module. -#### `ERR_UNESCAPED_CHARACTERS` +#### `ERR_UNESCAPED_CHARACTERS` A string that contained unescaped characters was received. -#### `ERR_UNHANDLED_ERROR` +#### `ERR_UNHANDLED_ERROR` An unhandled error occurred (for instance, when an `'error'` event is emitted by an [`EventEmitter`][] but an `'error'` handler is not registered). -#### `ERR_UNKNOWN_BUILTIN_MODULE` +#### `ERR_UNKNOWN_BUILTIN_MODULE` Used to identify a specific kind of internal Node.js error that should not typically be triggered by user code. Instances of this error point to an @@ -2739,43 +2739,43 @@ internal bug within the Node.js binary itself. -#### `ERR_UNKNOWN_CREDENTIAL` +#### `ERR_UNKNOWN_CREDENTIAL` A Unix group or user identifier that does not exist was passed. -#### `ERR_UNKNOWN_ENCODING` +#### `ERR_UNKNOWN_ENCODING` An invalid or unknown encoding option was passed to an API. -#### `ERR_UNKNOWN_FILE_EXTENSION` +#### `ERR_UNKNOWN_FILE_EXTENSION` - + An attempt was made to load a module with an unknown or unsupported file extension. -#### `ERR_UNKNOWN_MODULE_FORMAT` +#### `ERR_UNKNOWN_MODULE_FORMAT` - + An attempt was made to load a module with an unknown or unsupported format. -#### `ERR_UNKNOWN_SIGNAL` +#### `ERR_UNKNOWN_SIGNAL` An invalid or unknown process signal was passed to an API expecting a valid signal (such as [`subprocess.kill()`][]). -#### `ERR_UNSUPPORTED_DIR_IMPORT` +#### `ERR_UNSUPPORTED_DIR_IMPORT` `import` a directory URL is unsupported. Instead, [self-reference a package using its name][] and [define a custom subpath][] in @@ -2791,34 +2791,34 @@ import 'package-name'; // supported -#### `ERR_UNSUPPORTED_ESM_URL_SCHEME` +#### `ERR_UNSUPPORTED_ESM_URL_SCHEME` `import` with URL schemes other than `file` and `data` is unsupported. -#### `ERR_USE_AFTER_CLOSE` +#### `ERR_USE_AFTER_CLOSE` - + An attempt was made to use something that was already closed. -#### `ERR_VALID_PERFORMANCE_ENTRY_TYPE` +#### `ERR_VALID_PERFORMANCE_ENTRY_TYPE` While using the Performance Timing API (`perf_hooks`), no valid performance entry types are found. -#### `ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING` +#### `ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING` A dynamic import callback was not specified. -#### `ERR_VM_MODULE_ALREADY_LINKED` +#### `ERR_VM_MODULE_ALREADY_LINKED` The module attempted to be linked is not eligible for linking, because of one of the following reasons: @@ -2829,118 +2829,118 @@ the following reasons: -#### `ERR_VM_MODULE_CACHED_DATA_REJECTED` +#### `ERR_VM_MODULE_CACHED_DATA_REJECTED` The `cachedData` option passed to a module constructor is invalid. -#### `ERR_VM_MODULE_CANNOT_CREATE_CACHED_DATA` +#### `ERR_VM_MODULE_CANNOT_CREATE_CACHED_DATA` Cached data cannot be created for modules which have already been evaluated. -#### `ERR_VM_MODULE_DIFFERENT_CONTEXT` +#### `ERR_VM_MODULE_DIFFERENT_CONTEXT` The module being returned from the linker function is from a different context than the parent module. Linked modules must share the same context. -#### `ERR_VM_MODULE_LINK_FAILURE` +#### `ERR_VM_MODULE_LINK_FAILURE` The module was unable to be linked due to a failure. -#### `ERR_VM_MODULE_NOT_MODULE` +#### `ERR_VM_MODULE_NOT_MODULE` The fulfilled value of a linking promise is not a `vm.Module` object. -#### `ERR_VM_MODULE_STATUS` +#### `ERR_VM_MODULE_STATUS` The current module's status does not allow for this operation. The specific meaning of the error depends on the specific function. -#### `ERR_WASI_ALREADY_STARTED` +#### `ERR_WASI_ALREADY_STARTED` The WASI instance has already started. -#### `ERR_WASI_NOT_STARTED` +#### `ERR_WASI_NOT_STARTED` The WASI instance has not been started. -#### `ERR_WEBASSEMBLY_RESPONSE` +#### `ERR_WEBASSEMBLY_RESPONSE` - + The `Response` that has been passed to `WebAssembly.compileStreaming` or to `WebAssembly.instantiateStreaming` is not a valid WebAssembly response. -#### `ERR_WORKER_INIT_FAILED` +#### `ERR_WORKER_INIT_FAILED` The `Worker` initialization failed. -#### `ERR_WORKER_INVALID_EXEC_ARGV` +#### `ERR_WORKER_INVALID_EXEC_ARGV` The `execArgv` option passed to the `Worker` constructor contains invalid flags. -#### `ERR_WORKER_NOT_RUNNING` +#### `ERR_WORKER_NOT_RUNNING` An operation failed because the `Worker` instance is not currently running. -#### `ERR_WORKER_OUT_OF_MEMORY` +#### `ERR_WORKER_OUT_OF_MEMORY` The `Worker` instance terminated because it reached its memory limit. -#### `ERR_WORKER_PATH` +#### `ERR_WORKER_PATH` The path for the main script of a worker is neither an absolute path nor a relative path starting with `./` or `../`. -#### `ERR_WORKER_UNSERIALIZABLE_ERROR` +#### `ERR_WORKER_UNSERIALIZABLE_ERROR` All attempts at serializing an uncaught exception from a worker thread failed. -#### `ERR_WORKER_UNSUPPORTED_OPERATION` +#### `ERR_WORKER_UNSUPPORTED_OPERATION` The requested functionality is not supported in worker threads. -#### `ERR_ZLIB_INITIALIZATION_FAILED` +#### `ERR_ZLIB_INITIALIZATION_FAILED` Creation of a [`zlib`][] object failed due to incorrect configuration. -#### `HPE_HEADER_OVERFLOW` +#### `HPE_HEADER_OVERFLOW` - + Too much HTTP header data was received. In order to protect against malicious or malconfigured clients, if more than 8 KiB of HTTP header data is received then @@ -2949,7 +2949,7 @@ an `Error` with this code will be emitted. -#### `HPE_UNEXPECTED_CONTENT_LENGTH` +#### `HPE_UNEXPECTED_CONTENT_LENGTH` Server is sending both a `Content-Length` header and `Transfer-Encoding: chunked`. @@ -2961,31 +2961,31 @@ Use `Content-Length` or `Transfer-Encoding: chunked`. -#### `MODULE_NOT_FOUND` +#### `MODULE_NOT_FOUND` - + A module file could not be resolved by the CommonJS modules loader while attempting a [`require()`][] operation or when loading the program entry point. ### Legacy Node.js error codes - been removed."}}} /> + -#### `ERR_CANNOT_TRANSFER_OBJECT` +#### `ERR_CANNOT_TRANSFER_OBJECT` - + The value passed to `postMessage()` contained an object that is not supported for transferring. -#### `ERR_CRYPTO_HASH_DIGEST_NO_UTF16` +#### `ERR_CRYPTO_HASH_DIGEST_NO_UTF16` - + The UTF-16 encoding was used with [`hash.digest()`][]. While the `hash.digest()` method does allow an `encoding` argument to be passed in, @@ -2994,85 +2994,85 @@ encoding (e.g. `ucs` or `utf16le`) is not supported. -#### `ERR_HTTP2_FRAME_ERROR` +#### `ERR_HTTP2_FRAME_ERROR` - + Used when a failure occurs sending an individual frame on the HTTP/2 session. -#### `ERR_HTTP2_HEADERS_OBJECT` +#### `ERR_HTTP2_HEADERS_OBJECT` - + Used when an HTTP/2 Headers Object is expected. -#### `ERR_HTTP2_HEADER_REQUIRED` +#### `ERR_HTTP2_HEADER_REQUIRED` - + Used when a required header is missing in an HTTP/2 message. -#### `ERR_HTTP2_INFO_HEADERS_AFTER_RESPOND` +#### `ERR_HTTP2_INFO_HEADERS_AFTER_RESPOND` - + HTTP/2 informational headers must only be sent _prior_ to calling the `Http2Stream.prototype.respond()` method. -#### `ERR_HTTP2_STREAM_CLOSED` +#### `ERR_HTTP2_STREAM_CLOSED` - + Used when an action has been performed on an HTTP/2 Stream that has already been closed. -#### `ERR_HTTP_INVALID_CHAR` +#### `ERR_HTTP_INVALID_CHAR` - + Used when an invalid character is found in an HTTP response status message (reason phrase). -#### `ERR_INDEX_OUT_OF_RANGE` +#### `ERR_INDEX_OUT_OF_RANGE` - + A given index was out of the accepted range (e.g. negative offsets). -#### `ERR_INVALID_OPT_VALUE` +#### `ERR_INVALID_OPT_VALUE` - + An invalid or unexpected value was passed in an options object. -#### `ERR_INVALID_OPT_VALUE_ENCODING` +#### `ERR_INVALID_OPT_VALUE_ENCODING` - + An invalid or unknown file encoding was passed. -#### `ERR_MISSING_MESSAGE_PORT_IN_TRANSFER_LIST` +#### `ERR_MISSING_MESSAGE_PORT_IN_TRANSFER_LIST` - + This error code was replaced by [`ERR_MISSING_TRANSFERABLE_IN_TRANSFER_LIST`][] in Node.js v15.0.0, because it is no longer accurate as other types of @@ -3080,110 +3080,110 @@ transferable objects also exist now. -#### `ERR_NAPI_CONS_PROTOTYPE_OBJECT` +#### `ERR_NAPI_CONS_PROTOTYPE_OBJECT` - + Used by the `Node-API` when `Constructor.prototype` is not an object. -#### `ERR_NETWORK_IMPORT_BAD_RESPONSE` +#### `ERR_NETWORK_IMPORT_BAD_RESPONSE` - + Response was received but was invalid when importing a module over the network. -#### `ERR_NETWORK_IMPORT_DISALLOWED` +#### `ERR_NETWORK_IMPORT_DISALLOWED` - + A network module attempted to load another module that it is not allowed to load. Likely this restriction is for security reasons. -#### `ERR_NO_LONGER_SUPPORTED` +#### `ERR_NO_LONGER_SUPPORTED` A Node.js API was called in an unsupported manner, such as `Buffer.write(string, encoding, offset[, length])`. -#### `ERR_OPERATION_FAILED` +#### `ERR_OPERATION_FAILED` - + An operation failed. This is typically used to signal the general failure of an asynchronous operation. -#### `ERR_OUTOFMEMORY` +#### `ERR_OUTOFMEMORY` - + Used generically to identify that an operation caused an out of memory condition. -#### `ERR_PARSE_HISTORY_DATA` +#### `ERR_PARSE_HISTORY_DATA` - + The `node:repl` module was unable to parse data from the REPL history file. -#### `ERR_SOCKET_CANNOT_SEND` +#### `ERR_SOCKET_CANNOT_SEND` - + Data could not be sent on a socket. -#### `ERR_STDERR_CLOSE` +#### `ERR_STDERR_CLOSE` - + An attempt was made to close the `process.stderr` stream. By design, Node.js does not allow `stdout` or `stderr` streams to be closed by user code. -#### `ERR_STDOUT_CLOSE` +#### `ERR_STDOUT_CLOSE` - + An attempt was made to close the `process.stdout` stream. By design, Node.js does not allow `stdout` or `stderr` streams to be closed by user code. -#### `ERR_STREAM_READ_NOT_IMPLEMENTED` +#### `ERR_STREAM_READ_NOT_IMPLEMENTED` - + Used when an attempt is made to use a readable stream that has not implemented [`readable._read()`][]. -#### `ERR_TLS_RENEGOTIATION_FAILED` +#### `ERR_TLS_RENEGOTIATION_FAILED` - + Used when a TLS renegotiation request has failed in a non-specific way. -#### `ERR_TRANSFERRING_EXTERNALIZED_SHAREDARRAYBUFFER` +#### `ERR_TRANSFERRING_EXTERNALIZED_SHAREDARRAYBUFFER` - + A `SharedArrayBuffer` whose memory is not managed by the JavaScript engine or by Node.js was encountered during serialization. Such a `SharedArrayBuffer` @@ -3194,9 +3194,9 @@ This can only happen when native addons create `SharedArrayBuffer`s in -#### `ERR_UNKNOWN_STDIN_TYPE` +#### `ERR_UNKNOWN_STDIN_TYPE` - + An attempt was made to launch a Node.js process with an unknown `stdin` file type. This error is usually an indication of a bug within Node.js itself, @@ -3204,9 +3204,9 @@ although it is possible for user code to trigger it. -#### `ERR_UNKNOWN_STREAM_TYPE` +#### `ERR_UNKNOWN_STREAM_TYPE` - + An attempt was made to launch a Node.js process with an unknown `stdout` or `stderr` file type. This error is usually an indication of a bug within Node.js @@ -3214,55 +3214,55 @@ itself, although it is possible for user code to trigger it. -#### `ERR_V8BREAKITERATOR` +#### `ERR_V8BREAKITERATOR` The V8 `BreakIterator` API was used but the full ICU data set is not installed. -#### `ERR_VALUE_OUT_OF_RANGE` +#### `ERR_VALUE_OUT_OF_RANGE` - + Used when a given value is out of the accepted range. -#### `ERR_VM_MODULE_NOT_LINKED` +#### `ERR_VM_MODULE_NOT_LINKED` The module must be successfully linked before instantiation. -#### `ERR_VM_MODULE_LINKING_ERRORED` +#### `ERR_VM_MODULE_LINKING_ERRORED` - + The linker function returned a module for which linking has failed. -#### `ERR_WORKER_UNSUPPORTED_EXTENSION` +#### `ERR_WORKER_UNSUPPORTED_EXTENSION` - + The pathname used for the main script of a worker has an unknown file extension. -#### `ERR_ZLIB_BINDING_CLOSED` +#### `ERR_ZLIB_BINDING_CLOSED` - + Used when an attempt is made to use a `zlib` object after it has already been closed. -#### `ERR_CPU_USAGE` +#### `ERR_CPU_USAGE` - + The native call from `process.cpuUsage` could not be processed. diff --git a/content/api/v18/esm.en.md b/content/api/v18/esm.en.md index ce9f36cd21..edff2e8115 100644 --- a/content/api/v18/esm.en.md +++ b/content/api/v18/esm.en.md @@ -2,21 +2,21 @@ title: 'esm' displayTitle: 'ECMAScript modules' category: 'api' -editPage: 'https://github.com/nodejs/node/blob/v18.8.0/doc/api/esm.md' +editPage: 'https://github.com/nodejs/node/blob/v18.9.0/doc/api/esm.md' version: 'v18' --- - + - + - + - + ### Introduction - + ECMAScript modules are [the official standard format][] to package JavaScript code for reuse. Modules are defined using a variety of [`import`][] and @@ -53,7 +53,7 @@ provides interoperability between them and its original module format, ### Enabling - + Node.js has two module systems: [CommonJS][] modules and ECMAScript modules. @@ -70,12 +70,12 @@ module loader. See [Determining module system][] for more details. This section was moved to [Modules: Packages](packages.md). -### `import` Specifiers +### `import` Specifiers #### Terminology The _specifier_ of an `import` statement is the string after the `from` keyword, -e.g. `'node:path'` in `import { sep } from 'node:path'`. Specifiers are also +e.g. `'node:path'` in `import sep from 'node:path'`. Specifiers are also used in `export from` statements, and as the argument to an `import()` expression. @@ -124,7 +124,7 @@ must be [percent-encoded][], such as `#` with `%23` and `?` with `%3F`. `'https://example.com/app.js'` is not supported natively in Node.js unless using a [custom HTTPS loader][]. -##### `file:` URLs +##### `file:` URLs Modules are loaded multiple times if the `import` specifier used to resolve them has a different query or fragment. @@ -138,9 +138,9 @@ The volume root may be referenced via `/`, `//`, or `file:///`. Given the differences between [URL][] and path resolution (such as percent encoding details), it is recommended to use [url.pathToFileURL][] when importing a path. -##### `data:` imports +##### `data:` imports - + [`data:` URLs][] are supported for importing with the following MIME types: @@ -160,9 +160,9 @@ and [absolute specifiers][Terminology]. Resolving from `data:text/javascript,import "./foo";` fails to resolve because there is no concept of relative resolution for `data:` URLs. -##### `node:` imports +##### `node:` imports - + `node:` URLs are supported as an alternative means to load Node.js builtin modules. This URL scheme allows for builtin modules to be referenced by valid @@ -174,9 +174,9 @@ import fs from 'node:fs/promises'; ### Import assertions - + - + The [Import Assertions proposal][] adds an inline syntax for module import statements to pass on more information alongside the module specifier. @@ -230,19 +230,19 @@ syncBuiltinESMExports(); fs.readFileSync === readFileSync; ``` -### `import()` expressions +### `import()` expressions [Dynamic `import()`][] is supported in both CommonJS and ES modules. In CommonJS modules it can be used to load ES modules. -### `import.meta` +### `import.meta` * [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) The `import.meta` meta property is an `Object` that contains the following properties. -#### `import.meta.url` +#### `import.meta.url` * [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The absolute `file:` URL of the module. @@ -256,11 +256,11 @@ import { readFileSync } from 'node:fs'; const buffer = readFileSync(new URL('./data.proto', import.meta.url)); ``` -#### `import.meta.resolve(specifier[, parent])` +#### `import.meta.resolve(specifier[, parent])` - + - + This feature is only available with the `--experimental-import-meta-resolve` command flag enabled. @@ -293,7 +293,7 @@ allowed to be asynchronous. ### Interoperability with CommonJS -#### `import` statements +#### `import` statements An `import` statement can reference an ES module or a CommonJS module. `import` statements are permitted only in ES modules, but dynamic [`import()`][] @@ -304,7 +304,7 @@ When importing [CommonJS modules](#commonjs-namespaces), the available, provided by static analysis as a convenience for better ecosystem compatibility. -#### `require` +#### `require` The CommonJS module `require` always treats the files it references as CommonJS. @@ -449,7 +449,7 @@ separate cache. ### JSON modules - + JSON files can be referenced by `import`: @@ -457,7 +457,7 @@ JSON files can be referenced by `import`: import packageConfig from './package.json' assert { type: 'json' }; ``` -The `assert { type: 'json' }` syntax is mandatory; see [Import Assertions][]. +The `assert ```{ type: 'json' }```` syntax is mandatory; see [Import Assertions][]. The imported JSON only exposes a `default` export. There is no support for named exports. A cache entry is created in the CommonJS cache to avoid duplication. @@ -468,7 +468,7 @@ imported from the same path. ### Wasm modules - + Importing WebAssembly modules is supported under the `--experimental-wasm-modules` flag, allowing any `.wasm` files to be @@ -496,7 +496,7 @@ would provide the exports interface for the instantiation of `module.wasm`. ### Top-level `await` - + The `await` keyword may be used in the top level body of an ECMAScript module. @@ -537,7 +537,7 @@ spawn(execPath, [ ### HTTPS and HTTP imports - + Importing network based modules using `https:` and `http:` is supported under the `--experimental-network-imports` flag. This allows web browser-like imports @@ -604,13 +604,13 @@ of Node.js applications. ### Loaders - + - + > This API is currently being redesigned and will still change. - + To customize the default module resolution, loader hooks can optionally be provided via a `--experimental-loader ./loader-name.mjs` argument to Node.js. @@ -643,9 +643,9 @@ A hook that returns without calling `next()` _and_ without returning `shortCircuit: true` also triggers an exception. These errors are to help prevent unintentional breaks in the chain. -##### `resolve(specifier, context, nextResolve)` +##### `resolve(specifier, context, nextResolve)` - + > The loaders API is being redesigned. This hook may disappear or its > signature may change. Do not rely on the API described below. @@ -723,9 +723,9 @@ export async function resolve(specifier, context, nextResolve) { } ``` -##### `load(url, context, nextLoad)` +##### `load(url, context, nextLoad)` - + > The loaders API is being redesigned. This hook may disappear or its > signature may change. Do not rely on the API described below. @@ -759,9 +759,9 @@ The final value of `format` must be one of the following: | ------------ | ------------------------------ | ----------------------------------------------------- | | `'builtin'` | Load a Node.js builtin module | Not applicable | | `'commonjs'` | Load a Node.js CommonJS module | Not applicable | -| `'json'` | Load a JSON file | { [`string`][], [`ArrayBuffer`][], [`TypedArray`][] } | -| `'module'` | Load an ES module | { [`string`][], [`ArrayBuffer`][], [`TypedArray`][] } | -| `'wasm'` | Load a WebAssembly module | { [`ArrayBuffer`][], [`TypedArray`][] } | +| `'json'` | Load a JSON file | ```{ [`string`][], [`ArrayBuffer`][], [`TypedArray`][] }``` | +| `'module'` | Load an ES module | ```{ [`string`][], [`ArrayBuffer`][], [`TypedArray`][] }``` | +| `'wasm'` | Load a WebAssembly module | ```{ [`ArrayBuffer`][], [`TypedArray`][] }``` | The value of `source` is ignored for type `'builtin'` because currently it is not possible to replace the value of a Node.js builtin (core) module. The value @@ -814,9 +814,9 @@ export async function load(url, context, nextLoad) { In a more advanced scenario, this can also be used to transform an unsupported source to a supported one (see [Examples](#examples) below). -##### `globalPreload()` +##### `globalPreload()` - + > The loaders API is being redesigned. This hook may disappear or its > signature may change. Do not rely on the API described below. @@ -1074,7 +1074,7 @@ import { scream } from './scream.coffee' console.log scream 'hello, world' import { version } from 'node:process' -console.log "Brought to you by Node.js version #version" +console.log "Brought to you by Node.js version #{version}" ``` ```coffee @@ -1408,7 +1408,7 @@ _internal_, _conditions_) #### Customizing ESM specifier resolution algorithm - + > Do not rely on this flag. We plan to remove it once the > [Loaders API][] has advanced to the point that equivalent functionality can @@ -1434,7 +1434,7 @@ $ node --experimental-specifier-resolution=node index success! ``` - + [6.1.7 Array Index]: https://tc39.es/ecma262/#integer-index [CommonJS]: (/api/modules) diff --git a/content/api/v18/events.en.md b/content/api/v18/events.en.md index c9c072d9b1..d7adebc31a 100644 --- a/content/api/v18/events.en.md +++ b/content/api/v18/events.en.md @@ -2,17 +2,17 @@ title: 'events' displayTitle: 'Events' category: 'api' -editPage: 'https://github.com/nodejs/node/blob/v18.8.0/doc/api/events.md' +editPage: 'https://github.com/nodejs/node/blob/v18.9.0/doc/api/events.md' version: 'v18' --- - + - + - + - + Much of the Node.js core API is built around an idiomatic asynchronous event-driven architecture in which certain kinds of objects (called "emitters") @@ -264,9 +264,9 @@ The `'error'` events that are generated by the `captureRejections` behavior do not have a catch handler to avoid infinite error loops: the recommendation is to **not use `async` functions as `'error'` event handlers**. -### `EventEmitter` +### `EventEmitter` - + The `EventEmitter` class is defined and exposed by the `node:events` module: @@ -287,9 +287,9 @@ It supports the following option: [automatic capturing of promise rejection][capturerejections]. **Default:** `false`. -#### `'newListener'` +#### `'newListener'` - + * `eventName` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`symbol`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Symbol_type) The name of the event being listened for * `listener` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) The event handler function @@ -327,27 +327,27 @@ myEmitter.emit('event'); // A ``` -#### `'removeListener'` +#### `'removeListener'` - + * `eventName` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`symbol`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Symbol_type) The event name * `listener` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) The event handler function The `'removeListener'` event is emitted _after_ the `listener` is removed. -#### `emitter.addListener(eventName, listener)` +#### `emitter.addListener(eventName, listener)` - + * `eventName` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`symbol`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Symbol_type) * `listener` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) Alias for `emitter.on(eventName, listener)`. -#### `emitter.emit(eventName[, ...args])` +#### `emitter.emit(eventName[, ...args])` - + * `eventName` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`symbol`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Symbol_type) * `...args` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) @@ -374,7 +374,7 @@ myEmitter.on('event', function secondListener(arg1, arg2) { // Third listener myEmitter.on('event', function thirdListener(...args) { const parameters = args.join(', '); - console.log(`event with parameters $parameters in third listener`); + console.log(`event with parameters ${parameters} in third listener`); }); console.log(myEmitter.listeners('event')); @@ -407,7 +407,7 @@ myEmitter.on('event', function secondListener(arg1, arg2) { // Third listener myEmitter.on('event', function thirdListener(...args) { const parameters = args.join(', '); - console.log(`event with parameters $parameters in third listener`); + console.log(`event with parameters ${parameters} in third listener`); }); console.log(myEmitter.listeners('event')); @@ -425,9 +425,9 @@ myEmitter.emit('event', 1, 2, 3, 4, 5); // event with parameters 1, 2, 3, 4, 5 in third listener ``` -#### `emitter.eventNames()` +#### `emitter.eventNames()` - + * Returns: [`Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array) @@ -462,9 +462,9 @@ console.log(myEE.eventNames()); // Prints: [ 'foo', 'bar', Symbol(symbol) ] ``` -#### `emitter.getMaxListeners()` +#### `emitter.getMaxListeners()` - + * Returns: [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) @@ -472,18 +472,18 @@ Returns the current max listener value for the `EventEmitter` which is either set by [`emitter.setMaxListeners(n)`][] or defaults to [`events.defaultMaxListeners`][]. -#### `emitter.listenerCount(eventName)` +#### `emitter.listenerCount(eventName)` - + * `eventName` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`symbol`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Symbol_type) The name of the event being listened for * Returns: [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Returns the number of listeners listening to the event named `eventName`. -#### `emitter.listeners(eventName)` +#### `emitter.listeners(eventName)` - + * `eventName` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`symbol`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Symbol_type) * Returns: Function\[] @@ -498,9 +498,9 @@ console.log(util.inspect(server.listeners('connection'))); // Prints: [ [Function] ] ``` -#### `emitter.off(eventName, listener)` +#### `emitter.off(eventName, listener)` - + * `eventName` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`symbol`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Symbol_type) * `listener` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) @@ -508,9 +508,9 @@ console.log(util.inspect(server.listeners('connection'))); Alias for [`emitter.removeListener()`][]. -#### `emitter.on(eventName, listener)` +#### `emitter.on(eventName, listener)` - + * `eventName` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`symbol`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Symbol_type) The name of the event. * `listener` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) The callback function @@ -544,9 +544,9 @@ myEE.emit('foo'); // a ``` -#### `emitter.once(eventName, listener)` +#### `emitter.once(eventName, listener)` - + * `eventName` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`symbol`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Symbol_type) The name of the event. * `listener` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) The callback function @@ -577,9 +577,9 @@ myEE.emit('foo'); // a ``` -#### `emitter.prependListener(eventName, listener)` +#### `emitter.prependListener(eventName, listener)` - + * `eventName` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`symbol`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Symbol_type) The name of the event. * `listener` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) The callback function @@ -599,9 +599,9 @@ server.prependListener('connection', (stream) => { Returns a reference to the `EventEmitter`, so that calls can be chained. -#### `emitter.prependOnceListener(eventName, listener)` +#### `emitter.prependOnceListener(eventName, listener)` - + * `eventName` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`symbol`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Symbol_type) The name of the event. * `listener` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) The callback function @@ -619,9 +619,9 @@ server.prependOnceListener('connection', (stream) => { Returns a reference to the `EventEmitter`, so that calls can be chained. -#### `emitter.removeAllListeners([eventName])` +#### `emitter.removeAllListeners([eventName])` - + * `eventName` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`symbol`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Symbol_type) * Returns: [`EventEmitter`](/api/events#eventemitter) @@ -634,9 +634,9 @@ component or module (e.g. sockets or file streams). Returns a reference to the `EventEmitter`, so that calls can be chained. -#### `emitter.removeListener(eventName, listener)` +#### `emitter.removeListener(eventName, listener)` - + * `eventName` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`symbol`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Symbol_type) * `listener` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) @@ -723,9 +723,9 @@ ee.emit('ping'); Returns a reference to the `EventEmitter`, so that calls can be chained. -#### `emitter.setMaxListeners(n)` +#### `emitter.setMaxListeners(n)` - + * `n` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) * Returns: [`EventEmitter`](/api/events#eventemitter) @@ -738,9 +738,9 @@ modified for this specific `EventEmitter` instance. The value can be set to Returns a reference to the `EventEmitter`, so that calls can be chained. -#### `emitter.rawListeners(eventName)` +#### `emitter.rawListeners(eventName)` - + * `eventName` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`symbol`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Symbol_type) * Returns: Function\[] @@ -772,9 +772,9 @@ newListeners[0](); emitter.emit('log'); ``` -#### `emitter[Symbol.for('nodejs.rejection')](err, eventName[, ...args])` +#### `emitter[Symbol.for('nodejs.rejection')](err, eventName[, ...args])` - + * `err` Error * `eventName` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`symbol`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Symbol_type) @@ -824,9 +824,9 @@ class MyClass extends EventEmitter { } ``` -### `events.defaultMaxListeners` +### `events.defaultMaxListeners` - + By default, a maximum of `10` listeners can be registered for any single event. This limit can be changed for individual `EventEmitter` instances @@ -863,9 +863,9 @@ the event emitter instance, the event's name and the number of attached listeners, respectively. Its `name` property is set to `'MaxListenersExceededWarning'`. -### `events.errorMonitor` +### `events.errorMonitor` - + This symbol shall be used to install a listener for only monitoring `'error'` events. Listeners installed using this symbol are called before the regular @@ -875,9 +875,9 @@ Installing a listener using this symbol does not change the behavior once an `'error'` event is emitted. Therefore, the process will still crash if no regular `'error'` listener is installed. -### `events.getEventListeners(emitterOrTarget, eventName)` +### `events.getEventListeners(emitterOrTarget, eventName)` - + * `emitterOrTarget` [`EventEmitter`](/api/events#eventemitter) | [`EventTarget`](/api/events#eventtarget) * `eventName` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`symbol`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Symbol_type) @@ -925,9 +925,9 @@ const { getEventListeners, EventEmitter } = require('node:events'); } ``` -### `events.once(emitter, name[, options])` +### `events.once(emitter, name[, options])` - + * `emitter` [`EventEmitter`](/api/events#eventemitter) * `name` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) @@ -1177,27 +1177,27 @@ process.nextTick(() => { foo().then(() => console.log('done')); ``` -### `events.captureRejections` +### `events.captureRejections` - + Value: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) Change the default `captureRejections` option on all new `EventEmitter` objects. -### `events.captureRejectionSymbol` +### `events.captureRejectionSymbol` - + Value: `Symbol.for('nodejs.rejection')` See how to write a custom [rejection handler][rejection]. -### `events.listenerCount(emitter, eventName)` +### `events.listenerCount(emitter, eventName)` - + - + * `emitter` [`EventEmitter`](/api/events#eventemitter) The emitter to query * `eventName` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`symbol`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Symbol_type) The event name @@ -1225,9 +1225,9 @@ console.log(listenerCount(myEmitter, 'event')); // Prints: 2 ``` -### `events.on(emitter, eventName[, options])` +### `events.on(emitter, eventName[, options])` - + * `emitter` [`EventEmitter`](/api/events#eventemitter) * `eventName` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`symbol`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Symbol_type) The name of the event being listened for @@ -1338,9 +1338,9 @@ const ac = new AbortController(); process.nextTick(() => ac.abort()); ``` -### `events.setMaxListeners(n[, ...eventTargets])` +### `events.setMaxListeners(n[, ...eventTargets])` - + * `n` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) A non-negative number. The maximum number of listeners per `EventTarget` event. @@ -1369,18 +1369,18 @@ const emitter = new EventEmitter(); setMaxListeners(5, target, emitter); ``` -### `events.EventEmitterAsyncResource extends EventEmitter` +### `events.EventEmitterAsyncResource extends EventEmitter` - + Integrates `EventEmitter` with [`AsyncResource`](/api/async_hooks#asyncresource) for `EventEmitter`s that require manual async tracking. Specifically, all events emitted by instances of `events.EventEmitterAsyncResource` will run within its [async context][]. ```mjs -import { EventEmitterAsyncResource } from 'node:events'; +import { EventEmitterAsyncResource, EventEmitter } from 'node:events'; import { notStrictEqual, strictEqual } from 'node:assert'; -import { executionAsyncId } from 'node:async_hooks'; +import { executionAsyncId, triggerAsyncId } from 'node:async_hooks'; // Async tracking tooling will identify this as 'Q'. const ee1 = new EventEmitterAsyncResource({ name: 'Q' }); @@ -1407,9 +1407,9 @@ Promise.resolve().then(() => { ``` ```cjs -const { EventEmitterAsyncResource } = require('node:events'); +const { EventEmitterAsyncResource, EventEmitter } = require('node:events'); const { notStrictEqual, strictEqual } = require('node:assert'); -const { executionAsyncId } = require('node:async_hooks'); +const { executionAsyncId, triggerAsyncId } = require('node:async_hooks'); // Async tracking tooling will identify this as 'Q'. const ee1 = new EventEmitterAsyncResource({ name: 'Q' }); @@ -1438,7 +1438,7 @@ Promise.resolve().then(() => { The `EventEmitterAsyncResource` class has the same methods and takes the same options as `EventEmitter` and `AsyncResource` themselves. -#### `new events.EventEmitterAsyncResource(options)` +#### `new events.EventEmitterAsyncResource(options)` * `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) * `captureRejections` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) It enables @@ -1456,34 +1456,34 @@ same options as `EventEmitter` and `AsyncResource` themselves. will only take place if there is at least one active `destroy` hook. **Default:** `false`. -#### `eventemitterasyncresource.asyncId` +#### `eventemitterasyncresource.asyncId` * Type: [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The unique `asyncId` assigned to the resource. -#### `eventemitterasyncresource.asyncResource` +#### `eventemitterasyncresource.asyncResource` * Type: The underlying [`AsyncResource`](/api/async_hooks#asyncresource). The returned `AsyncResource` object has an additional `eventEmitter` property that provides a reference to this `EventEmitterAsyncResource`. -#### `eventemitterasyncresource.emitDestroy()` +#### `eventemitterasyncresource.emitDestroy()` Call all `destroy` hooks. This should only ever be called once. An error will be thrown if it is called more than once. This **must** be manually called. If the resource is left to be collected by the GC then the `destroy` hooks will never be called. -#### `eventemitterasyncresource.triggerAsyncId` +#### `eventemitterasyncresource.triggerAsyncId` * Type: [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The same `triggerAsyncId` that is passed to the `AsyncResource` constructor. -### `EventTarget` and `Event` API +### `EventTarget` and `Event` API - + The `EventTarget` and `Event` objects are a Node.js-specific implementation of the [`EventTarget` Web API][] that are exposed by some Node.js core APIs. @@ -1511,7 +1511,7 @@ There are two key differences between the Node.js `EventTarget` and the is automatically captured and handled the same way as a listener that throws synchronously (see [`EventTarget` error handling][] for details). -#### `NodeEventTarget` vs. `EventEmitter` +#### `NodeEventTarget` vs. `EventEmitter` The `NodeEventTarget` object implements a modified subset of the `EventEmitter` API that allows it to closely _emulate_ an `EventEmitter` in @@ -1583,7 +1583,7 @@ target.addEventListener('foo', handler3); target.addEventListener('foo', handler4, { once: true }); ``` -#### `EventTarget` error handling +#### `EventTarget` error handling When a registered event listener throws (or returns a Promise that rejects), by default the error is treated as an uncaught exception on @@ -1602,148 +1602,148 @@ deprecated and will change in a future release to align `EventTarget` with other Node.js APIs. Any code relying on the `process.on('error')` event should be aligned with the new behavior. -#### `Event` +#### `Event` - + The `Event` object is an adaptation of the [`Event` Web API][]. Instances are created internally by Node.js. -##### `event.bubbles` +##### `event.bubbles` - + * Type: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) Always returns `false`. This is not used in Node.js and is provided purely for completeness. -##### `event.cancelBubble()` +##### `event.cancelBubble()` - + Alias for `event.stopPropagation()`. This is not used in Node.js and is provided purely for completeness. -##### `event.cancelable` +##### `event.cancelable` - + * Type: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) True if the event was created with the `cancelable` option. -##### `event.composed` +##### `event.composed` - + * Type: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) Always returns `false`. This is not used in Node.js and is provided purely for completeness. -##### `event.composedPath()` +##### `event.composedPath()` - + Returns an array containing the current `EventTarget` as the only entry or empty if the event is not being dispatched. This is not used in Node.js and is provided purely for completeness. -##### `event.currentTarget` +##### `event.currentTarget` - + * Type: [`EventTarget`](/api/events#eventtarget) The `EventTarget` dispatching the event. Alias for `event.target`. -##### `event.defaultPrevented` +##### `event.defaultPrevented` - + * Type: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) Is `true` if `cancelable` is `true` and `event.preventDefault()` has been called. -##### `event.eventPhase` +##### `event.eventPhase` - + * Type: [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Returns `0` while an event is not being dispatched, `2` while it is being dispatched. This is not used in Node.js and is provided purely for completeness. -##### `event.isTrusted` +##### `event.isTrusted` - + * Type: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) The [`AbortSignal`](/api/globals#abortsignal) `"abort"` event is emitted with `isTrusted` set to `true`. The value is `false` in all other cases. -##### `event.preventDefault()` +##### `event.preventDefault()` - + Sets the `defaultPrevented` property to `true` if `cancelable` is `true`. -##### `event.returnValue` +##### `event.returnValue` - + * Type: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) True if the event has not been canceled. This is not used in Node.js and is provided purely for completeness. -##### `event.srcElement` +##### `event.srcElement` - + * Type: [`EventTarget`](/api/events#eventtarget) The `EventTarget` dispatching the event. Alias for `event.target`. -##### `event.stopImmediatePropagation()` +##### `event.stopImmediatePropagation()` - + Stops the invocation of event listeners after the current one completes. -##### `event.stopPropagation()` +##### `event.stopPropagation()` - + This is not used in Node.js and is provided purely for completeness. -##### `event.target` +##### `event.target` - + * Type: [`EventTarget`](/api/events#eventtarget) The `EventTarget` dispatching the event. -##### `event.timeStamp` +##### `event.timeStamp` - + * Type: [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The millisecond timestamp when the `Event` object was created. -##### `event.type` +##### `event.type` - + * Type: [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The event type identifier. -#### `EventTarget` +#### `EventTarget` - + -##### `eventTarget.addEventListener(type, listener[, options])` +##### `eventTarget.addEventListener(type, listener[, options])` - + * `type` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) * `listener` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) | [`EventListener`](/api/events#listener) @@ -1784,9 +1784,9 @@ target.removeEventListener('foo', handler); target.removeEventListener('foo', handler, { capture: true }); ``` -##### `eventTarget.dispatchEvent(event)` +##### `eventTarget.dispatchEvent(event)` - + * `event` [`Event`](/api/events#event) * Returns: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) `true` if either event's `cancelable` attribute value is @@ -1797,9 +1797,9 @@ Dispatches the `event` to the list of handlers for `event.type`. The registered event listeners is synchronously invoked in the order they were registered. -##### `eventTarget.removeEventListener(type, listener)` +##### `eventTarget.removeEventListener(type, listener)` - + * `type` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) * `listener` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) | [`EventListener`](/api/events#listener) @@ -1808,39 +1808,39 @@ were registered. Removes the `listener` from the list of handlers for event `type`. -#### `CustomEvent` +#### `CustomEvent` - + - + * Extends: [`Event`](/api/events#event) The `CustomEvent` object is an adaptation of the [`CustomEvent` Web API][]. Instances are created internally by Node.js. -##### `event.detail` +##### `event.detail` - + - + * Type: [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) Returns custom data passed when initializing. Read-only. -#### `NodeEventTarget` +#### `NodeEventTarget` - + * Extends: [`EventTarget`](/api/events#eventtarget) The `NodeEventTarget` is a Node.js-specific extension to `EventTarget` that emulates a subset of the `EventEmitter` API. -##### `nodeEventTarget.addListener(type, listener[, options])` +##### `nodeEventTarget.addListener(type, listener[, options])` - + * `type` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) @@ -1856,18 +1856,18 @@ equivalent `EventEmitter` API. The only difference between `addListener()` and `addEventListener()` is that `addListener()` will return a reference to the `EventTarget`. -##### `nodeEventTarget.eventNames()` +##### `nodeEventTarget.eventNames()` - + * Returns: string\[] Node.js-specific extension to the `EventTarget` class that returns an array of event `type` names for which event listeners are registered. -##### `nodeEventTarget.listenerCount(type)` +##### `nodeEventTarget.listenerCount(type)` - + * `type` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) @@ -1876,9 +1876,9 @@ of event `type` names for which event listeners are registered. Node.js-specific extension to the `EventTarget` class that returns the number of event listeners registered for the `type`. -##### `nodeEventTarget.off(type, listener)` +##### `nodeEventTarget.off(type, listener)` - + * `type` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) @@ -1888,9 +1888,9 @@ of event listeners registered for the `type`. Node.js-specific alias for `eventTarget.removeListener()`. -##### `nodeEventTarget.on(type, listener[, options])` +##### `nodeEventTarget.on(type, listener[, options])` - + * `type` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) @@ -1903,9 +1903,9 @@ Node.js-specific alias for `eventTarget.removeListener()`. Node.js-specific alias for `eventTarget.addListener()`. -##### `nodeEventTarget.once(type, listener[, options])` +##### `nodeEventTarget.once(type, listener[, options])` - + * `type` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) @@ -1919,9 +1919,9 @@ Node.js-specific extension to the `EventTarget` class that adds a `once` listener for the given event `type`. This is equivalent to calling `on` with the `once` option set to `true`. -##### `nodeEventTarget.removeAllListeners([type])` +##### `nodeEventTarget.removeAllListeners([type])` - + * `type` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) @@ -1931,9 +1931,9 @@ Node.js-specific extension to the `EventTarget` class. If `type` is specified, removes all registered listeners for `type`, otherwise removes all registered listeners. -##### `nodeEventTarget.removeListener(type, listener)` +##### `nodeEventTarget.removeListener(type, listener)` - + * `type` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) diff --git a/content/api/v18/fs.en.md b/content/api/v18/fs.en.md index b6c3c94e26..246b10a0d6 100644 --- a/content/api/v18/fs.en.md +++ b/content/api/v18/fs.en.md @@ -2,17 +2,17 @@ title: 'fs' displayTitle: 'File system' category: 'api' -editPage: 'https://github.com/nodejs/node/blob/v18.8.0/doc/api/fs.md' +editPage: 'https://github.com/nodejs/node/blob/v18.9.0/doc/api/fs.md' version: 'v18' --- - + - + - + - + The `node:fs` module enables interacting with the file system in a way modeled on standard POSIX functions. @@ -62,7 +62,7 @@ const { unlink } = require('node:fs/promises'); (async function(path) { try { await unlink(path); - console.log(`successfully deleted $path`); + console.log(`successfully deleted ${path}`); } catch (error) { console.error('there was an error:', error.message); } @@ -129,7 +129,7 @@ try { ### Promises API - + The `fs/promises` API provides asynchronous file system methods that return promises. @@ -139,9 +139,9 @@ system operations off the event loop thread. These operations are not synchronized or threadsafe. Care must be taken when performing multiple concurrent modifications on the same file or data corruption may occur. -#### `FileHandle` +#### `FileHandle` - + A [`FileHandle`](/api/fs#filehandle) object is an object wrapper for a numeric file descriptor. @@ -156,16 +156,16 @@ helping to prevent memory leaks. Please do not rely on this behavior because it can be unreliable and the file may not be closed. Instead, always explicitly close [`FileHandle`](/api/fs#filehandle)s. Node.js may change this behavior in the future. -##### `'close'` +##### `'close'` - + The `'close'` event is emitted when the [`FileHandle`](/api/fs#filehandle) has been closed and can no longer be used. -##### `filehandle.appendFile(data[, options])` +##### `filehandle.appendFile(data[, options])` - + * `data` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) | [`AsyncIterable`](https://tc39.github.io/ecma262/#sec-asynciterable-interface) | [`Iterable`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#The_iterable_protocol) | [`Stream`](/api/stream#stream) * `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) @@ -178,18 +178,18 @@ When operating on file handles, the mode cannot be changed from what it was set to with [`fsPromises.open()`][]. Therefore, this is equivalent to [`filehandle.writeFile()`][]. -##### `filehandle.chmod(mode)` +##### `filehandle.chmod(mode)` - + * `mode` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) the file mode bit mask. * Returns: [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) Fulfills with `undefined` upon success. Modifies the permissions on the file. See chmod(2). -##### `filehandle.chown(uid, gid)` +##### `filehandle.chown(uid, gid)` - + * `uid` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The file's new owner's user id. * `gid` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The file's new group's group id. @@ -197,9 +197,9 @@ Modifies the permissions on the file. See chmod(2). Changes the ownership of the file. A wrapper for chown(2). -##### `filehandle.close()` +##### `filehandle.close()` - + * Returns: [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) Fulfills with `undefined` upon success. @@ -217,9 +217,9 @@ try { } ``` -##### `filehandle.createReadStream([options])` +##### `filehandle.createReadStream([options])` - + * `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) * `encoding` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) **Default:** `null` @@ -282,9 +282,9 @@ const fd = await open('sample.txt'); fd.createReadStream({ start: 90, end: 99 }); ``` -##### `filehandle.createWriteStream([options])` +##### `filehandle.createWriteStream([options])` - + * `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) * `encoding` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) **Default:** `'utf8'` @@ -308,9 +308,9 @@ file descriptor leak. By default, the stream will emit a `'close'` event after it has been destroyed. Set the `emitClose` option to `false` to change this behavior. -##### `filehandle.datasync()` +##### `filehandle.datasync()` - + * Returns: [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) Fulfills with `undefined` upon success. @@ -320,15 +320,15 @@ fdatasync(2) documentation for details. Unlike `filehandle.sync` this method does not flush modified metadata. -##### `filehandle.fd` +##### `filehandle.fd` - + * [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The numeric file descriptor managed by the [`FileHandle`](/api/fs#filehandle) object. -##### `filehandle.read(buffer, offset, length, position)` +##### `filehandle.read(buffer, offset, length, position)` - + * `buffer` [`Buffer`](/api/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) A buffer that will be filled with the file data read. @@ -348,9 +348,9 @@ Reads data from the file and stores that in the given buffer. If the file is not modified concurrently, the end-of-file is reached when the number of bytes read is zero. -##### `filehandle.read([options])` +##### `filehandle.read([options])` - + * `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) * `buffer` [`Buffer`](/api/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) A buffer that will be filled with the @@ -373,9 +373,9 @@ Reads data from the file and stores that in the given buffer. If the file is not modified concurrently, the end-of-file is reached when the number of bytes read is zero. -##### `filehandle.read(buffer[, options])` +##### `filehandle.read(buffer[, options])` - + * `buffer` [`Buffer`](/api/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) A buffer that will be filled with the file data read. @@ -398,11 +398,11 @@ Reads data from the file and stores that in the given buffer. If the file is not modified concurrently, the end-of-file is reached when the number of bytes read is zero. -##### `filehandle.readableWebStream()` +##### `filehandle.readableWebStream()` - + - + * Returns: [`ReadableStream`](/api/webstreams#readablestream) @@ -443,9 +443,9 @@ While the `ReadableStream` will read the file to completion, it will not close the `FileHandle` automatically. User code must still call the `fileHandle.close()` method. -##### `filehandle.readFile(options)` +##### `filehandle.readFile(options)` - + * `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) * `encoding` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`null`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type) **Default:** `null` @@ -465,9 +465,9 @@ If one or more `filehandle.read()` calls are made on a file handle and then a position till the end of the file. It doesn't always read from the beginning of the file. -##### `filehandle.readv(buffers[, position])` +##### `filehandle.readv(buffers[, position])` - + * `buffers` Buffer\[]|TypedArray\[]|DataView\[] * `position` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) | [`null`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type) The offset from the beginning of the file where @@ -480,18 +480,18 @@ of the file. Read from a file and write to an array of [`ArrayBufferView`](https://developer.mozilla.org/en-US/docs/Web/API/ArrayBufferView)s -##### `filehandle.stat([options])` +##### `filehandle.stat([options])` - + * `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) * `bigint` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) Whether the numeric values in the returned [`fs.Stats`](/api/fs#fsstats) object should be `bigint`. **Default:** `false`. * Returns: [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) Fulfills with an [`fs.Stats`](/api/fs#fsstats) for the file. -##### `filehandle.sync()` +##### `filehandle.sync()` - + * Returns: [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) Fulfills with `undefined` upon success. @@ -499,9 +499,9 @@ Request that all data for the open file descriptor is flushed to the storage device. The specific implementation is operating system and device specific. Refer to the POSIX fsync(2) documentation for more detail. -##### `filehandle.truncate(len)` +##### `filehandle.truncate(len)` - + * `len` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) **Default:** `0` * Returns: [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) Fulfills with `undefined` upon success. @@ -530,9 +530,9 @@ extended part is filled with null bytes (`'\0'`): If `len` is negative then `0` will be used. -##### `filehandle.utimes(atime, mtime)` +##### `filehandle.utimes(atime, mtime)` - + * `atime` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Date`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date) * `mtime` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Date`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date) @@ -541,9 +541,9 @@ If `len` is negative then `0` will be used. Change the file system timestamps of the object referenced by the [`FileHandle`](/api/fs#filehandle) then resolves the promise with no arguments upon success. -##### `filehandle.write(buffer, offset[, length[, position]])` +##### `filehandle.write(buffer, offset[, length[, position]])` - + * `buffer` [`Buffer`](/api/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) * `offset` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The start position from within `buffer` where the data @@ -572,9 +572,9 @@ On Linux, positional writes do not work when the file is opened in append mode. The kernel ignores the position argument and always appends the data to the end of the file. -##### `filehandle.write(buffer[, options])` +##### `filehandle.write(buffer[, options])` - + * `buffer` [`Buffer`](/api/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) * `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) @@ -589,9 +589,9 @@ Similar to the above `filehandle.write` function, this version takes an optional `options` object. If no `options` object is specified, it will default with the above values. -##### `filehandle.write(string[, position[, encoding]])` +##### `filehandle.write(string[, position[, encoding]])` - + * `string` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) * `position` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) | [`null`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type) The offset from the beginning of the file where the @@ -617,9 +617,9 @@ On Linux, positional writes do not work when the file is opened in append mode. The kernel ignores the position argument and always appends the data to the end of the file. -##### `filehandle.writeFile(data, options)` +##### `filehandle.writeFile(data, options)` - + * `data` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) | [`AsyncIterable`](https://tc39.github.io/ecma262/#sec-asynciterable-interface) | [`Iterable`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#The_iterable_protocol) | [`Stream`](/api/stream#stream) * `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) @@ -643,9 +643,9 @@ If one or more `filehandle.write()` calls are made on a file handle and then a current position till the end of the file. It doesn't always write from the beginning of the file. -##### `filehandle.writev(buffers[, position])` +##### `filehandle.writev(buffers[, position])` - + * `buffers` Buffer\[]|TypedArray\[]|DataView\[] * `position` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) | [`null`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type) The offset from the beginning of the file where the @@ -668,9 +668,9 @@ On Linux, positional writes don't work when the file is opened in append mode. The kernel ignores the position argument and always appends the data to the end of the file. -#### `fsPromises.access(path[, mode])` +#### `fsPromises.access(path[, mode])` - + * `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api) * `mode` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) **Default:** `fs.constants.F_OK` @@ -706,9 +706,9 @@ condition, since other processes may change the file's state between the two calls. Instead, user code should open/read/write the file directly and handle the error raised if the file is not accessible. -#### `fsPromises.appendFile(path, data[, options])` +#### `fsPromises.appendFile(path, data[, options])` - + * `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api) | [`FileHandle`](/api/fs#filehandle) filename or [`FileHandle`](/api/fs#filehandle) * `data` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) @@ -729,9 +729,9 @@ for more details. The `path` may be specified as a [`FileHandle`](/api/fs#filehandle) that has been opened for appending (using `fsPromises.open()`). -#### `fsPromises.chmod(path, mode)` +#### `fsPromises.chmod(path, mode)` - + * `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api) * `mode` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) @@ -739,9 +739,9 @@ for appending (using `fsPromises.open()`). Changes the permissions of a file. -#### `fsPromises.chown(path, uid, gid)` +#### `fsPromises.chown(path, uid, gid)` - + * `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api) * `uid` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) @@ -750,9 +750,9 @@ Changes the permissions of a file. Changes the ownership of a file. -#### `fsPromises.copyFile(src, dest[, mode])` +#### `fsPromises.copyFile(src, dest[, mode])` - + * `src` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api) source filename to copy * `dest` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api) destination filename of the copy operation @@ -797,11 +797,11 @@ try { } ``` -#### `fsPromises.cp(src, dest[, options])` +#### `fsPromises.cp(src, dest[, options])` - + - + * `src` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`URL`](/api/url#the-whatwg-url-api) source path to copy. * `dest` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`URL`](/api/url#the-whatwg-url-api) destination path to copy to. @@ -829,9 +829,9 @@ including subdirectories and files. When copying a directory to another directory, globs are not supported and behavior is similar to `cp dir1/ dir2/`. -#### `fsPromises.lchmod(path, mode)` +#### `fsPromises.lchmod(path, mode)` - + * `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api) * `mode` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) @@ -841,9 +841,9 @@ Changes the permissions on a symbolic link. This method is only implemented on macOS. -#### `fsPromises.lchown(path, uid, gid)` +#### `fsPromises.lchown(path, uid, gid)` - + * `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api) * `uid` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) @@ -852,9 +852,9 @@ This method is only implemented on macOS. Changes the ownership on a symbolic link. -#### `fsPromises.lutimes(path, atime, mtime)` +#### `fsPromises.lutimes(path, atime, mtime)` - + * `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api) * `atime` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Date`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date) @@ -866,9 +866,9 @@ Changes the access and modification times of a file in the same way as symbolic link, then the link is not dereferenced: instead, the timestamps of the symbolic link itself are changed. -#### `fsPromises.link(existingPath, newPath)` +#### `fsPromises.link(existingPath, newPath)` - + * `existingPath` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api) * `newPath` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api) @@ -877,9 +877,9 @@ the symbolic link itself are changed. Creates a new link from the `existingPath` to the `newPath`. See the POSIX link(2) documentation for more detail. -#### `fsPromises.lstat(path[, options])` +#### `fsPromises.lstat(path[, options])` - + * `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api) * `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) @@ -892,9 +892,9 @@ Equivalent to [`fsPromises.stat()`][] unless `path` refers to a symbolic link, in which case the link itself is stat-ed, not the file that it refers to. Refer to the POSIX lstat(2) document for more detail. -#### `fsPromises.mkdir(path[, options])` +#### `fsPromises.mkdir(path[, options])` - + * `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api) * `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) | [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) @@ -918,7 +918,7 @@ try { const projectFolder = new URL('./test/project/', import.meta.url); const createDir = await mkdir(path, { recursive: true }); - console.log(`created $createDir`); + console.log(`created ${createDir}`); } catch (err) { console.error(err.message); } @@ -939,9 +939,9 @@ async function makeDirectory() { makeDirectory().catch(console.error); ``` -#### `fsPromises.mkdtemp(prefix[, options])` +#### `fsPromises.mkdtemp(prefix[, options])` - + * `prefix` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) * `options` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) @@ -974,9 +974,9 @@ characters directly to the `prefix` string. For instance, given a directory `prefix` must end with a trailing platform-specific path separator (`require('node:path').sep`). -#### `fsPromises.open(path, flags[, mode])` +#### `fsPromises.open(path, flags[, mode])` - + * `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api) * `flags` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) See [support of file system `flags`][]. @@ -994,9 +994,9 @@ by [Naming Files, Paths, and Namespaces][]. Under NTFS, if the filename contains a colon, Node.js will open a file system stream, as described by [this MSDN page][MSDN-Using-Streams]. -#### `fsPromises.opendir(path[, options])` +#### `fsPromises.opendir(path[, options])` - + * `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api) * `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) @@ -1032,9 +1032,9 @@ try { When using the async iterator, the [`fs.Dir`](/api/fs#fsdir) object will be automatically closed after the iterator exits. -#### `fsPromises.readdir(path[, options])` +#### `fsPromises.readdir(path[, options])` - + * `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api) * `options` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) @@ -1065,9 +1065,9 @@ try { } ``` -#### `fsPromises.readFile(path[, options])` +#### `fsPromises.readFile(path[, options])` - + * `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api) | [`FileHandle`](/api/fs#filehandle) filename or `FileHandle` * `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) @@ -1114,9 +1114,9 @@ system requests but rather the internal buffering `fs.readFile` performs. Any specified [`FileHandle`](/api/fs#filehandle) has to support reading. -#### `fsPromises.readlink(path[, options])` +#### `fsPromises.readlink(path[, options])` - + * `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api) * `options` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) @@ -1132,9 +1132,9 @@ object with an `encoding` property specifying the character encoding to use for the link path returned. If the `encoding` is set to `'buffer'`, the link path returned will be passed as a [`Buffer`](/api/buffer#buffer) object. -#### `fsPromises.realpath(path[, options])` +#### `fsPromises.realpath(path[, options])` - + * `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api) * `options` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) @@ -1155,9 +1155,9 @@ On Linux, when Node.js is linked against musl libc, the procfs file system must be mounted on `/proc` in order for this function to work. Glibc does not have this restriction. -#### `fsPromises.rename(oldPath, newPath)` +#### `fsPromises.rename(oldPath, newPath)` - + * `oldPath` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api) * `newPath` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api) @@ -1165,9 +1165,9 @@ this restriction. Renames `oldPath` to `newPath`. -#### `fsPromises.rmdir(path[, options])` +#### `fsPromises.rmdir(path[, options])` - + * `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api) * `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) @@ -1191,11 +1191,11 @@ promise being rejected with an `ENOENT` error on Windows and an `ENOTDIR` error on POSIX. To get a behavior similar to the `rm -rf` Unix command, use -[`fsPromises.rm()`][] with options `{ recursive: true, force: true }`. +[`fsPromises.rm()`][] with options ````{ recursive: true, force: true }````. -#### `fsPromises.rm(path[, options])` +#### `fsPromises.rm(path[, options])` - + * `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api) * `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) @@ -1215,9 +1215,9 @@ To get a behavior similar to the `rm -rf` Unix command, use Removes files and directories (modeled on the standard POSIX `rm` utility). -#### `fsPromises.stat(path[, options])` +#### `fsPromises.stat(path[, options])` - + * `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api) * `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) @@ -1226,9 +1226,9 @@ Removes files and directories (modeled on the standard POSIX `rm` utility). * Returns: [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) Fulfills with the [`fs.Stats`](/api/fs#fsstats) object for the given `path`. -#### `fsPromises.symlink(target, path[, type])` +#### `fsPromises.symlink(target, path[, type])` - + * `target` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api) * `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api) @@ -1242,9 +1242,9 @@ The `type` argument is only used on Windows platforms and can be one of `'dir'`, to be absolute. When using `'junction'`, the `target` argument will automatically be normalized to absolute path. -#### `fsPromises.truncate(path[, len])` +#### `fsPromises.truncate(path[, len])` - + * `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api) * `len` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) **Default:** `0` @@ -1253,9 +1253,9 @@ automatically be normalized to absolute path. Truncates (shortens or extends the length) of the content at `path` to `len` bytes. -#### `fsPromises.unlink(path)` +#### `fsPromises.unlink(path)` - + * `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api) * Returns: [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) Fulfills with `undefined` upon success. @@ -1265,9 +1265,9 @@ the file or directory to which that link refers. If the `path` refers to a file path that is not a symbolic link, the file is deleted. See the POSIX unlink(2) documentation for more detail. -#### `fsPromises.utimes(path, atime, mtime)` +#### `fsPromises.utimes(path, atime, mtime)` - + * `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api) * `atime` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Date`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date) @@ -1283,9 +1283,9 @@ The `atime` and `mtime` arguments follow these rules: * If the value can not be converted to a number, or is `NaN`, `Infinity`, or `-Infinity`, an `Error` will be thrown. -#### `fsPromises.watch(filename[, options])` +#### `fsPromises.watch(filename[, options])` - + * `filename` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api) * `options` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) @@ -1331,9 +1331,9 @@ disappears in the directory. All the [caveats][] for `fs.watch()` also apply to `fsPromises.watch()`. -#### `fsPromises.writeFile(file, data[, options])` +#### `fsPromises.writeFile(file, data[, options])` - + * `file` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api) | [`FileHandle`](/api/fs#filehandle) filename or `FileHandle` * `data` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) | [`AsyncIterable`](https://tc39.github.io/ecma262/#sec-asynciterable-interface) | [`Iterable`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#The_iterable_protocol) | [`Stream`](/api/stream#stream) @@ -1391,7 +1391,7 @@ try { Aborting an ongoing request does not abort individual operating system requests but rather the internal buffering `fs.writeFile` performs. -#### `fsPromises.constants` +#### `fsPromises.constants` * [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) @@ -1409,9 +1409,9 @@ system operations off the event loop thread. These operations are not synchronized or threadsafe. Care must be taken when performing multiple concurrent modifications on the same file or data corruption may occur. -#### `fs.access(path[, mode], callback)` +#### `fs.access(path[, mode], callback)` - + * `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api) * `mode` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) **Default:** `fs.constants.F_OK` @@ -1438,22 +1438,22 @@ const file = 'package.json'; // Check if the file exists in the current directory. access(file, constants.F_OK, (err) => { - console.log(`$file ${err ? 'does not exist' : 'exists'}`); + console.log(`${file} ${err ? 'does not exist' : 'exists'}`); }); // Check if the file is readable. access(file, constants.R_OK, (err) => { - console.log(`$file ${err ? 'is not readable' : 'is readable'}`); + console.log(`${file} ${err ? 'is not readable' : 'is readable'}`); }); // Check if the file is writable. access(file, constants.W_OK, (err) => { - console.log(`$file ${err ? 'is not writable' : 'is writable'}`); + console.log(`${file} ${err ? 'is not writable' : 'is writable'}`); }); // Check if the file is readable and writable. access(file, constants.R_OK | constants.W_OK, (err) => { - console.log(`$file ${err ? 'is not' : 'is'} readable and writable`); + console.log(`${file} ${err ? 'is not' : 'is'} readable and writable`); }); ``` @@ -1579,9 +1579,9 @@ a file or directory. The `fs.access()` function, however, does not check the ACL and therefore may report that a path is accessible even if the ACL restricts the user from reading or writing to it. -#### `fs.appendFile(path, data[, options], callback)` +#### `fs.appendFile(path, data[, options], callback)` - + * `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api) | [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) filename or file descriptor * `data` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) @@ -1643,9 +1643,9 @@ open('message.txt', 'a', (err, fd) => { }); ``` -#### `fs.chmod(path, mode, callback)` +#### `fs.chmod(path, mode, callback)` - + * `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api) * `mode` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) @@ -1716,9 +1716,9 @@ Caveats: on Windows only the write permission can be changed, and the distinction among the permissions of group, owner, or others is not implemented. -#### `fs.chown(path, uid, gid, callback)` +#### `fs.chown(path, uid, gid, callback)` - + * `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api) * `uid` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) @@ -1731,9 +1731,9 @@ possible exception are given to the completion callback. See the POSIX chown(2) documentation for more detail. -#### `fs.close(fd[, callback])` +#### `fs.close(fd[, callback])` - + * `fd` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) * `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) @@ -1747,9 +1747,9 @@ through any other `fs` operation may lead to undefined behavior. See the POSIX close(2) documentation for more detail. -#### `fs.copyFile(src, dest[, mode], callback)` +#### `fs.copyFile(src, dest[, mode], callback)` - + * `src` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api) source filename to copy * `dest` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api) destination filename of the copy operation @@ -1791,11 +1791,11 @@ copyFile('source.txt', 'destination.txt', callback); copyFile('source.txt', 'destination.txt', constants.COPYFILE_EXCL, callback); ``` -#### `fs.cp(src, dest[, options], callback)` +#### `fs.cp(src, dest[, options], callback)` - + - + * `src` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`URL`](/api/url#the-whatwg-url-api) source path to copy. * `dest` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`URL`](/api/url#the-whatwg-url-api) destination path to copy to. @@ -1823,9 +1823,9 @@ including subdirectories and files. When copying a directory to another directory, globs are not supported and behavior is similar to `cp dir1/ dir2/`. -#### `fs.createReadStream(path[, options])` +#### `fs.createReadStream(path[, options])` - + * `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api) * `options` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) @@ -1908,9 +1908,9 @@ createReadStream('sample.txt', { start: 90, end: 99 }); If `options` is a string, then it specifies the encoding. -#### `fs.createWriteStream(path[, options])` +#### `fs.createWriteStream(path[, options])` - + * `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api) * `options` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) @@ -1955,11 +1955,11 @@ should be passed to [`net.Socket`](/api/net#netsocket). If `options` is a string, then it specifies the encoding. -#### `fs.exists(path, callback)` +#### `fs.exists(path, callback)` - + - + * `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api) * `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) @@ -2093,9 +2093,9 @@ In general, check for the existence of a file only if the file won't be used directly, for example when its existence is a signal from another process. -#### `fs.fchmod(fd, mode, callback)` +#### `fs.fchmod(fd, mode, callback)` - + * `fd` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) * `mode` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) @@ -2107,9 +2107,9 @@ are given to the completion callback. See the POSIX fchmod(2) documentation for more detail. -#### `fs.fchown(fd, uid, gid, callback)` +#### `fs.fchown(fd, uid, gid, callback)` - + * `fd` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) * `uid` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) @@ -2122,9 +2122,9 @@ given to the completion callback. See the POSIX fchown(2) documentation for more detail. -#### `fs.fdatasync(fd, callback)` +#### `fs.fdatasync(fd, callback)` - + * `fd` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) * `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) @@ -2135,9 +2135,9 @@ operating system's synchronized I/O completion state. Refer to the POSIX fdatasync(2) documentation for details. No arguments other than a possible exception are given to the completion callback. -#### `fs.fstat(fd[, options], callback)` +#### `fs.fstat(fd[, options], callback)` - + * `fd` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) * `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) @@ -2151,9 +2151,9 @@ Invokes the callback with the [`fs.Stats`](/api/fs#fsstats) for the file descrip See the POSIX fstat(2) documentation for more detail. -#### `fs.fsync(fd, callback)` +#### `fs.fsync(fd, callback)` - + * `fd` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) * `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) @@ -2164,9 +2164,9 @@ device. The specific implementation is operating system and device specific. Refer to the POSIX fsync(2) documentation for more detail. No arguments other than a possible exception are given to the completion callback. -#### `fs.ftruncate(fd[, len], callback)` +#### `fs.ftruncate(fd[, len], callback)` - + * `fd` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) * `len` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) **Default:** `0` @@ -2213,9 +2213,9 @@ extended part is filled with null bytes (`'\0'`): If `len` is negative then `0` will be used. -#### `fs.futimes(fd, atime, mtime, callback)` +#### `fs.futimes(fd, atime, mtime, callback)` - + * `fd` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) * `atime` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Date`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date) @@ -2226,9 +2226,9 @@ If `len` is negative then `0` will be used. Change the file system timestamps of the object referenced by the supplied file descriptor. See [`fs.utimes()`][]. -#### `fs.lchmod(path, mode, callback)` +#### `fs.lchmod(path, mode, callback)` - + * `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api) * `mode` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) @@ -2242,9 +2242,9 @@ This method is only implemented on macOS. See the POSIX lchmod(2) documentation for more detail. -#### `fs.lchown(path, uid, gid, callback)` +#### `fs.lchown(path, uid, gid, callback)` - + * `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api) * `uid` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) @@ -2257,9 +2257,9 @@ exception are given to the completion callback. See the POSIX lchown(2) documentation for more detail. -#### `fs.lutimes(path, atime, mtime, callback)` +#### `fs.lutimes(path, atime, mtime, callback)` - + * `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api) * `atime` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Date`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date) @@ -2275,9 +2275,9 @@ symbolic link itself are changed. No arguments other than a possible exception are given to the completion callback. -#### `fs.link(existingPath, newPath, callback)` +#### `fs.link(existingPath, newPath, callback)` - + * `existingPath` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api) * `newPath` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api) @@ -2288,9 +2288,9 @@ Creates a new link from the `existingPath` to the `newPath`. See the POSIX link(2) documentation for more detail. No arguments other than a possible exception are given to the completion callback. -#### `fs.lstat(path[, options], callback)` +#### `fs.lstat(path[, options], callback)` - + * `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api) * `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) @@ -2307,9 +2307,9 @@ link, then the link itself is stat-ed, not the file that it refers to. See the POSIX lstat(2) documentation for more details. -#### `fs.mkdir(path[, options], callback)` +#### `fs.mkdir(path[, options], callback)` - + * `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api) * `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) | [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) @@ -2355,9 +2355,9 @@ mkdir('/', { recursive: true }, (err) => { See the POSIX mkdir(2) documentation for more details. -#### `fs.mkdtemp(prefix[, options], callback)` +#### `fs.mkdtemp(prefix[, options], callback)` - + * `prefix` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) * `options` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) @@ -2414,7 +2414,7 @@ mkdtemp(tmpDir, (err, directory) => { // This method is *CORRECT*: import { sep } from 'node:path'; -mkdtemp(`$tmpDir$sep`, (err, directory) => { +mkdtemp(`${tmpDir}${sep}`, (err, directory) => { if (err) throw err; console.log(directory); // Will print something similar to `/tmp/abc123`. @@ -2423,9 +2423,9 @@ mkdtemp(`$tmpDir$sep`, (err, directory) => { }); ``` -#### `fs.open(path[, flags[, mode]], callback)` +#### `fs.open(path[, flags[, mode]], callback)` - + * `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api) * `flags` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) See [support of file system `flags`][]. @@ -2451,9 +2451,9 @@ a colon, Node.js will open a file system stream, as described by Functions based on `fs.open()` exhibit this behavior as well: `fs.writeFile()`, `fs.readFile()`, etc. -#### `fs.opendir(path[, options], callback)` +#### `fs.opendir(path[, options], callback)` - + * `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api) * `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) @@ -2474,9 +2474,9 @@ and cleaning up the directory. The `encoding` option sets the encoding for the `path` while opening the directory and subsequent read operations. -#### `fs.read(fd, buffer, offset, length, position, callback)` +#### `fs.read(fd, buffer, offset, length, position, callback)` - + * `fd` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) * `buffer` [`Buffer`](/api/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) The buffer that the data will be @@ -2502,9 +2502,9 @@ number of bytes read is zero. If this method is invoked as its [`util.promisify()`][]ed version, it returns a promise for an `Object` with `bytesRead` and `buffer` properties. -#### `fs.read(fd[, options], callback)` +#### `fs.read(fd[, options], callback)` - + * `fd` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) * `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) @@ -2521,9 +2521,9 @@ Similar to the [`fs.read()`][] function, this version takes an optional `options` object. If no `options` object is specified, it will default with the above values. -#### `fs.read(fd, buffer[, options], callback)` +#### `fs.read(fd, buffer[, options], callback)` - + * `fd` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) * `buffer` [`Buffer`](/api/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) The buffer that the data will be @@ -2541,9 +2541,9 @@ Similar to the [`fs.read()`][] function, this version takes an optional `options` object. If no `options` object is specified, it will default with the above values. -#### `fs.readdir(path[, options], callback)` +#### `fs.readdir(path[, options], callback)` - + * `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api) * `options` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) @@ -2567,9 +2567,9 @@ the filenames returned will be passed as [`Buffer`](/api/buffer#buffer) objects. If `options.withFileTypes` is set to `true`, the `files` array will contain [`fs.Dirent`](/api/fs#fsdirent) objects. -#### `fs.readFile(path[, options], callback)` +#### `fs.readFile(path[, options], callback)` - + * `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api) | [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) filename or file descriptor * `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) @@ -2676,9 +2676,9 @@ The Node.js GitHub issue [#25741][] provides more information and a detailed analysis on the performance of `fs.readFile()` for multiple file sizes in different Node.js versions. -#### `fs.readlink(path[, options], callback)` +#### `fs.readlink(path[, options], callback)` - + * `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api) * `options` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) @@ -2697,9 +2697,9 @@ object with an `encoding` property specifying the character encoding to use for the link path passed to the callback. If the `encoding` is set to `'buffer'`, the link path returned will be passed as a [`Buffer`](/api/buffer#buffer) object. -#### `fs.readv(fd, buffers[, position], callback)` +#### `fs.readv(fd, buffers[, position], callback)` - + * `fd` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) * `buffers` ArrayBufferView\[] @@ -2722,9 +2722,9 @@ The callback will be given three arguments: `err`, `bytesRead`, and If this method is invoked as its [`util.promisify()`][]ed version, it returns a promise for an `Object` with `bytesRead` and `buffers` properties. -#### `fs.realpath(path[, options], callback)` +#### `fs.realpath(path[, options], callback)` - + * `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api) * `options` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) @@ -2759,9 +2759,9 @@ the path returned will be passed as a [`Buffer`](/api/buffer#buffer) object. If `path` resolves to a socket or a pipe, the function will return a system dependent name for that object. -#### `fs.realpath.native(path[, options], callback)` +#### `fs.realpath.native(path[, options], callback)` - + * `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api) * `options` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) @@ -2785,9 +2785,9 @@ On Linux, when Node.js is linked against musl libc, the procfs file system must be mounted on `/proc` in order for this function to work. Glibc does not have this restriction. -#### `fs.rename(oldPath, newPath, callback)` +#### `fs.rename(oldPath, newPath, callback)` - + * `oldPath` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api) * `newPath` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api) @@ -2811,9 +2811,9 @@ rename('oldFile.txt', 'newFile.txt', (err) => { }); ``` -#### `fs.rmdir(path[, options], callback)` +#### `fs.rmdir(path[, options], callback)` - + * `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api) * `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) @@ -2838,11 +2838,11 @@ Using `fs.rmdir()` on a file (not a directory) results in an `ENOENT` error on Windows and an `ENOTDIR` error on POSIX. To get a behavior similar to the `rm -rf` Unix command, use [`fs.rm()`][] -with options `{ recursive: true, force: true }`. +with options ````{ recursive: true, force: true }````. -#### `fs.rm(path[, options], callback)` +#### `fs.rm(path[, options], callback)` - + * `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api) * `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) @@ -2865,9 +2865,9 @@ Asynchronously removes files and directories (modeled on the standard POSIX `rm` utility). No arguments other than a possible exception are given to the completion callback. -#### `fs.stat(path[, options], callback)` +#### `fs.stat(path[, options], callback)` - + * `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api) * `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) @@ -2960,9 +2960,9 @@ Stats { } ``` -#### `fs.symlink(target, path[, type], callback)` +#### `fs.symlink(target, path[, type], callback)` - + * `target` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api) * `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api) @@ -3000,9 +3000,9 @@ $ tree . └── mewtwo -> ./mew ``` -#### `fs.truncate(path[, len], callback)` +#### `fs.truncate(path[, len], callback)` - + * `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api) * `len` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) **Default:** `0` @@ -3036,9 +3036,9 @@ in the future. See the POSIX truncate(2) documentation for more details. -#### `fs.unlink(path, callback)` +#### `fs.unlink(path, callback)` - + * `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api) * `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) @@ -3061,9 +3061,9 @@ directory, use [`fs.rmdir()`][]. See the POSIX unlink(2) documentation for more details. -#### `fs.unwatchFile(filename[, listener])` +#### `fs.unwatchFile(filename[, listener])` - + * `filename` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api) * `listener` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) Optional, a listener previously attached using @@ -3080,9 +3080,9 @@ Using [`fs.watch()`][] is more efficient than `fs.watchFile()` and `fs.unwatchFile()`. `fs.watch()` should be used instead of `fs.watchFile()` and `fs.unwatchFile()` when possible. -#### `fs.utimes(path, atime, mtime, callback)` +#### `fs.utimes(path, atime, mtime, callback)` - + * `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api) * `atime` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Date`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date) @@ -3099,9 +3099,9 @@ The `atime` and `mtime` arguments follow these rules: * If the value can not be converted to a number, or is `NaN`, `Infinity`, or `-Infinity`, an `Error` will be thrown. -#### `fs.watch(filename[, options][, listener])` +#### `fs.watch(filename[, options][, listener])` - + * `filename` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api) * `options` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) @@ -3141,7 +3141,7 @@ the returned [`fs.FSWatcher`](/api/fs#fsfswatcher). ##### Caveats - + The `fs.watch` API is not 100% consistent across platforms, and is unavailable in some situations. @@ -3155,7 +3155,7 @@ renamed. An `EPERM` error is reported when the watched directory is deleted. ###### Availability - + This feature depends on the underlying operating system providing a way to be notified of filesystem changes. @@ -3180,7 +3180,7 @@ this method is slower and less reliable. ###### Inodes - + On Linux and macOS systems, `fs.watch()` resolves the path to an [inode][] and watches the inode. If the watched path is deleted and recreated, it is assigned @@ -3194,7 +3194,7 @@ content, and one for truncation). ###### Filename argument - + Providing `filename` argument in the callback is only supported on Linux, macOS, Windows, and AIX. Even on supported platforms, `filename` is not always @@ -3204,18 +3204,18 @@ always provided in the callback, and have some fallback logic if it is `null`. ```mjs import { watch } from 'node:fs'; watch('somedir', (eventType, filename) => { - console.log(`event type is: $eventType`); + console.log(`event type is: ${eventType}`); if (filename) { - console.log(`filename provided: $filename`); + console.log(`filename provided: ${filename}`); } else { console.log('filename not provided'); } }); ``` -#### `fs.watchFile(filename[, options], listener)` +#### `fs.watchFile(filename[, options], listener)` - + * `filename` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api) * `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) @@ -3243,8 +3243,8 @@ stat object: import { watchFile } from 'node:fs'; watchFile('message.text', (curr, prev) => { - console.log(`the current mtime is: $curr.mtime`); - console.log(`the previous mtime was: $prev.mtime`); + console.log(`the current mtime is: ${curr.mtime}`); + console.log(`the previous mtime was: ${prev.mtime}`); }); ``` @@ -3274,9 +3274,9 @@ This happens when: * the file is deleted, followed by a restore * the file is renamed and then renamed a second time back to its original name -#### `fs.write(fd, buffer, offset[, length[, position]], callback)` +#### `fs.write(fd, buffer, offset[, length[, position]], callback)` - + * `fd` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) * `buffer` [`Buffer`](/api/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) @@ -3311,9 +3311,9 @@ On Linux, positional writes don't work when the file is opened in append mode. The kernel ignores the position argument and always appends the data to the end of the file. -#### `fs.write(fd, buffer[, options], callback)` +#### `fs.write(fd, buffer[, options], callback)` - + * `fd` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) * `buffer` [`Buffer`](/api/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) @@ -3332,9 +3332,9 @@ Similar to the above `fs.write` function, this version takes an optional `options` object. If no `options` object is specified, it will default with the above values. -#### `fs.write(fd, string[, position[, encoding]], callback)` +#### `fs.write(fd, string[, position[, encoding]], callback)` - + * `fd` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) * `string` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) @@ -3374,9 +3374,9 @@ It is possible to configure the console to render UTF-8 properly by changing the active codepage with the `chcp 65001` command. See the [chcp][] docs for more details. -#### `fs.writeFile(file, data[, options], callback)` +#### `fs.writeFile(file, data[, options], callback)` - + * `file` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api) | [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) filename or file descriptor * `data` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) | [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) @@ -3477,9 +3477,9 @@ on the size of the original file, and the position of the file descriptor). If a file name had been used instead of a descriptor, the file would be guaranteed to contain only `', World'`. -#### `fs.writev(fd, buffers[, position], callback)` +#### `fs.writev(fd, buffers[, position], callback)` - + * `fd` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) * `buffers` ArrayBufferView\[] @@ -3514,9 +3514,9 @@ the end of the file. The synchronous APIs perform all operations synchronously, blocking the event loop until the operation completes or fails. -#### `fs.accessSync(path[, mode])` +#### `fs.accessSync(path[, mode])` - + * `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api) * `mode` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) **Default:** `fs.constants.F_OK` @@ -3543,9 +3543,9 @@ try { } ``` -#### `fs.appendFileSync(path, data[, options])` +#### `fs.appendFileSync(path, data[, options])` - + * `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api) | [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) filename or file descriptor * `data` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) @@ -3599,9 +3599,9 @@ try { } ``` -#### `fs.chmodSync(path, mode)` +#### `fs.chmodSync(path, mode)` - + * `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api) * `mode` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) @@ -3611,9 +3611,9 @@ this API: [`fs.chmod()`][]. See the POSIX chmod(2) documentation for more detail. -#### `fs.chownSync(path, uid, gid)` +#### `fs.chownSync(path, uid, gid)` - + * `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api) * `uid` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) @@ -3624,9 +3624,9 @@ This is the synchronous version of [`fs.chown()`][]. See the POSIX chown(2) documentation for more detail. -#### `fs.closeSync(fd)` +#### `fs.closeSync(fd)` - + * `fd` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) @@ -3637,9 +3637,9 @@ through any other `fs` operation may lead to undefined behavior. See the POSIX close(2) documentation for more detail. -#### `fs.copyFileSync(src, dest[, mode])` +#### `fs.copyFileSync(src, dest[, mode])` - + * `src` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api) source filename to copy * `dest` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api) destination filename of the copy operation @@ -3675,11 +3675,11 @@ console.log('source.txt was copied to destination.txt'); copyFileSync('source.txt', 'destination.txt', constants.COPYFILE_EXCL); ``` -#### `fs.cpSync(src, dest[, options])` +#### `fs.cpSync(src, dest[, options])` - + - + * `src` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`URL`](/api/url#the-whatwg-url-api) source path to copy. * `dest` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`URL`](/api/url#the-whatwg-url-api) destination path to copy to. @@ -3705,9 +3705,9 @@ including subdirectories and files. When copying a directory to another directory, globs are not supported and behavior is similar to `cp dir1/ dir2/`. -#### `fs.existsSync(path)` +#### `fs.existsSync(path)` - + * `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api) * Returns: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) @@ -3728,9 +3728,9 @@ if (existsSync('/etc/passwd')) console.log('The path exists.'); ``` -#### `fs.fchmodSync(fd, mode)` +#### `fs.fchmodSync(fd, mode)` - + * `fd` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) * `mode` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) @@ -3739,9 +3739,9 @@ Sets the permissions on the file. Returns `undefined`. See the POSIX fchmod(2) documentation for more detail. -#### `fs.fchownSync(fd, uid, gid)` +#### `fs.fchownSync(fd, uid, gid)` - + * `fd` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) * `uid` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The file's new owner's user id. @@ -3751,9 +3751,9 @@ Sets the owner of the file. Returns `undefined`. See the POSIX fchown(2) documentation for more detail. -#### `fs.fdatasyncSync(fd)` +#### `fs.fdatasyncSync(fd)` - + * `fd` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) @@ -3761,9 +3761,9 @@ Forces all currently queued I/O operations associated with the file to the operating system's synchronized I/O completion state. Refer to the POSIX fdatasync(2) documentation for details. Returns `undefined`. -#### `fs.fstatSync(fd[, options])` +#### `fs.fstatSync(fd[, options])` - + * `fd` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) * `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) @@ -3775,9 +3775,9 @@ Retrieves the [`fs.Stats`](/api/fs#fsstats) for the file descriptor. See the POSIX fstat(2) documentation for more detail. -#### `fs.fsyncSync(fd)` +#### `fs.fsyncSync(fd)` - + * `fd` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) @@ -3785,9 +3785,9 @@ Request that all data for the open file descriptor is flushed to the storage device. The specific implementation is operating system and device specific. Refer to the POSIX fsync(2) documentation for more detail. Returns `undefined`. -#### `fs.ftruncateSync(fd[, len])` +#### `fs.ftruncateSync(fd[, len])` - + * `fd` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) * `len` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) **Default:** `0` @@ -3797,9 +3797,9 @@ Truncates the file descriptor. Returns `undefined`. For detailed information, see the documentation of the asynchronous version of this API: [`fs.ftruncate()`][]. -#### `fs.futimesSync(fd, atime, mtime)` +#### `fs.futimesSync(fd, atime, mtime)` - + * `fd` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) * `atime` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Date`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date) @@ -3807,9 +3807,9 @@ this API: [`fs.ftruncate()`][]. Synchronous version of [`fs.futimes()`][]. Returns `undefined`. -#### `fs.lchmodSync(path, mode)` +#### `fs.lchmodSync(path, mode)` - + * `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api) * `mode` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) @@ -3820,9 +3820,9 @@ This method is only implemented on macOS. See the POSIX lchmod(2) documentation for more detail. -#### `fs.lchownSync(path, uid, gid)` +#### `fs.lchownSync(path, uid, gid)` - + * `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api) * `uid` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The file's new owner's user id. @@ -3832,9 +3832,9 @@ Set the owner for the path. Returns `undefined`. See the POSIX lchown(2) documentation for more details. -#### `fs.lutimesSync(path, atime, mtime)` +#### `fs.lutimesSync(path, atime, mtime)` - + * `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api) * `atime` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Date`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date) @@ -3844,9 +3844,9 @@ Change the file system timestamps of the symbolic link referenced by `path`. Returns `undefined`, or throws an exception when parameters are incorrect or the operation fails. This is the synchronous version of [`fs.lutimes()`][]. -#### `fs.linkSync(existingPath, newPath)` +#### `fs.linkSync(existingPath, newPath)` - + * `existingPath` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api) * `newPath` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api) @@ -3854,9 +3854,9 @@ the operation fails. This is the synchronous version of [`fs.lutimes()`][]. Creates a new link from the `existingPath` to the `newPath`. See the POSIX link(2) documentation for more detail. Returns `undefined`. -#### `fs.lstatSync(path[, options])` +#### `fs.lstatSync(path[, options])` - + * `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api) * `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) @@ -3871,9 +3871,9 @@ Retrieves the [`fs.Stats`](/api/fs#fsstats) for the symbolic link referred to by See the POSIX lstat(2) documentation for more details. -#### `fs.mkdirSync(path[, options])` +#### `fs.mkdirSync(path[, options])` - + * `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api) * `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) | [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) @@ -3887,9 +3887,9 @@ This is the synchronous version of [`fs.mkdir()`][]. See the POSIX mkdir(2) documentation for more details. -#### `fs.mkdtempSync(prefix[, options])` +#### `fs.mkdtempSync(prefix[, options])` - + * `prefix` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) * `options` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) @@ -3904,9 +3904,9 @@ this API: [`fs.mkdtemp()`][]. The optional `options` argument can be a string specifying an encoding, or an object with an `encoding` property specifying the character encoding to use. -#### `fs.opendirSync(path[, options])` +#### `fs.opendirSync(path[, options])` - + * `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api) * `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) @@ -3924,9 +3924,9 @@ and cleaning up the directory. The `encoding` option sets the encoding for the `path` while opening the directory and subsequent read operations. -#### `fs.openSync(path[, flags[, mode]])` +#### `fs.openSync(path[, flags[, mode]])` - + * `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api) * `flags` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) **Default:** `'r'`. @@ -3939,9 +3939,9 @@ Returns an integer representing the file descriptor. For detailed information, see the documentation of the asynchronous version of this API: [`fs.open()`][]. -#### `fs.readdirSync(path[, options])` +#### `fs.readdirSync(path[, options])` - + * `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api) * `options` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) @@ -3961,9 +3961,9 @@ the filenames returned will be passed as [`Buffer`](/api/buffer#buffer) objects. If `options.withFileTypes` is set to `true`, the result will contain [`fs.Dirent`](/api/fs#fsdirent) objects. -#### `fs.readFileSync(path[, options])` +#### `fs.readFileSync(path[, options])` - + * `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api) | [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) filename or file descriptor * `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) @@ -3993,9 +3993,9 @@ readFileSync(''); readFileSync(''); // => ``` -#### `fs.readlinkSync(path[, options])` +#### `fs.readlinkSync(path[, options])` - + * `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api) * `options` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) @@ -4011,9 +4011,9 @@ object with an `encoding` property specifying the character encoding to use for the link path returned. If the `encoding` is set to `'buffer'`, the link path returned will be passed as a [`Buffer`](/api/buffer#buffer) object. -#### `fs.readSync(fd, buffer, offset, length[, position])` +#### `fs.readSync(fd, buffer, offset, length[, position])` - + * `fd` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) * `buffer` [`Buffer`](/api/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) @@ -4027,9 +4027,9 @@ Returns the number of `bytesRead`. For detailed information, see the documentation of the asynchronous version of this API: [`fs.read()`][]. -#### `fs.readSync(fd, buffer[, options])` +#### `fs.readSync(fd, buffer[, options])` - + * `fd` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) * `buffer` [`Buffer`](/api/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) @@ -4047,9 +4047,9 @@ If no `options` object is specified, it will default with the above values. For detailed information, see the documentation of the asynchronous version of this API: [`fs.read()`][]. -#### `fs.readvSync(fd, buffers[, position])` +#### `fs.readvSync(fd, buffers[, position])` - + * `fd` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) * `buffers` ArrayBufferView\[] @@ -4059,9 +4059,9 @@ this API: [`fs.read()`][]. For detailed information, see the documentation of the asynchronous version of this API: [`fs.readv()`][]. -#### `fs.realpathSync(path[, options])` +#### `fs.realpathSync(path[, options])` - + * `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api) * `options` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) @@ -4073,9 +4073,9 @@ Returns the resolved pathname. For detailed information, see the documentation of the asynchronous version of this API: [`fs.realpath()`][]. -#### `fs.realpathSync.native(path[, options])` +#### `fs.realpathSync.native(path[, options])` - + * `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api) * `options` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) @@ -4095,9 +4095,9 @@ On Linux, when Node.js is linked against musl libc, the procfs file system must be mounted on `/proc` in order for this function to work. Glibc does not have this restriction. -#### `fs.renameSync(oldPath, newPath)` +#### `fs.renameSync(oldPath, newPath)` - + * `oldPath` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api) * `newPath` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api) @@ -4106,9 +4106,9 @@ Renames the file from `oldPath` to `newPath`. Returns `undefined`. See the POSIX rename(2) documentation for more details. -#### `fs.rmdirSync(path[, options])` +#### `fs.rmdirSync(path[, options])` - + * `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api) * `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) @@ -4130,11 +4130,11 @@ Using `fs.rmdirSync()` on a file (not a directory) results in an `ENOENT` error on Windows and an `ENOTDIR` error on POSIX. To get a behavior similar to the `rm -rf` Unix command, use [`fs.rmSync()`][] -with options `{ recursive: true, force: true }`. +with options ````{ recursive: true, force: true }````. -#### `fs.rmSync(path[, options])` +#### `fs.rmSync(path[, options])` - + * `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api) * `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) @@ -4154,9 +4154,9 @@ with options `{ recursive: true, force: true }`. Synchronously removes files and directories (modeled on the standard POSIX `rm` utility). Returns `undefined`. -#### `fs.statSync(path[, options])` +#### `fs.statSync(path[, options])` - + * `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api) * `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) @@ -4169,9 +4169,9 @@ utility). Returns `undefined`. Retrieves the [`fs.Stats`](/api/fs#fsstats) for the path. -#### `fs.symlinkSync(target, path[, type])` +#### `fs.symlinkSync(target, path[, type])` - + * `target` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api) * `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api) @@ -4182,9 +4182,9 @@ Returns `undefined`. For detailed information, see the documentation of the asynchronous version of this API: [`fs.symlink()`][]. -#### `fs.truncateSync(path[, len])` +#### `fs.truncateSync(path[, len])` - + * `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api) * `len` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) **Default:** `0` @@ -4195,17 +4195,17 @@ passed as the first argument. In this case, `fs.ftruncateSync()` is called. Passing a file descriptor is deprecated and may result in an error being thrown in the future. -#### `fs.unlinkSync(path)` +#### `fs.unlinkSync(path)` - + * `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api) Synchronous unlink(2). Returns `undefined`. -#### `fs.utimesSync(path, atime, mtime)` +#### `fs.utimesSync(path, atime, mtime)` - + * `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api) * `atime` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Date`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date) @@ -4216,9 +4216,9 @@ Returns `undefined`. For detailed information, see the documentation of the asynchronous version of this API: [`fs.utimes()`][]. -#### `fs.writeFileSync(file, data[, options])` +#### `fs.writeFileSync(file, data[, options])` - + * `file` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api) | [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) filename or file descriptor * `data` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) | [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) @@ -4235,9 +4235,9 @@ for more details. For detailed information, see the documentation of the asynchronous version of this API: [`fs.writeFile()`][]. -#### `fs.writeSync(fd, buffer, offset[, length[, position]])` +#### `fs.writeSync(fd, buffer, offset[, length[, position]])` - + * `fd` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) * `buffer` [`Buffer`](/api/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) @@ -4249,9 +4249,9 @@ this API: [`fs.writeFile()`][]. For detailed information, see the documentation of the asynchronous version of this API: [`fs.write(fd, buffer...)`][]. -#### `fs.writeSync(fd, buffer[, options])` +#### `fs.writeSync(fd, buffer[, options])` - + * `fd` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) * `buffer` [`Buffer`](/api/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) @@ -4264,9 +4264,9 @@ this API: [`fs.write(fd, buffer...)`][]. For detailed information, see the documentation of the asynchronous version of this API: [`fs.write(fd, buffer...)`][]. -#### `fs.writeSync(fd, string[, position[, encoding]])` +#### `fs.writeSync(fd, string[, position[, encoding]])` - + * `fd` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) * `string` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) @@ -4277,9 +4277,9 @@ this API: [`fs.write(fd, buffer...)`][]. For detailed information, see the documentation of the asynchronous version of this API: [`fs.write(fd, string...)`][]. -#### `fs.writevSync(fd, buffers[, position])` +#### `fs.writevSync(fd, buffers[, position])` - + * `fd` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) * `buffers` ArrayBufferView\[] @@ -4294,9 +4294,9 @@ this API: [`fs.writev()`][]. The common objects are shared by all of the file system API variants (promise, callback, and synchronous). -#### `fs.Dir` +#### `fs.Dir` - + A class representing a directory stream. @@ -4318,9 +4318,9 @@ try { When using the async iterator, the [`fs.Dir`](/api/fs#fsdir) object will be automatically closed after the iterator exits. -##### `dir.close()` +##### `dir.close()` - + * Returns: [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) @@ -4330,9 +4330,9 @@ Subsequent reads will result in errors. A promise is returned that will be resolved after the resource has been closed. -##### `dir.close(callback)` +##### `dir.close(callback)` - + * `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) * `err` [`Error`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error) @@ -4342,25 +4342,25 @@ Subsequent reads will result in errors. The `callback` will be called after the resource handle has been closed. -##### `dir.closeSync()` +##### `dir.closeSync()` - + Synchronously close the directory's underlying resource handle. Subsequent reads will result in errors. -##### `dir.path` +##### `dir.path` - + * [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The read-only path of this directory as was provided to [`fs.opendir()`][], [`fs.opendirSync()`][], or [`fsPromises.opendir()`][]. -##### `dir.read()` +##### `dir.read()` - + * Returns: [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) containing [`fs.Dirent`](/api/fs#fsdirent) | [`null`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type) @@ -4375,9 +4375,9 @@ provided by the operating system's underlying directory mechanisms. Entries added or removed while iterating over the directory might not be included in the iteration results. -##### `dir.read(callback)` +##### `dir.read(callback)` - + * `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) * `err` [`Error`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error) @@ -4394,9 +4394,9 @@ provided by the operating system's underlying directory mechanisms. Entries added or removed while iterating over the directory might not be included in the iteration results. -##### `dir.readSync()` +##### `dir.readSync()` - + * Returns: [`fs.Dirent`](/api/fs#fsdirent) | [`null`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type) @@ -4410,9 +4410,9 @@ provided by the operating system's underlying directory mechanisms. Entries added or removed while iterating over the directory might not be included in the iteration results. -##### `dir[Symbol.asyncIterator]()` +##### `dir[Symbol.asyncIterator]()` - + * Returns: [`AsyncIterator`](https://tc39.github.io/ecma262/#sec-asynciterator-interface) of [`fs.Dirent`](/api/fs#fsdirent) @@ -4429,9 +4429,9 @@ provided by the operating system's underlying directory mechanisms. Entries added or removed while iterating over the directory might not be included in the iteration results. -#### `fs.Dirent` +#### `fs.Dirent` - + A representation of a directory entry, which can be a file or a subdirectory within the directory, as returned by reading from an [`fs.Dir`](/api/fs#fsdir). The @@ -4441,67 +4441,67 @@ Additionally, when [`fs.readdir()`][] or [`fs.readdirSync()`][] is called with the `withFileTypes` option set to `true`, the resulting array is filled with [`fs.Dirent`](/api/fs#fsdirent) objects, rather than strings or [`Buffer`](/api/buffer#buffer)s. -##### `dirent.isBlockDevice()` +##### `dirent.isBlockDevice()` - + * Returns: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) Returns `true` if the [`fs.Dirent`](/api/fs#fsdirent) object describes a block device. -##### `dirent.isCharacterDevice()` +##### `dirent.isCharacterDevice()` - + * Returns: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) Returns `true` if the [`fs.Dirent`](/api/fs#fsdirent) object describes a character device. -##### `dirent.isDirectory()` +##### `dirent.isDirectory()` - + * Returns: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) Returns `true` if the [`fs.Dirent`](/api/fs#fsdirent) object describes a file system directory. -##### `dirent.isFIFO()` +##### `dirent.isFIFO()` - + * Returns: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) Returns `true` if the [`fs.Dirent`](/api/fs#fsdirent) object describes a first-in-first-out (FIFO) pipe. -##### `dirent.isFile()` +##### `dirent.isFile()` - + * Returns: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) Returns `true` if the [`fs.Dirent`](/api/fs#fsdirent) object describes a regular file. -##### `dirent.isSocket()` +##### `dirent.isSocket()` - + * Returns: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) Returns `true` if the [`fs.Dirent`](/api/fs#fsdirent) object describes a socket. -##### `dirent.isSymbolicLink()` +##### `dirent.isSymbolicLink()` - + * Returns: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) Returns `true` if the [`fs.Dirent`](/api/fs#fsdirent) object describes a symbolic link. -##### `dirent.name` +##### `dirent.name` - + * [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) @@ -4509,9 +4509,9 @@ The file name that this [`fs.Dirent`](/api/fs#fsdirent) object refers to. The ty value is determined by the `options.encoding` passed to [`fs.readdir()`][] or [`fs.readdirSync()`][]. -#### `fs.FSWatcher` +#### `fs.FSWatcher` - + * Extends [`EventEmitter`](/api/events#eventemitter) @@ -4521,9 +4521,9 @@ object. All [`fs.FSWatcher`](/api/fs#fsfswatcher) objects emit a `'change'` event whenever a specific watched file is modified. -##### `'change'` +##### `'change'` - + * `eventType` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The type of change event that has occurred * `filename` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) The filename that changed (if relevant/available) @@ -4547,32 +4547,32 @@ watch('./tmp', { encoding: 'buffer' }, (eventType, filename) => { }); ``` -##### `'close'` +##### `'close'` - + Emitted when the watcher stops watching for changes. The closed [`fs.FSWatcher`](/api/fs#fsfswatcher) object is no longer usable in the event handler. -##### `'error'` +##### `'error'` - + * `error` [`Error`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error) Emitted when an error occurs while watching the file. The errored [`fs.FSWatcher`](/api/fs#fsfswatcher) object is no longer usable in the event handler. -##### `watcher.close()` +##### `watcher.close()` - + Stop watching for changes on the given [`fs.FSWatcher`](/api/fs#fsfswatcher). Once stopped, the [`fs.FSWatcher`](/api/fs#fsfswatcher) object is no longer usable. -##### `watcher.ref()` +##### `watcher.ref()` - + * Returns: [`fs.FSWatcher`](/api/fs#fsfswatcher) @@ -4584,9 +4584,9 @@ By default, all [`fs.FSWatcher`](/api/fs#fsfswatcher) objects are "ref'ed", maki unnecessary to call `watcher.ref()` unless `watcher.unref()` had been called previously. -##### `watcher.unref()` +##### `watcher.unref()` - + * Returns: [`fs.FSWatcher`](/api/fs#fsfswatcher) @@ -4596,18 +4596,18 @@ event loop running, the process may exit before the [`fs.FSWatcher`](/api/fs#fsf callback is invoked. Calling `watcher.unref()` multiple times will have no effect. -#### `fs.StatWatcher` +#### `fs.StatWatcher` - + * Extends [`EventEmitter`](/api/events#eventemitter) A successful call to `fs.watchFile()` method will return a new [`fs.StatWatcher`](/api/fs#fsstatwatcher) object. -##### `watcher.ref()` +##### `watcher.ref()` - + * Returns: [`fs.StatWatcher`](/api/fs#fsstatwatcher) @@ -4619,9 +4619,9 @@ By default, all [`fs.StatWatcher`](/api/fs#fsstatwatcher) objects are "ref'ed", unnecessary to call `watcher.ref()` unless `watcher.unref()` had been called previously. -##### `watcher.unref()` +##### `watcher.unref()` - + * Returns: [`fs.StatWatcher`](/api/fs#fsstatwatcher) @@ -4631,48 +4631,48 @@ event loop running, the process may exit before the [`fs.StatWatcher`](/api/fs#f callback is invoked. Calling `watcher.unref()` multiple times will have no effect. -#### `fs.ReadStream` +#### `fs.ReadStream` - + * Extends: [`stream.Readable`](/api/stream#streamreadable) Instances of [`fs.ReadStream`](/api/fs#fsreadstream) are created and returned using the [`fs.createReadStream()`][] function. -##### `'close'` +##### `'close'` - + Emitted when the [`fs.ReadStream`](/api/fs#fsreadstream)'s underlying file descriptor has been closed. -##### `'open'` +##### `'open'` - + * `fd` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Integer file descriptor used by the [`fs.ReadStream`](/api/fs#fsreadstream). Emitted when the [`fs.ReadStream`](/api/fs#fsreadstream)'s file descriptor has been opened. -##### `'ready'` +##### `'ready'` - + Emitted when the [`fs.ReadStream`](/api/fs#fsreadstream) is ready to be used. Fires immediately after `'open'`. -##### `readStream.bytesRead` +##### `readStream.bytesRead` - + * [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The number of bytes that have been read so far. -##### `readStream.path` +##### `readStream.path` - + * [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) @@ -4682,18 +4682,18 @@ argument to `fs.createReadStream()`. If `path` is passed as a string, then `readStream.path` will be a [`Buffer`](/api/buffer#buffer). If `fd` is specified, then `readStream.path` will be `undefined`. -##### `readStream.pending` +##### `readStream.pending` - + * [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) This property is `true` if the underlying file has not been opened yet, i.e. before the `'ready'` event is emitted. -#### `fs.Stats` +#### `fs.Stats` - + A [`fs.Stats`](/api/fs#fsstats) object provides information about a file. @@ -4753,25 +4753,25 @@ BigIntStats { birthtime: Mon, 10 Oct 2011 23:24:11 GMT } ``` -##### `stats.isBlockDevice()` +##### `stats.isBlockDevice()` - + * Returns: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) Returns `true` if the [`fs.Stats`](/api/fs#fsstats) object describes a block device. -##### `stats.isCharacterDevice()` +##### `stats.isCharacterDevice()` - + * Returns: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) Returns `true` if the [`fs.Stats`](/api/fs#fsstats) object describes a character device. -##### `stats.isDirectory()` +##### `stats.isDirectory()` - + * Returns: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) @@ -4781,34 +4781,34 @@ If the [`fs.Stats`](/api/fs#fsstats) object was obtained from [`fs.lstat()`][], always return `false`. This is because [`fs.lstat()`][] returns information about a symbolic link itself and not the path it resolves to. -##### `stats.isFIFO()` +##### `stats.isFIFO()` - + * Returns: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) Returns `true` if the [`fs.Stats`](/api/fs#fsstats) object describes a first-in-first-out (FIFO) pipe. -##### `stats.isFile()` +##### `stats.isFile()` - + * Returns: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) Returns `true` if the [`fs.Stats`](/api/fs#fsstats) object describes a regular file. -##### `stats.isSocket()` +##### `stats.isSocket()` - + * Returns: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) Returns `true` if the [`fs.Stats`](/api/fs#fsstats) object describes a socket. -##### `stats.isSymbolicLink()` +##### `stats.isSymbolicLink()` - + * Returns: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) @@ -4816,49 +4816,49 @@ Returns `true` if the [`fs.Stats`](/api/fs#fsstats) object describes a symbolic This method is only valid when using [`fs.lstat()`][]. -##### `stats.dev` +##### `stats.dev` * [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) | [`bigint`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt) The numeric identifier of the device containing the file. -##### `stats.ino` +##### `stats.ino` * [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) | [`bigint`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt) The file system specific "Inode" number for the file. -##### `stats.mode` +##### `stats.mode` * [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) | [`bigint`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt) A bit-field describing the file type and mode. -##### `stats.nlink` +##### `stats.nlink` * [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) | [`bigint`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt) The number of hard-links that exist for the file. -##### `stats.uid` +##### `stats.uid` * [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) | [`bigint`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt) The numeric user identifier of the user that owns the file (POSIX). -##### `stats.gid` +##### `stats.gid` * [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) | [`bigint`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt) The numeric group identifier of the group that owns the file (POSIX). -##### `stats.rdev` +##### `stats.rdev` * [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) | [`bigint`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt) A numeric device identifier if the file represents a device. -##### `stats.size` +##### `stats.size` * [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) | [`bigint`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt) @@ -4867,57 +4867,57 @@ The size of the file in bytes. If the underlying file system does not support getting the size of the file, this will be `0`. -##### `stats.blksize` +##### `stats.blksize` * [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) | [`bigint`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt) The file system block size for i/o operations. -##### `stats.blocks` +##### `stats.blocks` * [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) | [`bigint`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt) The number of blocks allocated for this file. -##### `stats.atimeMs` +##### `stats.atimeMs` - + * [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) | [`bigint`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt) The timestamp indicating the last time this file was accessed expressed in milliseconds since the POSIX Epoch. -##### `stats.mtimeMs` +##### `stats.mtimeMs` - + * [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) | [`bigint`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt) The timestamp indicating the last time this file was modified expressed in milliseconds since the POSIX Epoch. -##### `stats.ctimeMs` +##### `stats.ctimeMs` - + * [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) | [`bigint`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt) The timestamp indicating the last time the file status was changed expressed in milliseconds since the POSIX Epoch. -##### `stats.birthtimeMs` +##### `stats.birthtimeMs` - + * [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) | [`bigint`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt) The timestamp indicating the creation time of this file expressed in milliseconds since the POSIX Epoch. -##### `stats.atimeNs` +##### `stats.atimeNs` - + * [`bigint`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt) @@ -4926,9 +4926,9 @@ the object. The timestamp indicating the last time this file was accessed expressed in nanoseconds since the POSIX Epoch. -##### `stats.mtimeNs` +##### `stats.mtimeNs` - + * [`bigint`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt) @@ -4937,9 +4937,9 @@ the object. The timestamp indicating the last time this file was modified expressed in nanoseconds since the POSIX Epoch. -##### `stats.ctimeNs` +##### `stats.ctimeNs` - + * [`bigint`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt) @@ -4948,9 +4948,9 @@ the object. The timestamp indicating the last time the file status was changed expressed in nanoseconds since the POSIX Epoch. -##### `stats.birthtimeNs` +##### `stats.birthtimeNs` - + * [`bigint`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt) @@ -4959,33 +4959,33 @@ the object. The timestamp indicating the creation time of this file expressed in nanoseconds since the POSIX Epoch. -##### `stats.atime` +##### `stats.atime` - + * [`Date`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date) The timestamp indicating the last time this file was accessed. -##### `stats.mtime` +##### `stats.mtime` - + * [`Date`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date) The timestamp indicating the last time this file was modified. -##### `stats.ctime` +##### `stats.ctime` - + * [`Date`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date) The timestamp indicating the last time the file status was changed. -##### `stats.birthtime` +##### `stats.birthtime` - + * [`Date`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date) @@ -5031,47 +5031,47 @@ The times in the stat object have the following semantics: Prior to Node.js 0.12, the `ctime` held the `birthtime` on Windows systems. As of 0.12, `ctime` is not "creation time", and on Unix systems, it never was. -#### `fs.WriteStream` +#### `fs.WriteStream` - + * Extends [`stream.Writable`](/api/stream#streamwritable) Instances of [`fs.WriteStream`](/api/fs#fswritestream) are created and returned using the [`fs.createWriteStream()`][] function. -##### `'close'` +##### `'close'` - + Emitted when the [`fs.WriteStream`](/api/fs#fswritestream)'s underlying file descriptor has been closed. -##### `'open'` +##### `'open'` - + * `fd` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Integer file descriptor used by the [`fs.WriteStream`](/api/fs#fswritestream). Emitted when the [`fs.WriteStream`](/api/fs#fswritestream)'s file is opened. -##### `'ready'` +##### `'ready'` - + Emitted when the [`fs.WriteStream`](/api/fs#fswritestream) is ready to be used. Fires immediately after `'open'`. -##### `writeStream.bytesWritten` +##### `writeStream.bytesWritten` - + The number of bytes written so far. Does not include data that is still queued for writing. -##### `writeStream.close([callback])` +##### `writeStream.close([callback])` - + * `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) * `err` [`Error`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error) @@ -5080,25 +5080,25 @@ Closes `writeStream`. Optionally accepts a callback that will be executed once the `writeStream` is closed. -##### `writeStream.path` +##### `writeStream.path` - + The path to the file the stream is writing to as specified in the first argument to [`fs.createWriteStream()`][]. If `path` is passed as a string, then `writeStream.path` will be a string. If `path` is passed as a [`Buffer`](/api/buffer#buffer), then `writeStream.path` will be a [`Buffer`](/api/buffer#buffer). -##### `writeStream.pending` +##### `writeStream.pending` - + * [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) This property is `true` if the underlying file has not been opened yet, i.e. before the `'ready'` event is emitted. -#### `fs.constants` +#### `fs.constants` * [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) @@ -5526,7 +5526,7 @@ try { ##### File URL paths - + For most `node:fs` module functions, the `path` or `filename` argument may be passed as a [`URL`](/api/url#the-whatwg-url-api) object using the `file:` protocol. diff --git a/content/api/v18/globals.en.md b/content/api/v18/globals.en.md index f1ec941a72..51085ee09e 100644 --- a/content/api/v18/globals.en.md +++ b/content/api/v18/globals.en.md @@ -2,13 +2,13 @@ title: 'globals' displayTitle: 'Global objects' category: 'api' -editPage: 'https://github.com/nodejs/node/blob/v18.8.0/doc/api/globals.md' +editPage: 'https://github.com/nodejs/node/blob/v18.9.0/doc/api/globals.md' version: 'v18' --- - + - + These objects are available in all modules. The following variables may appear to be global but are not. They exist only in the scope of modules, see the @@ -24,11 +24,11 @@ The objects listed here are specific to Node.js. There are [built-in objects][] that are part of the JavaScript language itself, which are also globally accessible. -### `AbortController` +### `AbortController` - + - + A utility class used to signal cancelation in selected `Promise`-based APIs. The API is based on the Web API [`AbortController`][]. @@ -44,9 +44,9 @@ ac.abort(); console.log(ac.signal.aborted); // Prints True ``` -#### `abortController.abort([reason])` +#### `abortController.abort([reason])` - + * `reason` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) An optional reason, retrievable on the `AbortSignal`'s `reason` property. @@ -54,15 +54,15 @@ console.log(ac.signal.aborted); // Prints True Triggers the abort signal, causing the `abortController.signal` to emit the `'abort'` event. -#### `abortController.signal` +#### `abortController.signal` - + * Type: [`AbortSignal`](/api/globals#abortsignal) -#### `AbortSignal` +#### `AbortSignal` - + * Extends: [`EventTarget`](/api/events#eventtarget) @@ -71,7 +71,7 @@ The `AbortSignal` is used to notify observers when the ##### Static method: `AbortSignal.abort([reason])` - + * `reason`: [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) * Returns: [`AbortSignal`](/api/globals#abortsignal) @@ -80,16 +80,16 @@ Returns a new already aborted `AbortSignal`. ##### Static method: `AbortSignal.timeout(delay)` - + * `delay` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The number of milliseconds to wait before triggering the AbortSignal. Returns a new `AbortSignal` which will be aborted in `delay` milliseconds. -##### `'abort'` +##### `'abort'` - + The `'abort'` event is emitted when the `abortController.abort()` method is called. The callback is invoked with a single object argument with a @@ -115,29 +115,29 @@ that the `abortSignal.aborted` attribute is `false` before adding an `'abort'` event listener. Any event listeners attached to the `AbortSignal` should use the -`{ once: true }` option (or, if using the `EventEmitter` APIs to attach a +````{ once: true }```` option (or, if using the `EventEmitter` APIs to attach a listener, use the `once()` method) to ensure that the event listener is removed as soon as the `'abort'` event is handled. Failure to do so may result in memory leaks. -##### `abortSignal.aborted` +##### `abortSignal.aborted` - + * Type: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) True after the `AbortController` has been aborted. -##### `abortSignal.onabort` +##### `abortSignal.onabort` - + * Type: [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) An optional callback function that may be set by user code to be notified when the `abortController.abort()` function has been called. -##### `abortSignal.reason` +##### `abortSignal.reason` - + * Type: [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) @@ -149,207 +149,207 @@ ac.abort(new Error('boom!')); console.log(ac.signal.reason); // Error('boom!'); ``` -##### `abortSignal.throwIfAborted()` +##### `abortSignal.throwIfAborted()` - + If `abortSignal.aborted` is `true`, throws `abortSignal.reason`. -### `Blob` +### `Blob` - + - + See [`Blob`](/api/buffer#blob). -### `Buffer` +### `Buffer` - + - + * [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) Used to handle binary data. See the [buffer section][]. -### `ByteLengthQueuingStrategy` +### `ByteLengthQueuingStrategy` - + - + A browser-compatible implementation of [`ByteLengthQueuingStrategy`][]. -### `__dirname` +### `__dirname` This variable may appear to be global but is not. See [`__dirname`][]. -### `__filename` +### `__filename` This variable may appear to be global but is not. See [`__filename`][]. -### `atob(data)` +### `atob(data)` - + - + Global alias for [`buffer.atob()`][]. -### `BroadcastChannel` +### `BroadcastChannel` - + See [`BroadcastChannel`](/api/worker_threads#broadcastchannel-extends-eventtarget). -### `btoa(data)` +### `btoa(data)` - + - + Global alias for [`buffer.btoa()`][]. -### `clearImmediate(immediateObject)` +### `clearImmediate(immediateObject)` - + - + [`clearImmediate`][] is described in the [timers][] section. -### `clearInterval(intervalObject)` +### `clearInterval(intervalObject)` - + - + [`clearInterval`][] is described in the [timers][] section. -### `clearTimeout(timeoutObject)` +### `clearTimeout(timeoutObject)` - + - + [`clearTimeout`][] is described in the [timers][] section. -### `CompressionStream` +### `CompressionStream` - + - + A browser-compatible implementation of [`CompressionStream`][]. -### `console` +### `console` - + - + * [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) Used to print to stdout and stderr. See the [`console`][] section. -### `CountQueuingStrategy` +### `CountQueuingStrategy` - + - + A browser-compatible implementation of [`CountQueuingStrategy`][]. -### `Crypto` +### `Crypto` - + - [`--experimental-global-webcrypto`][] CLI flag."}}} /> + A browser-compatible implementation of [`Crypto`](/api/webcrypto#crypto). This global is available only if the Node.js binary was compiled with including support for the `node:crypto` module. -### `crypto` +### `crypto` - + - [`--experimental-global-webcrypto`][] CLI flag."}}} /> + A browser-compatible implementation of the [Web Crypto API][]. -### `CryptoKey` +### `CryptoKey` - + - [`--experimental-global-webcrypto`][] CLI flag."}}} /> + A browser-compatible implementation of [`CryptoKey`](/api/webcrypto#cryptokey). This global is available only if the Node.js binary was compiled with including support for the `node:crypto` module. -### `CustomEvent` +### `CustomEvent` - + - [`--experimental-global-customevent`][] CLI flag."}}} /> + - + A browser-compatible implementation of the [`CustomEvent` Web API][]. -### `DecompressionStream` +### `DecompressionStream` - + - + A browser-compatible implementation of [`DecompressionStream`][]. -### `Event` +### `Event` - + - + A browser-compatible implementation of the `Event` class. See [`EventTarget` and `Event` API][] for more details. -### `EventTarget` +### `EventTarget` - + - + A browser-compatible implementation of the `EventTarget` class. See [`EventTarget` and `Event` API][] for more details. -### `exports` +### `exports` This variable may appear to be global but is not. See [`exports`][]. -### `fetch` +### `fetch` - + - CLI flag."}}} /> + A browser-compatible implementation of the [`fetch()`][] function. ### Class `FormData` - + - CLI flag."}}} /> + A browser-compatible implementation of [`FormData`](https://developer.mozilla.org/en-US/docs/Web/API/FormData). -### `global` +### `global` - + - + * [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) The global namespace object. @@ -360,61 +360,61 @@ Node.js this is different. The top-level scope is not the global scope; ### Class `Headers` - + - CLI flag."}}} /> + A browser-compatible implementation of [`Headers`](https://developer.mozilla.org/en-US/docs/Web/API/Headers). -### `MessageChannel` +### `MessageChannel` - + - + The `MessageChannel` class. See [`MessageChannel`][] for more details. -### `MessageEvent` +### `MessageEvent` - + - + The `MessageEvent` class. See [`MessageEvent`][] for more details. -### `MessagePort` +### `MessagePort` - + - + The `MessagePort` class. See [`MessagePort`][] for more details. -### `module` +### `module` This variable may appear to be global but is not. See [`module`][]. -### `performance` +### `performance` - + The [`perf_hooks.performance`][] object. -### `process` +### `process` - + - + * [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) The process object. See the [`process` object][] section. -### `queueMicrotask(callback)` +### `queueMicrotask(callback)` - + - + * `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) Function to be queued. @@ -448,193 +448,193 @@ DataHandler.prototype.load = async function load(key) { }; ``` -### `ReadableByteStreamController` +### `ReadableByteStreamController` - + - + A browser-compatible implementation of [`ReadableByteStreamController`][]. -### `ReadableStream` +### `ReadableStream` - + - + A browser-compatible implementation of [`ReadableStream`][]. -### `ReadableStreamBYOBReader` +### `ReadableStreamBYOBReader` - + - + A browser-compatible implementation of [`ReadableStreamBYOBReader`][]. -### `ReadableStreamBYOBRequest` +### `ReadableStreamBYOBRequest` - + - + A browser-compatible implementation of [`ReadableStreamBYOBRequest`][]. -### `ReadableStreamDefaultController` +### `ReadableStreamDefaultController` - + - + A browser-compatible implementation of [`ReadableStreamDefaultController`][]. -### `ReadableStreamDefaultReader` +### `ReadableStreamDefaultReader` - + - + A browser-compatible implementation of [`ReadableStreamDefaultReader`][]. -### `require()` +### `require()` This variable may appear to be global but is not. See [`require()`][]. -### `Response` +### `Response` - + - CLI flag."}}} /> + A browser-compatible implementation of [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response). -### `Request` +### `Request` - + - CLI flag."}}} /> + A browser-compatible implementation of [`Request`](https://developer.mozilla.org/en-US/docs/Web/API/Request). -### `setImmediate(callback[, ...args])` +### `setImmediate(callback[, ...args])` - + - + [`setImmediate`][] is described in the [timers][] section. -### `setInterval(callback, delay[, ...args])` +### `setInterval(callback, delay[, ...args])` - + - + [`setInterval`][] is described in the [timers][] section. -### `setTimeout(callback, delay[, ...args])` +### `setTimeout(callback, delay[, ...args])` - + - + [`setTimeout`][] is described in the [timers][] section. -### `structuredClone(value[, options])` +### `structuredClone(value[, options])` - + - + The WHATWG [`structuredClone`][] method. -### `SubtleCrypto` +### `SubtleCrypto` - + - [`--experimental-global-webcrypto`][] CLI flag."}}} /> + A browser-compatible implementation of [`SubtleCrypto`](/api/webcrypto#subtlecrypto). This global is available only if the Node.js binary was compiled with including support for the `node:crypto` module. -### `DOMException` +### `DOMException` - + - + The WHATWG `DOMException` class. See [`DOMException`][] for more details. -### `TextDecoder` +### `TextDecoder` - + - + The WHATWG `TextDecoder` class. See the [`TextDecoder`][] section. -### `TextDecoderStream` +### `TextDecoderStream` - + - + A browser-compatible implementation of [`TextDecoderStream`][]. -### `TextEncoder` +### `TextEncoder` - + - + The WHATWG `TextEncoder` class. See the [`TextEncoder`][] section. -### `TextEncoderStream` +### `TextEncoderStream` - + - + A browser-compatible implementation of [`TextEncoderStream`][]. -### `TransformStream` +### `TransformStream` - + - + A browser-compatible implementation of [`TransformStream`][]. -### `TransformStreamDefaultController` +### `TransformStreamDefaultController` - + - + A browser-compatible implementation of [`TransformStreamDefaultController`][]. -### `URL` +### `URL` - + - + The WHATWG `URL` class. See the [`URL`][] section. -### `URLSearchParams` +### `URLSearchParams` - + - + The WHATWG `URLSearchParams` class. See the [`URLSearchParams`][] section. -### `WebAssembly` +### `WebAssembly` - + - + * [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) @@ -642,27 +642,27 @@ The object that acts as the namespace for all W3C [WebAssembly][webassembly-org] related functionality. See the [Mozilla Developer Network][webassembly-mdn] for usage and compatibility. -### `WritableStream` +### `WritableStream` - + - + A browser-compatible implementation of [`WritableStream`][]. -### `WritableStreamDefaultController` +### `WritableStreamDefaultController` - + - + A browser-compatible implementation of [`WritableStreamDefaultController`][]. -### `WritableStreamDefaultWriter` +### `WritableStreamDefaultWriter` - + - + A browser-compatible implementation of [`WritableStreamDefaultWriter`][]. diff --git a/content/api/v18/http.en.md b/content/api/v18/http.en.md index 12b37a69f9..4b3f5ac7cc 100644 --- a/content/api/v18/http.en.md +++ b/content/api/v18/http.en.md @@ -2,15 +2,15 @@ title: 'http' displayTitle: 'HTTP' category: 'api' -editPage: 'https://github.com/nodejs/node/blob/v18.8.0/doc/api/http.md' +editPage: 'https://github.com/nodejs/node/blob/v18.9.0/doc/api/http.md' version: 'v18' --- - + - + - + To use the HTTP server and client one must `require('node:http')`. @@ -57,9 +57,9 @@ list like the following: 'accepT', '*/*' ] ``` -### `http.Agent` +### `http.Agent` - + An `Agent` is responsible for managing connection persistence and reuse for HTTP clients. It maintains a queue of pending requests @@ -99,7 +99,7 @@ http.get(options, (res) => { ``` An agent may also be used for an individual request. By providing -`{agent: false}` as an option to the `http.get()` or `http.request()` +````{agent: false}```` as an option to the `http.get()` or `http.request()` functions, a one-time use `Agent` with default options will be used for the client connection. @@ -116,9 +116,9 @@ http.get({ }); ``` -#### `new Agent([options])` +#### `new Agent([options])` - + * `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) Set of configurable options to set on the agent. Can have the following fields: @@ -179,9 +179,9 @@ options.agent = keepAliveAgent; http.request(options, onResponseCallback); ``` -#### `agent.createConnection(options[, callback])` +#### `agent.createConnection(options[, callback])` - + * `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) Options containing connection details. Check [`net.createConnection()`][] for the format of the options @@ -202,9 +202,9 @@ type other than [`net.Socket`](/api/net#netsocket). `callback` has a signature of `(err, stream)`. -#### `agent.keepSocketAlive(socket)` +#### `agent.keepSocketAlive(socket)` - + * `socket` [`stream.Duplex`](/api/stream#streamduplex) @@ -224,9 +224,9 @@ it for use with the next request. The `socket` argument can be an instance of [`net.Socket`](/api/net#netsocket), a subclass of [`stream.Duplex`](/api/stream#streamduplex). -#### `agent.reuseSocket(socket, request)` +#### `agent.reuseSocket(socket, request)` - + * `socket` [`stream.Duplex`](/api/stream#streamduplex) * `request` [`http.ClientRequest`](/api/http#httpclientrequest) @@ -243,9 +243,9 @@ This method can be overridden by a particular `Agent` subclass. The `socket` argument can be an instance of [`net.Socket`](/api/net#netsocket), a subclass of [`stream.Duplex`](/api/stream#streamduplex). -#### `agent.destroy()` +#### `agent.destroy()` - + Destroy any sockets that are currently in use by the agent. @@ -255,9 +255,9 @@ the agent when it is no longer needed. Otherwise, sockets might stay open for quite a long time before the server terminates them. -#### `agent.freeSockets` +#### `agent.freeSockets` - + * [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) @@ -267,9 +267,9 @@ the agent when `keepAlive` is enabled. Do not modify. Sockets in the `freeSockets` list will be automatically destroyed and removed from the array on `'timeout'`. -#### `agent.getName([options])` +#### `agent.getName([options])` - + * `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) A set of options providing information for name generation * `host` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) A domain name or IP address of the server to issue the @@ -286,9 +286,9 @@ connection can be reused. For an HTTP agent, this returns the name includes the CA, cert, ciphers, and other HTTPS/TLS-specific options that determine socket reusability. -#### `agent.maxFreeSockets` +#### `agent.maxFreeSockets` - + * [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) @@ -296,45 +296,45 @@ By default set to 256. For agents with `keepAlive` enabled, this sets the maximum number of sockets that will be left open in the free state. -#### `agent.maxSockets` +#### `agent.maxSockets` - + * [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) By default set to `Infinity`. Determines how many concurrent sockets the agent can have open per origin. Origin is the returned value of [`agent.getName()`][]. -#### `agent.maxTotalSockets` +#### `agent.maxTotalSockets` - + * [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) By default set to `Infinity`. Determines how many concurrent sockets the agent can have open. Unlike `maxSockets`, this parameter applies across all origins. -#### `agent.requests` +#### `agent.requests` - + * [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) An object which contains queues of requests that have not yet been assigned to sockets. Do not modify. -#### `agent.sockets` +#### `agent.sockets` - + * [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) An object which contains arrays of sockets currently in use by the agent. Do not modify. -### `http.ClientRequest` +### `http.ClientRequest` - + * Extends: [`http.OutgoingMessage`](/api/http#httpoutgoingmessage) @@ -367,25 +367,25 @@ For backward compatibility, `res` will only emit `'error'` if there is an Node.js does not check whether Content-Length and the length of the body which has been transmitted are equal or not. -#### `'abort'` +#### `'abort'` - + - + Emitted when the request has been aborted by the client. This event is only emitted on the first call to `abort()`. -#### `'close'` +#### `'close'` - + Indicates that the request is completed, or its underlying connection was terminated prematurely (before the response completion). -#### `'connect'` +#### `'connect'` - + * `response` [`http.IncomingMessage`](/api/http#httpincomingmessage) * `socket` [`stream.Duplex`](/api/stream#streamduplex) @@ -413,7 +413,7 @@ const proxy = http.createServer((req, res) => { }); proxy.on('connect', (req, clientSocket, head) => { // Connect to an origin server - const { port, hostname } = new URL(`http://$req.url`); + const { port, hostname } = new URL(`http://${req.url}`); const serverSocket = net.connect(port || 80, hostname, () => { clientSocket.write('HTTP/1.1 200 Connection Established\r\n' + 'Proxy-agent: Node.js-Proxy\r\n' + @@ -456,26 +456,26 @@ proxy.listen(1337, '127.0.0.1', () => { }); ``` -#### `'continue'` +#### `'continue'` - + Emitted when the server sends a '100 Continue' HTTP response, usually because the request contained 'Expect: 100-continue'. This is an instruction that the client should send the request body. -#### `'finish'` +#### `'finish'` - + Emitted when the request has been sent. More specifically, this event is emitted when the last segment of the response headers and body have been handed off to the operating system for transmission over the network. It does not imply that the server has received anything yet. -#### `'information'` +#### `'information'` - + * `info` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) * `httpVersion` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) @@ -505,7 +505,7 @@ const req = http.request(options); req.end(); req.on('information', (info) => { - console.log(`Got information prior to main response: $info.statusCode`); + console.log(`Got information prior to main response: ${info.statusCode}`); }); ``` @@ -514,18 +514,18 @@ traditional HTTP request/response chain, such as web sockets, in-place TLS upgrades, or HTTP 2.0. To be notified of 101 Upgrade notices, listen for the [`'upgrade'`][] event instead. -#### `'response'` +#### `'response'` - + * `response` [`http.IncomingMessage`](/api/http#httpincomingmessage) Emitted when a response is received to this request. This event is emitted only once. -#### `'socket'` +#### `'socket'` - + * `socket` [`stream.Duplex`](/api/stream#streamduplex) @@ -533,18 +533,18 @@ This event is guaranteed to be passed an instance of the [`net.Socket`](/api/net a subclass of [`stream.Duplex`](/api/stream#streamduplex), unless the user specifies a socket type other than [`net.Socket`](/api/net#netsocket). -#### `'timeout'` +#### `'timeout'` - + Emitted when the underlying socket times out from inactivity. This only notifies that the socket has been idle. The request must be destroyed manually. See also: [`request.setTimeout()`][]. -#### `'upgrade'` +#### `'upgrade'` - + * `response` [`http.IncomingMessage`](/api/http#httpincomingmessage) * `socket` [`stream.Duplex`](/api/stream#streamduplex) @@ -602,45 +602,45 @@ server.listen(1337, '127.0.0.1', () => { }); ``` -#### `request.abort()` +#### `request.abort()` - + - + Marks the request as aborting. Calling this will cause remaining data in the response to be dropped and the socket to be destroyed. -#### `request.aborted` +#### `request.aborted` - + - + * [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) The `request.aborted` property will be `true` if the request has been aborted. -#### `request.connection` +#### `request.connection` - + - + * [`stream.Duplex`](/api/stream#streamduplex) See [`request.socket`][]. -#### `request.cork()` +#### `request.cork()` - + See [`writable.cork()`][]. -#### `request.end([data[, encoding]][, callback])` +#### `request.end([data[, encoding]][, callback])` - + * `data` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) * `encoding` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) @@ -657,9 +657,9 @@ If `data` is specified, it is equivalent to calling If `callback` is specified, it will be called when the request stream is finished. -#### `request.destroy([error])` +#### `request.destroy([error])` - + * `error` [`Error`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error) Optional, an error to emit with `'error'` event. * Returns: [`this`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this) @@ -670,9 +670,9 @@ in the response to be dropped and the socket to be destroyed. See [`writable.destroy()`][] for further details. -##### `request.destroyed` +##### `request.destroyed` - + * [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) @@ -680,11 +680,11 @@ Is `true` after [`request.destroy()`][] has been called. See [`writable.destroyed`][] for further details. -#### `request.finished` +#### `request.finished` - + - + * [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) @@ -692,9 +692,9 @@ The `request.finished` property will be `true` if [`request.end()`][] has been called. `request.end()` will automatically be called if the request was initiated via [`http.get()`][]. -#### `request.flushHeaders()` +#### `request.flushHeaders()` - + Flushes the request headers. @@ -706,9 +706,9 @@ That's usually desired (it saves a TCP round-trip), but not when the first data is not sent until possibly much later. `request.flushHeaders()` bypasses the optimization and kickstarts the request. -#### `request.getHeader(name)` +#### `request.getHeader(name)` - + * `name` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) * Returns: [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) @@ -729,9 +729,9 @@ const cookie = request.getHeader('Cookie'); // 'cookie' is of type string[] ``` -#### `request.getHeaderNames()` +#### `request.getHeaderNames()` - + * Returns: string\[] @@ -746,9 +746,9 @@ const headerNames = request.getHeaderNames(); // headerNames === ['foo', 'cookie'] ``` -#### `request.getHeaders()` +#### `request.getHeaders()` - + * Returns: [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) @@ -771,9 +771,9 @@ const headers = response.getHeaders(); // headers === { foo: 'bar', 'cookie': ['foo=bar', 'bar=baz'] } ``` -#### `request.getRawHeaderNames()` +#### `request.getRawHeaderNames()` - + * Returns: string\[] @@ -788,9 +788,9 @@ const headerNames = request.getRawHeaderNames(); // headerNames === ['Foo', 'Set-Cookie'] ``` -#### `request.hasHeader(name)` +#### `request.hasHeader(name)` - + * `name` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) * Returns: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) @@ -802,39 +802,39 @@ outgoing headers. The header name matching is case-insensitive. const hasContentType = request.hasHeader('content-type'); ``` -#### `request.maxHeadersCount` +#### `request.maxHeadersCount` * [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) **Default:** `2000` Limits maximum response headers count. If set to 0, no limit will be applied. -#### `request.path` +#### `request.path` - + * [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The request path. -#### `request.method` +#### `request.method` - + * [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The request method. -#### `request.host` +#### `request.host` - + * [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The request host. -#### `request.protocol` +#### `request.protocol` - + * [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The request protocol. -#### `request.removeHeader(name)` +#### `request.removeHeader(name)` - + * `name` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) @@ -844,9 +844,9 @@ Removes a header that's already defined into headers object. request.removeHeader('Content-Type'); ``` -#### `request.reusedSocket` +#### `request.reusedSocket` - + * [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) Whether the request is send through a reused socket. @@ -898,9 +898,9 @@ function retriableRequest() { retriableRequest(); ``` -#### `request.setHeader(name, value)` +#### `request.setHeader(name, value)` - + * `name` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) * `value` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) @@ -933,18 +933,18 @@ const filename = 'Rock 🎵.txt'; request.setHeader('Content-Disposition', `attachment; filename*=utf-8''${encodeURIComponent(filename)}`); ``` -#### `request.setNoDelay([noDelay])` +#### `request.setNoDelay([noDelay])` - + * `noDelay` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) Once a socket is assigned to this request and is connected [`socket.setNoDelay()`][] will be called. -#### `request.setSocketKeepAlive([enable][, initialDelay])` +#### `request.setSocketKeepAlive([enable][, initialDelay])` - + * `enable` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) * `initialDelay` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) @@ -952,9 +952,9 @@ Once a socket is assigned to this request and is connected Once a socket is assigned to this request and is connected [`socket.setKeepAlive()`][] will be called. -#### `request.setTimeout(timeout[, callback])` +#### `request.setTimeout(timeout[, callback])` - + * `timeout` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Milliseconds before a request times out. * `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) Optional function to be called when a timeout occurs. @@ -964,9 +964,9 @@ Once a socket is assigned to this request and is connected Once a socket is assigned to this request and is connected [`socket.setTimeout()`][] will be called. -#### `request.socket` +#### `request.socket` - + * [`stream.Duplex`](/api/stream#streamduplex) @@ -984,7 +984,7 @@ req.end(); req.once('response', (res) => { const ip = req.socket.localAddress; const port = req.socket.localPort; - console.log(`Your IP address is $ip and your source port is $port.`); + console.log(`Your IP address is ${ip} and your source port is ${port}.`); // Consume response object }); ``` @@ -993,15 +993,15 @@ This property is guaranteed to be an instance of the [`net.Socket`](/api/net#net a subclass of [`stream.Duplex`](/api/stream#streamduplex), unless the user specified a socket type other than [`net.Socket`](/api/net#netsocket). -#### `request.uncork()` +#### `request.uncork()` - + See [`writable.uncork()`][]. -#### `request.writableEnded` +#### `request.writableEnded` - + * [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) @@ -1009,18 +1009,18 @@ Is `true` after [`request.end()`][] has been called. This property does not indicate whether the data has been flushed, for this use [`request.writableFinished`][] instead. -#### `request.writableFinished` +#### `request.writableFinished` - + * [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) Is `true` if all data has been flushed to the underlying system, immediately before the [`'finish'`][] event is emitted. -#### `request.write(chunk[, encoding][, callback])` +#### `request.write(chunk[, encoding][, callback])` - + * `chunk` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) * `encoding` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) @@ -1046,15 +1046,15 @@ buffer. Returns `false` if all or part of the data was queued in user memory. When `write` function is called with empty string or buffer, it does nothing and waits for more input. -### `http.Server` +### `http.Server` - + * Extends: [`net.Server`](/api/net#netserver) -#### `'checkContinue'` +#### `'checkContinue'` - + * `request` [`http.IncomingMessage`](/api/http#httpincomingmessage) * `response` [`http.ServerResponse`](/api/http#httpserverresponse) @@ -1071,9 +1071,9 @@ the request body. When this event is emitted and handled, the [`'request'`][] event will not be emitted. -#### `'checkExpectation'` +#### `'checkExpectation'` - + * `request` [`http.IncomingMessage`](/api/http#httpincomingmessage) * `response` [`http.ServerResponse`](/api/http#httpserverresponse) @@ -1085,9 +1085,9 @@ automatically respond with a `417 Expectation Failed` as appropriate. When this event is emitted and handled, the [`'request'`][] event will not be emitted. -#### `'clientError'` +#### `'clientError'` - + * `exception` [`Error`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error) * `socket` [`stream.Duplex`](/api/stream#streamduplex) @@ -1146,15 +1146,15 @@ server.on('clientError', (err, socket) => { }); ``` -#### `'close'` +#### `'close'` - + Emitted when the server closes. -#### `'connect'` +#### `'connect'` - + * `request` [`http.IncomingMessage`](/api/http#httpincomingmessage) Arguments for the HTTP request, as it is in the [`'request'`][] event @@ -1173,9 +1173,9 @@ After this event is emitted, the request's socket will not have a `'data'` event listener, meaning it will need to be bound in order to handle data sent to the server on that socket. -#### `'connection'` +#### `'connection'` - + * `socket` [`stream.Duplex`](/api/stream#streamduplex) @@ -1196,9 +1196,9 @@ This event is guaranteed to be passed an instance of the [`net.Socket`](/api/net a subclass of [`stream.Duplex`](/api/stream#streamduplex), unless the user specifies a socket type other than [`net.Socket`](/api/net#netsocket). -#### `'dropRequest'` +#### `'dropRequest'` - + * `request` [`http.IncomingMessage`](/api/http#httpincomingmessage) Arguments for the HTTP request, as it is in the [`'request'`][] event @@ -1208,9 +1208,9 @@ When the number of requests on a socket reaches the threshold of `server.maxRequestsPerSocket`, the server will drop new requests and emit `'dropRequest'` event instead, then send `503` to client. -#### `'request'` +#### `'request'` - + * `request` [`http.IncomingMessage`](/api/http#httpincomingmessage) * `response` [`http.ServerResponse`](/api/http#httpserverresponse) @@ -1218,9 +1218,9 @@ and emit `'dropRequest'` event instead, then send `503` to client. Emitted each time there is a request. There may be multiple requests per connection (in the case of HTTP Keep-Alive connections). -#### `'upgrade'` +#### `'upgrade'` - + * `request` [`http.IncomingMessage`](/api/http#httpincomingmessage) Arguments for the HTTP request, as it is in the [`'request'`][] event @@ -1238,30 +1238,30 @@ This event is guaranteed to be passed an instance of the [`net.Socket`](/api/net a subclass of [`stream.Duplex`](/api/stream#streamduplex), unless the user specifies a socket type other than [`net.Socket`](/api/net#netsocket). -#### `server.close([callback])` +#### `server.close([callback])` - + * `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) Stops the server from accepting new connections. See [`net.Server.close()`][]. -#### `server.closeAllConnections()` +#### `server.closeAllConnections()` - + Closes all connections connected to this server. -#### `server.closeIdleConnections()` +#### `server.closeIdleConnections()` - + Closes all connections connected to this server which are not sending a request or waiting for a response. -#### `server.headersTimeout` +#### `server.headersTimeout` - + * [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) **Default:** `60000` @@ -1275,28 +1275,28 @@ It must be set to a non-zero value (e.g. 120 seconds) to protect against potential Denial-of-Service attacks in case the server is deployed without a reverse proxy in front. -#### `server.listen()` +#### `server.listen()` Starts the HTTP server listening for connections. This method is identical to [`server.listen()`][] from [`net.Server`][]. -#### `server.listening` +#### `server.listening` - + * [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) Indicates whether or not the server is listening for connections. -#### `server.maxHeadersCount` +#### `server.maxHeadersCount` - + * [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) **Default:** `2000` Limits maximum incoming headers count. If set to 0, no limit will be applied. -#### `server.requestTimeout` +#### `server.requestTimeout` - + * [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) **Default:** `300000` @@ -1310,9 +1310,9 @@ It must be set to a non-zero value (e.g. 120 seconds) to protect against potential Denial-of-Service attacks in case the server is deployed without a reverse proxy in front. -#### `server.setTimeout([msecs][, callback])` +#### `server.setTimeout([msecs][, callback])` - + * `msecs` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) **Default:** 0 (no timeout) * `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) @@ -1329,9 +1329,9 @@ By default, the Server does not timeout sockets. However, if a callback is assigned to the Server's `'timeout'` event, timeouts must be handled explicitly. -#### `server.maxRequestsPerSocket` +#### `server.maxRequestsPerSocket` - + * [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Requests per socket. **Default:** 0 (no limit) @@ -1344,9 +1344,9 @@ When the limit is reached it will set the `Connection` header value to `close`, but will not actually close the connection, subsequent requests sent after the limit is reached will get `503 Service Unavailable` as a response. -#### `server.timeout` +#### `server.timeout` - + * [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Timeout in milliseconds. **Default:** 0 (no timeout) @@ -1358,9 +1358,9 @@ A value of `0` will disable the timeout behavior on incoming connections. The socket timeout logic is set up on connection, so changing this value only affects new connections to the server, not any existing connections. -#### `server.keepAliveTimeout` +#### `server.keepAliveTimeout` - + * [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Timeout in milliseconds. **Default:** `5000` (5 seconds). @@ -1378,34 +1378,34 @@ to 8.0.0, which did not have a keep-alive timeout. The socket timeout logic is set up on connection, so changing this value only affects new connections to the server, not any existing connections. -### `http.ServerResponse` +### `http.ServerResponse` - + * Extends: [`http.OutgoingMessage`](/api/http#httpoutgoingmessage) This object is created internally by an HTTP server, not by the user. It is passed as the second parameter to the [`'request'`][] event. -#### `'close'` +#### `'close'` - + Indicates that the response is completed, or its underlying connection was terminated prematurely (before the response completion). -#### `'finish'` +#### `'finish'` - + Emitted when the response has been sent. More specifically, this event is emitted when the last segment of the response headers and body have been handed off to the operating system for transmission over the network. It does not imply that the client has received anything yet. -#### `response.addTrailers(headers)` +#### `response.addTrailers(headers)` - + * `headers` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) @@ -1430,25 +1430,25 @@ response.end(); Attempting to set a header field name or value that contains invalid characters will result in a [`TypeError`][] being thrown. -#### `response.connection` +#### `response.connection` - + - + * [`stream.Duplex`](/api/stream#streamduplex) See [`response.socket`][]. -#### `response.cork()` +#### `response.cork()` - + See [`writable.cork()`][]. -#### `response.end([data[, encoding]][, callback])` +#### `response.end([data[, encoding]][, callback])` - + * `data` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) * `encoding` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) @@ -1465,26 +1465,26 @@ If `data` is specified, it is similar in effect to calling If `callback` is specified, it will be called when the response stream is finished. -#### `response.finished` +#### `response.finished` - + - + * [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) The `response.finished` property will be `true` if [`response.end()`][] has been called. -#### `response.flushHeaders()` +#### `response.flushHeaders()` - + Flushes the response headers. See also: [`request.flushHeaders()`][]. -#### `response.getHeader(name)` +#### `response.getHeader(name)` - + * `name` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) * Returns: [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) @@ -1505,9 +1505,9 @@ const setCookie = response.getHeader('set-cookie'); // setCookie is of type string[] ``` -#### `response.getHeaderNames()` +#### `response.getHeaderNames()` - + * Returns: string\[] @@ -1522,9 +1522,9 @@ const headerNames = response.getHeaderNames(); // headerNames === ['foo', 'set-cookie'] ``` -#### `response.getHeaders()` +#### `response.getHeaders()` - + * Returns: [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) @@ -1547,9 +1547,9 @@ const headers = response.getHeaders(); // headers === { foo: 'bar', 'set-cookie': ['foo=bar', 'bar=baz'] } ``` -#### `response.hasHeader(name)` +#### `response.hasHeader(name)` - + * `name` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) * Returns: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) @@ -1561,17 +1561,17 @@ outgoing headers. The header name matching is case-insensitive. const hasContentType = response.hasHeader('content-type'); ``` -#### `response.headersSent` +#### `response.headersSent` - + * [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) Boolean (read-only). True if headers were sent, false otherwise. -#### `response.removeHeader(name)` +#### `response.removeHeader(name)` - + * `name` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) @@ -1581,17 +1581,17 @@ Removes a header that's queued for implicit sending. response.removeHeader('Content-Encoding'); ``` -#### `response.req` +#### `response.req` - + * [`http.IncomingMessage`](/api/http#httpincomingmessage) A reference to the original HTTP `request` object. -#### `response.sendDate` +#### `response.sendDate` - + * [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) @@ -1601,9 +1601,9 @@ the response if it is not already present in the headers. Defaults to true. This should only be disabled for testing; HTTP requires the Date header in responses. -#### `response.setHeader(name, value)` +#### `response.setHeader(name, value)` - + * `name` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) * `value` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) @@ -1653,9 +1653,9 @@ header will not yield the expected result. If progressive population of headers is desired with potential future retrieval and modification, use [`response.setHeader()`][] instead of [`response.writeHead()`][]. -#### `response.setTimeout(msecs[, callback])` +#### `response.setTimeout(msecs[, callback])` - + * `msecs` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) * `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) @@ -1670,9 +1670,9 @@ the server, then sockets are destroyed when they time out. If a handler is assigned to the request, the response, or the server's `'timeout'` events, timed out sockets must be handled explicitly. -#### `response.socket` +#### `response.socket` - + * [`stream.Duplex`](/api/stream#streamduplex) @@ -1686,7 +1686,7 @@ const http = require('node:http'); const server = http.createServer((req, res) => { const ip = res.socket.remoteAddress; const port = res.socket.remotePort; - res.end(`Your IP address is $ip and your source port is $port.`); + res.end(`Your IP address is ${ip} and your source port is ${port}.`); }).listen(3000); ``` @@ -1694,9 +1694,9 @@ This property is guaranteed to be an instance of the [`net.Socket`](/api/net#net a subclass of [`stream.Duplex`](/api/stream#streamduplex), unless the user specified a socket type other than [`net.Socket`](/api/net#netsocket). -#### `response.statusCode` +#### `response.statusCode` - + * [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) **Default:** `200` @@ -1711,9 +1711,9 @@ response.statusCode = 404; After response header was sent to the client, this property indicates the status code which was sent out. -#### `response.statusMessage` +#### `response.statusMessage` - + * [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) @@ -1729,15 +1729,15 @@ response.statusMessage = 'Not found'; After response header was sent to the client, this property indicates the status message which was sent out. -#### `response.uncork()` +#### `response.uncork()` - + See [`writable.uncork()`][]. -#### `response.writableEnded` +#### `response.writableEnded` - + * [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) @@ -1745,18 +1745,18 @@ Is `true` after [`response.end()`][] has been called. This property does not indicate whether the data has been flushed, for this use [`response.writableFinished`][] instead. -#### `response.writableFinished` +#### `response.writableFinished` - + * [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) Is `true` if all data has been flushed to the underlying system, immediately before the [`'finish'`][] event is emitted. -#### `response.write(chunk[, encoding][, callback])` +#### `response.write(chunk[, encoding][, callback])` - + * `chunk` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) * `encoding` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) **Default:** `'utf8'` @@ -1790,17 +1790,17 @@ Returns `true` if the entire data was flushed successfully to the kernel buffer. Returns `false` if all or part of the data was queued in user memory. `'drain'` will be emitted when the buffer is free again. -#### `response.writeContinue()` +#### `response.writeContinue()` - + Sends a HTTP/1.1 100 Continue message to the client, indicating that the request body should be sent. See the [`'checkContinue'`][] event on `Server`. -#### `response.writeHead(statusCode[, statusMessage][, headers])` +#### `response.writeHead(statusCode[, statusMessage][, headers])` - + * `statusCode` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) * `statusMessage` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) @@ -1864,16 +1864,16 @@ been transmitted are equal or not. Attempting to set a header field name or value that contains invalid characters will result in a [`TypeError`][] being thrown. -#### `response.writeProcessing()` +#### `response.writeProcessing()` - + Sends a HTTP/1.1 102 Processing message to the client, indicating that the request body should be sent. -### `http.IncomingMessage` +### `http.IncomingMessage` - + * Extends: [`stream.Readable`](/api/stream#streamreadable) @@ -1887,34 +1887,34 @@ Different from its `socket` value which is a subclass of [`stream.Duplex`](/api/ parse and emit the incoming HTTP headers and payload, as the underlying socket may be reused multiple times in case of keep-alive. -#### `'aborted'` +#### `'aborted'` - + - + Emitted when the request has been aborted. -#### `'close'` +#### `'close'` - + Emitted when the request has been completed. -#### `message.aborted` +#### `message.aborted` - + - + * [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) The `message.aborted` property will be `true` if the request has been aborted. -#### `message.complete` +#### `message.complete` - + * [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) @@ -1939,17 +1939,17 @@ const req = http.request({ }); ``` -#### `message.connection` +#### `message.connection` - + - + Alias for [`message.socket`][]. -#### `message.destroy([error])` +#### `message.destroy([error])` - + * `error` [`Error`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error) * Returns: [`this`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this) @@ -1958,9 +1958,9 @@ Calls `destroy()` on the socket that received the `IncomingMessage`. If `error` is provided, an `'error'` event is emitted on the socket and `error` is passed as an argument to any listeners on the event. -#### `message.headers` +#### `message.headers` - + * [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) @@ -1988,9 +1988,9 @@ header name: * For duplicate `cookie` headers, the values are joined together with `; `. * For all other headers, the values are joined together with `, `. -#### `message.headersDistinct` +#### `message.headersDistinct` - + * [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) @@ -2006,9 +2006,9 @@ always arrays of strings, even for headers received just once. console.log(request.headersDistinct); ``` -#### `message.httpVersion` +#### `message.httpVersion` - + * [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) @@ -2019,9 +2019,9 @@ Probably either `'1.1'` or `'1.0'`. Also `message.httpVersionMajor` is the first integer and `message.httpVersionMinor` is the second. -#### `message.method` +#### `message.method` - + * [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) @@ -2029,9 +2029,9 @@ Also `message.httpVersionMajor` is the first integer and The request method as a string. Read only. Examples: `'GET'`, `'DELETE'`. -#### `message.rawHeaders` +#### `message.rawHeaders` - + * string\[] @@ -2057,18 +2057,18 @@ Header names are not lowercased, and duplicates are not merged. console.log(request.rawHeaders); ``` -#### `message.rawTrailers` +#### `message.rawTrailers` - + * string\[] The raw request/response trailer keys and values exactly as they were received. Only populated at the `'end'` event. -#### `message.setTimeout(msecs[, callback])` +#### `message.setTimeout(msecs[, callback])` - + * `msecs` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) * `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) @@ -2076,9 +2076,9 @@ received. Only populated at the `'end'` event. Calls `message.socket.setTimeout(msecs, callback)`. -#### `message.socket` +#### `message.socket` - + * [`stream.Duplex`](/api/stream#streamduplex) @@ -2091,9 +2091,9 @@ This property is guaranteed to be an instance of the [`net.Socket`](/api/net#net a subclass of [`stream.Duplex`](/api/stream#streamduplex), unless the user specified a socket type other than [`net.Socket`](/api/net#netsocket) or internally nulled. -#### `message.statusCode` +#### `message.statusCode` - + * [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) @@ -2101,9 +2101,9 @@ type other than [`net.Socket`](/api/net#netsocket) or internally nulled. The 3-digit HTTP response status code. E.G. `404`. -#### `message.statusMessage` +#### `message.statusMessage` - + * [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) @@ -2112,17 +2112,17 @@ The 3-digit HTTP response status code. E.G. `404`. The HTTP response status message (reason phrase). E.G. `OK` or `Internal Server Error`. -#### `message.trailers` +#### `message.trailers` - + * [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) The request/response trailers object. Only populated at the `'end'` event. -#### `message.trailersDistinct` +#### `message.trailersDistinct` - + * [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) @@ -2130,9 +2130,9 @@ Similar to [`message.trailers`][], but there is no join logic and the values are always arrays of strings, even for headers received just once. Only populated at the `'end'` event. -#### `message.url` +#### `message.url` - + * [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) @@ -2174,9 +2174,9 @@ URL { } ``` -### `http.OutgoingMessage` +### `http.OutgoingMessage` - + * Extends: [`Stream`](/api/stream#stream) @@ -2184,29 +2184,29 @@ This class serves as the parent class of [`http.ClientRequest`][] and [`http.ServerResponse`][]. It is an abstract outgoing message from the perspective of the participants of an HTTP transaction. -#### `'drain'` +#### `'drain'` - + Emitted when the buffer of the message is free again. -#### `'finish'` +#### `'finish'` - + Emitted when the transmission is finished successfully. -#### `'prefinish'` +#### `'prefinish'` - + Emitted after `outgoingMessage.end()` is called. When the event is emitted, all data has been processed but not necessarily completely flushed. -#### `outgoingMessage.addTrailers(headers)` +#### `outgoingMessage.addTrailers(headers)` - + * `headers` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) @@ -2229,9 +2229,9 @@ message.end(); Attempting to set a header field name or value that contains invalid characters will result in a `TypeError` being thrown. -#### `outgoingMessage.appendHeader(name, value)` +#### `outgoingMessage.appendHeader(name, value)` - + * `name` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) Header name * `value` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) Header value @@ -2249,23 +2249,23 @@ Depending of the value of `options.uniqueHeaders` when the client request or the server were created, this will end up in the header being sent multiple times or a single time with values joined using `; `. -#### `outgoingMessage.connection` +#### `outgoingMessage.connection` - + - + Alias of [`outgoingMessage.socket`][]. -#### `outgoingMessage.cork()` +#### `outgoingMessage.cork()` - + See [`writable.cork()`][]. -#### `outgoingMessage.destroy([error])` +#### `outgoingMessage.destroy([error])` - + * `error` [`Error`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error) Optional, an error to emit with `error` event * Returns: [`this`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this) @@ -2273,11 +2273,11 @@ See [`writable.cork()`][]. Destroys the message. Once a socket is associated with the message and is connected, that socket will be destroyed as well. -#### `outgoingMessage.end(chunk[, encoding][, callback])` +#### `outgoingMessage.end(chunk[, encoding][, callback])` - + -* `chunk` {string | Buffer} +* `chunk` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) * `encoding` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) Optional, **Default**: `utf8` * `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) Optional * Returns: [`this`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this) @@ -2293,9 +2293,9 @@ If `chunk` is specified, it is equivalent to calling If `callback` is provided, it will be called when the message is finished (equivalent to a listener of the `'finish'` event). -#### `outgoingMessage.flushHeaders()` +#### `outgoingMessage.flushHeaders()` - + Flushes the message headers. @@ -2308,28 +2308,28 @@ It is usually desired (it saves a TCP round-trip), but not when the first data is not sent until possibly much later. `outgoingMessage.flushHeaders()` bypasses the optimization and kickstarts the message. -#### `outgoingMessage.getHeader(name)` +#### `outgoingMessage.getHeader(name)` - + * `name` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) Name of header -* Returns {string | undefined} +* Returns [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`undefined`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type) Gets the value of the HTTP header with the given name. If that header is not set, the returned value will be `undefined`. -#### `outgoingMessage.getHeaderNames()` +#### `outgoingMessage.getHeaderNames()` - + * Returns string\[] Returns an array containing the unique names of the current outgoing headers. All names are lowercase. -#### `outgoingMessage.getHeaders()` +#### `outgoingMessage.getHeaders()` - + * Returns: [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) @@ -2352,9 +2352,9 @@ const headers = outgoingMessage.getHeaders(); // headers === { foo: 'bar', 'set-cookie': ['foo=bar', 'bar=baz'] } ``` -#### `outgoingMessage.hasHeader(name)` +#### `outgoingMessage.hasHeader(name)` - + * `name` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) * Returns [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) @@ -2366,17 +2366,17 @@ outgoing headers. The header name is case-insensitive. const hasContentType = outgoingMessage.hasHeader('content-type'); ``` -#### `outgoingMessage.headersSent` +#### `outgoingMessage.headersSent` - + * [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) Read-only. `true` if the headers were sent, otherwise `false`. -#### `outgoingMessage.pipe()` +#### `outgoingMessage.pipe()` - + Overrides the `stream.pipe()` method inherited from the legacy `Stream` class which is the parent class of `http.OutgoingMessage`. @@ -2384,9 +2384,9 @@ which is the parent class of `http.OutgoingMessage`. Calling this method will throw an `Error` because `outgoingMessage` is a write-only stream. -#### `outgoingMessage.removeHeader(name)` +#### `outgoingMessage.removeHeader(name)` - + * `name` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) Header name @@ -2396,9 +2396,9 @@ Removes a header that is queued for implicit sending. outgoingMessage.removeHeader('Content-Encoding'); ``` -#### `outgoingMessage.setHeader(name, value)` +#### `outgoingMessage.setHeader(name, value)` - + * `name` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) Header name * `value` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) Header value @@ -2408,9 +2408,9 @@ Sets a single header value. If the header already exists in the to-be-sent headers, its value will be replaced. Use an array of strings to send multiple headers with the same name. -#### `outgoingMessage.setTimeout(msesc[, callback])` +#### `outgoingMessage.setTimeout(msesc[, callback])` - + * `msesc` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) * `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) Optional function to be called when a timeout @@ -2420,9 +2420,9 @@ headers with the same name. Once a socket is associated with the message and is connected, [`socket.setTimeout()`][] will be called with `msecs` as the first parameter. -#### `outgoingMessage.socket` +#### `outgoingMessage.socket` - + * [`stream.Duplex`](/api/stream#streamduplex) @@ -2431,23 +2431,23 @@ this property. After calling `outgoingMessage.end()`, this property will be nulled. -#### `outgoingMessage.uncork()` +#### `outgoingMessage.uncork()` - + See [`writable.uncork()`][] -#### `outgoingMessage.writableCorked` +#### `outgoingMessage.writableCorked` - + * [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The number of times `outgoingMessage.cork()` has been called. -#### `outgoingMessage.writableEnded` +#### `outgoingMessage.writableEnded` - + * [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) @@ -2455,44 +2455,44 @@ Is `true` if `outgoingMessage.end()` has been called. This property does not indicate whether the data has been flushed. For that purpose, use `message.writableFinished` instead. -#### `outgoingMessage.writableFinished` +#### `outgoingMessage.writableFinished` - + * [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) Is `true` if all data has been flushed to the underlying system. -#### `outgoingMessage.writableHighWaterMark` +#### `outgoingMessage.writableHighWaterMark` - + * [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The `highWaterMark` of the underlying socket if assigned. Otherwise, the default buffer level when [`writable.write()`][] starts returning false (`16384`). -#### `outgoingMessage.writableLength` +#### `outgoingMessage.writableLength` - + * [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The number of buffered bytes. -#### `outgoingMessage.writableObjectMode` +#### `outgoingMessage.writableObjectMode` - + * [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) Always `false`. -#### `outgoingMessage.write(chunk[, encoding][, callback])` +#### `outgoingMessage.write(chunk[, encoding][, callback])` - + -* `chunk` {string | Buffer} +* `chunk` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) * `encoding` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) **Default**: `utf8` * `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) * Returns [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) @@ -2509,17 +2509,17 @@ Returns `true` if the entire data was flushed successfully to the kernel buffer. Returns `false` if all or part of the data was queued in the user memory. The `'drain'` event will be emitted when the buffer is free again. -### `http.METHODS` +### `http.METHODS` - + * string\[] A list of the HTTP methods that are supported by the parser. -### `http.STATUS_CODES` +### `http.STATUS_CODES` - + * [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) @@ -2527,9 +2527,9 @@ A collection of all the standard HTTP response status codes, and the short description of each. For example, `http.STATUS_CODES[404] === 'Not Found'`. -### `http.createServer([options][, requestListener])` +### `http.createServer([options][, requestListener])` - + * `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) * `IncomingMessage` [`http.IncomingMessage`](/api/http#httpincomingmessage) Specifies the `IncomingMessage` @@ -2616,13 +2616,13 @@ server.on('request', (request, res) => { server.listen(8000); ``` -### `http.get(options[, callback])` +### `http.get(options[, callback])` -### `http.get(url[, options][, callback])` +### `http.get(url[, options][, callback])` - + -* `url` {string | URL} +* `url` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`URL`](/api/url#the-whatwg-url-api) * `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) Accepts the same `options` as [`http.request()`][], with the `method` always set to `GET`. Properties that are inherited from the prototype are ignored. @@ -2650,10 +2650,10 @@ http.get('http://localhost:8000/', (res) => { // here we're only checking for 200. if (statusCode !== 200) { error = new Error('Request Failed.\n' + - `Status Code: $statusCode`); + `Status Code: ${statusCode}`); } else if (!/^application\/json/.test(contentType)) { error = new Error('Invalid content-type.\n' + - `Expected application/json but received $contentType`); + `Expected application/json but received ${contentType}`); } if (error) { console.error(error.message); @@ -2674,7 +2674,7 @@ http.get('http://localhost:8000/', (res) => { } }); }).on('error', (e) => { - console.error(`Got error: $e.message`); + console.error(`Got error: ${e.message}`); }); // Create a local server to receive data from @@ -2688,18 +2688,18 @@ const server = http.createServer((req, res) => { server.listen(8000); ``` -### `http.globalAgent` +### `http.globalAgent` - + * [`http.Agent`](/api/http#httpagent) Global instance of `Agent` which is used as the default for all HTTP client requests. -### `http.maxHeaderSize` +### `http.maxHeaderSize` - + * [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) @@ -2710,15 +2710,15 @@ option. This can be overridden for servers and client requests by passing the `maxHeaderSize` option. -### `http.request(options[, callback])` +### `http.request(options[, callback])` -### `http.request(url[, options][, callback])` +### `http.request(url[, options][, callback])` - + -* `url` {string | URL} +* `url` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`URL`](/api/url#the-whatwg-url-api) * `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) - * `agent` {http.Agent | boolean} Controls [`Agent`][] behavior. Possible + * `agent` [`http.Agent`](/api/http#httpagent) | [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) Controls [`Agent`][] behavior. Possible values: * `undefined` (default): use [`http.globalAgent`][] for this host and port. * `Agent` object: explicitly use the passed in `Agent`. @@ -2813,11 +2813,11 @@ const options = { }; const req = http.request(options, (res) => { - console.log(`STATUS: $res.statusCode`); + console.log(`STATUS: ${res.statusCode}`); console.log(`HEADERS: ${JSON.stringify(res.headers)}`); res.setEncoding('utf8'); res.on('data', (chunk) => { - console.log(`BODY: $chunk`); + console.log(`BODY: ${chunk}`); }); res.on('end', () => { console.log('No more data in response.'); @@ -2825,7 +2825,7 @@ const req = http.request(options, (res) => { }); req.on('error', (e) => { - console.error(`problem with request: $e.message`); + console.error(`problem with request: ${e.message}`); }); // Write data to request body @@ -2973,9 +2973,9 @@ Passing an `AbortSignal` and then calling `abort` on the corresponding `AbortController` will behave the same way as calling `.destroy()` on the request itself. -### `http.validateHeaderName(name)` +### `http.validateHeaderName(name)` - + * `name` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) @@ -3003,9 +3003,9 @@ try { } ``` -### `http.validateHeaderValue(name, value)` +### `http.validateHeaderValue(name, value)` - + * `name` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) * `value` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) @@ -3043,9 +3043,9 @@ try { } ``` -### `http.setMaxIdleHTTPParsers` +### `http.setMaxIdleHTTPParsers` - + * [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) diff --git a/content/api/v18/http2.en.md b/content/api/v18/http2.en.md index 4af3c07cef..e35ed500df 100644 --- a/content/api/v18/http2.en.md +++ b/content/api/v18/http2.en.md @@ -2,17 +2,17 @@ title: 'http2' displayTitle: 'HTTP/2' category: 'api' -editPage: 'https://github.com/nodejs/node/blob/v18.8.0/doc/api/http2.md' +editPage: 'https://github.com/nodejs/node/blob/v18.9.0/doc/api/http2.md' version: 'v18' --- - + - + - + - + The `node:http2` module provides an implementation of the [HTTP/2][] protocol. It can be accessed using: @@ -120,7 +120,7 @@ const req = client.request({ ':path': '/' }); req.on('response', (headers, flags) => { for (const name in headers) { - console.log(`$name: $headers[name]`); + console.log(`${name}: ${headers[name]}`); } }); @@ -128,15 +128,15 @@ req.setEncoding('utf8'); let data = ''; req.on('data', (chunk) => { data += chunk; }); req.on('end', () => { - console.log(`\n$data`); + console.log(`\n${data}`); client.close(); }); req.end(); ``` -#### `Http2Session` +#### `Http2Session` - + * Extends: [`EventEmitter`](/api/events#eventemitter) @@ -157,7 +157,7 @@ User code will not create `Http2Session` instances directly. Server-side new HTTP/2 connection is received. Client-side `Http2Session` instances are created using the `http2.connect()` method. -##### `Http2Session` and sockets +##### `Http2Session` and sockets Every `Http2Session` instance is associated with exactly one [`net.Socket`][] or [`tls.TLSSocket`][] when it is created. When either the `Socket` or the @@ -172,18 +172,18 @@ the socket to become unusable. Once a `Socket` has been bound to an `Http2Session`, user code should rely solely on the API of the `Http2Session`. -##### `'close'` +##### `'close'` - + The `'close'` event is emitted once the `Http2Session` has been destroyed. Its listener does not expect any arguments. -##### `'connect'` +##### `'connect'` - + -* `session` {Http2Session} +* `session` [`Http2Session`](/api/http2#http2session) * `socket` [`net.Socket`](/api/net#netsocket) The `'connect'` event is emitted once the `Http2Session` has been successfully @@ -191,18 +191,18 @@ connected to the remote peer and communication may begin. User code will typically not listen for this event directly. -##### `'error'` +##### `'error'` - + * `error` [`Error`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error) The `'error'` event is emitted when an error occurs during the processing of an `Http2Session`. -##### `'frameError'` +##### `'frameError'` - + * `type` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The frame type. * `code` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The error code. @@ -219,9 +219,9 @@ closed and destroyed immediately following the `'frameError'` event. If the event is not associated with a stream, the `Http2Session` will be shut down immediately following the `'frameError'` event. -##### `'goaway'` +##### `'goaway'` - + * `errorCode` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The HTTP/2 error code specified in the `GOAWAY` frame. * `lastStreamID` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The ID of the last stream the remote peer successfully @@ -234,11 +234,11 @@ The `'goaway'` event is emitted when a `GOAWAY` frame is received. The `Http2Session` instance will be shut down automatically when the `'goaway'` event is emitted. -##### `'localSettings'` +##### `'localSettings'` - + -* `settings` {HTTP/2 Settings Object} A copy of the `SETTINGS` frame received. +* `settings` ```{HTTP/2 Settings Object}``` A copy of the `SETTINGS` frame received. The `'localSettings'` event is emitted when an acknowledgment `SETTINGS` frame has been received. @@ -254,20 +254,20 @@ session.on('localSettings', (settings) => { }); ``` -##### `'ping'` +##### `'ping'` - + * `payload` [`Buffer`](/api/buffer#buffer) The `PING` frame 8-byte payload The `'ping'` event is emitted whenever a `PING` frame is received from the connected peer. -##### `'remoteSettings'` +##### `'remoteSettings'` - + -* `settings` {HTTP/2 Settings Object} A copy of the `SETTINGS` frame received. +* `settings` ```{HTTP/2 Settings Object}``` A copy of the `SETTINGS` frame received. The `'remoteSettings'` event is emitted when a new `SETTINGS` frame is received from the connected peer. @@ -278,12 +278,12 @@ session.on('remoteSettings', (settings) => { }); ``` -##### `'stream'` +##### `'stream'` - + -* `stream` {Http2Stream} A reference to the stream -* `headers` {HTTP/2 Headers Object} An object describing the headers +* `stream` [`Http2Stream`](/api/http2#http2stream) A reference to the stream +* `headers` ```{HTTP/2 Headers Object}``` An object describing the headers * `flags` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The associated numeric flags * `rawHeaders` [`Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array) An array containing the raw header names followed by their respective values. @@ -332,9 +332,9 @@ Even though HTTP/2 streams and network sockets are not in a 1:1 correspondence, a network error will destroy each individual stream and must be handled on the stream level, as shown above. -##### `'timeout'` +##### `'timeout'` - + After the `http2session.setTimeout()` method is used to set the timeout period for this `Http2Session`, the `'timeout'` event is emitted if there is no @@ -346,9 +346,9 @@ session.setTimeout(2000); session.on('timeout', () => { /* .. */ }); ``` -##### `http2session.alpnProtocol` +##### `http2session.alpnProtocol` - + * [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`undefined`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type) @@ -357,9 +357,9 @@ socket, `h2c` if the `Http2Session` is not connected to a `TLSSocket`, or will return the value of the connected `TLSSocket`'s own `alpnProtocol` property. -##### `http2session.close([callback])` +##### `http2session.close([callback])` - + * `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) @@ -371,18 +371,18 @@ are no open `Http2Stream` instances. If specified, the `callback` function is registered as a handler for the `'close'` event. -##### `http2session.closed` +##### `http2session.closed` - + * [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) Will be `true` if this `Http2Session` instance has been closed, otherwise `false`. -##### `http2session.connecting` +##### `http2session.connecting` - + * [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) @@ -390,9 +390,9 @@ Will be `true` if this `Http2Session` instance is still connecting, will be set to `false` before emitting `connect` event and/or calling the `http2.connect` callback. -##### `http2session.destroy([error][, code])` +##### `http2session.destroy([error][, code])` - + * `error` [`Error`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error) An `Error` object if the `Http2Session` is being destroyed due to an error. @@ -410,18 +410,18 @@ is not undefined, an `'error'` event will be emitted immediately before the If there are any remaining open `Http2Streams` associated with the `Http2Session`, those will also be destroyed. -##### `http2session.destroyed` +##### `http2session.destroyed` - + * [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) Will be `true` if this `Http2Session` instance has been destroyed and must no longer be used, otherwise `false`. -##### `http2session.encrypted` +##### `http2session.encrypted` - + * [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) | [`undefined`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type) @@ -430,9 +430,9 @@ connected, `true` if the `Http2Session` is connected with a `TLSSocket`, and `false` if the `Http2Session` is connected to any other kind of socket or stream. -##### `http2session.goaway([code[, lastStreamID[, opaqueData]]])` +##### `http2session.goaway([code[, lastStreamID[, opaqueData]]])` - + * `code` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) An HTTP/2 error code * `lastStreamID` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The numeric ID of the last processed `Http2Stream` @@ -442,18 +442,18 @@ or stream. Transmits a `GOAWAY` frame to the connected peer _without_ shutting down the `Http2Session`. -##### `http2session.localSettings` +##### `http2session.localSettings` - + -* {HTTP/2 Settings Object} +* ```{HTTP/2 Settings Object}``` A prototype-less object describing the current local settings of this `Http2Session`. The local settings are local to _this_ `Http2Session` instance. -##### `http2session.originSet` +##### `http2session.originSet` - + * [`undefined`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type) @@ -463,9 +463,9 @@ considered authoritative. The `originSet` property is only available when using a secure TLS connection. -##### `http2session.pendingSettingsAck` +##### `http2session.pendingSettingsAck` - + * [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) @@ -474,9 +474,9 @@ a sent `SETTINGS` frame. Will be `true` after calling the `http2session.settings()` method. Will be `false` once all sent `SETTINGS` frames have been acknowledged. -##### `http2session.ping([payload, ]callback)` +##### `http2session.ping([payload, ]callback)` - + * `payload` [`Buffer`](/api/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) Optional ping payload. * `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) @@ -502,7 +502,7 @@ payload. ```js session.ping(Buffer.from('abcdefgh'), (err, duration, payload) => { if (!err) { - console.log(`Ping acknowledged in $duration milliseconds`); + console.log(`Ping acknowledged in ${duration} milliseconds`); console.log(`With payload '${payload.toString()}'`); } }); @@ -511,25 +511,25 @@ session.ping(Buffer.from('abcdefgh'), (err, duration, payload) => { If the `payload` argument is not specified, the default payload will be the 64-bit timestamp (little endian) marking the start of the `PING` duration. -##### `http2session.ref()` +##### `http2session.ref()` - + Calls [`ref()`][`net.Socket.prototype.ref()`] on this `Http2Session` instance's underlying [`net.Socket`][]. -##### `http2session.remoteSettings` +##### `http2session.remoteSettings` - + -* {HTTP/2 Settings Object} +* ```{HTTP/2 Settings Object}``` A prototype-less object describing the current remote settings of this `Http2Session`. The remote settings are set by the _connected_ HTTP/2 peer. -##### `http2session.setLocalWindowSize(windowSize)` +##### `http2session.setLocalWindowSize(windowSize)` - + * `windowSize` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) @@ -549,9 +549,9 @@ server.on('connect', (session) => { }); ``` -##### `http2session.setTimeout(msecs, callback)` +##### `http2session.setTimeout(msecs, callback)` - + * `msecs` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) * `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) @@ -560,9 +560,9 @@ Used to set a callback function that is called when there is no activity on the `Http2Session` after `msecs` milliseconds. The given `callback` is registered as a listener on the `'timeout'` event. -##### `http2session.socket` +##### `http2session.socket` - + * [`net.Socket`](/api/net#netsocket) | [`tls.TLSSocket`](/api/tls#tlstlssocket) @@ -577,9 +577,9 @@ an error with code `ERR_HTTP2_NO_SOCKET_MANIPULATION`. See All other interactions will be routed directly to the socket. -##### `http2session.state` +##### `http2session.state` - + Provides miscellaneous information about the current state of the `Http2Session`. @@ -606,15 +606,15 @@ Provides miscellaneous information about the current state of the An object describing the current status of this `Http2Session`. -##### `http2session.settings([settings][, callback])` +##### `http2session.settings([settings][, callback])` - + -* `settings` {HTTP/2 Settings Object} +* `settings` ```{HTTP/2 Settings Object}``` * `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) Callback that is called once the session is connected or right away if the session is already connected. * `err` [`Error`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error) | [`null`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type) - * `settings` {HTTP/2 Settings Object} The updated `settings` object. + * `settings` ```{HTTP/2 Settings Object}``` The updated `settings` object. * `duration` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Updates the current local settings for this `Http2Session` and sends a new @@ -628,9 +628,9 @@ The new settings will not become effective until the `SETTINGS` acknowledgment is received and the `'localSettings'` event is emitted. It is possible to send multiple `SETTINGS` frames while acknowledgment is still pending. -##### `http2session.type` +##### `http2session.type` - + * [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) @@ -639,22 +639,22 @@ The `http2session.type` will be equal to server, and `http2.constants.NGHTTP2_SESSION_CLIENT` if the instance is a client. -##### `http2session.unref()` +##### `http2session.unref()` - + Calls [`unref()`][`net.Socket.prototype.unref()`] on this `Http2Session` instance's underlying [`net.Socket`][]. -#### `ServerHttp2Session` +#### `ServerHttp2Session` - + -* Extends: {Http2Session} +* Extends: [`Http2Session`](/api/http2#http2session) -##### `serverhttp2session.altsvc(alt, originOrStream)` +##### `serverhttp2session.altsvc(alt, originOrStream)` - + * `alt` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) A description of the alternative service configuration as defined by [RFC 7838][]. @@ -718,11 +718,11 @@ The protocol identifier (`'h2'` in the examples) may be any valid The syntax of these values is not validated by the Node.js implementation and are passed through as provided by the user or received from the peer. -##### `serverhttp2session.origin(...origins)` +##### `serverhttp2session.origin(...origins)` - + -* `origins` { string | URL | Object } One or more URL Strings passed as +* `origins` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`URL`](/api/url#the-whatwg-url-api) | [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) One or more URL Strings passed as separate arguments. Submits an `ORIGIN` frame (as defined by [RFC 8336][]) to the connected client @@ -767,15 +767,15 @@ server.on('stream', (stream) => { }); ``` -#### `ClientHttp2Session` +#### `ClientHttp2Session` - + -* Extends: {Http2Session} +* Extends: [`Http2Session`](/api/http2#http2session) -##### `'altsvc'` +##### `'altsvc'` - + * `alt` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) * `origin` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) @@ -797,9 +797,9 @@ client.on('altsvc', (alt, origin, streamId) => { }); ``` -##### `'origin'` +##### `'origin'` - + * `origins` string\[] @@ -820,11 +820,11 @@ client.on('origin', (origins) => { The `'origin'` event is only emitted when using a secure TLS connection. -##### `clienthttp2session.request(headers[, options])` +##### `clienthttp2session.request(headers[, options])` - + -* `headers` {HTTP/2 Headers Object} +* `headers` ```{HTTP/2 Headers Object}``` * `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) * `endStream` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) `true` if the `Http2Stream` _writable_ side should @@ -844,7 +844,7 @@ The `'origin'` event is only emitted when using a secure TLS connection. * `signal` [`AbortSignal`](/api/globals#abortsignal) An AbortSignal that may be used to abort an ongoing request. -* Returns: {ClientHttp2Stream} +* Returns: [`ClientHttp2Stream`](/api/http2#clienthttp2stream) For HTTP/2 Client `Http2Session` instances only, the `http2session.request()` creates and returns an `Http2Stream` instance that can be used to send an @@ -895,9 +895,9 @@ they respectively default to: * `:method` = `'GET'` * `:path` = `/` -#### `Http2Stream` +#### `Http2Stream` - + * Extends: [`stream.Duplex`](/api/stream#streamduplex) @@ -933,7 +933,7 @@ stream.respond({ }); ``` -##### `Http2Stream` Lifecycle +##### `Http2Stream` Lifecycle ###### Creation @@ -978,9 +978,9 @@ property will be `true` and the `http2stream.rstCode` property will specify the `RST_STREAM` error code. The `Http2Stream` instance is no longer usable once destroyed. -##### `'aborted'` +##### `'aborted'` - + The `'aborted'` event is emitted whenever a `Http2Stream` instance is abnormally aborted in mid-communication. @@ -989,9 +989,9 @@ Its listener does not expect any arguments. The `'aborted'` event will only be emitted if the `Http2Stream` writable side has not been ended. -##### `'close'` +##### `'close'` - + The `'close'` event is emitted when the `Http2Stream` is destroyed. Once this event is emitted, the `Http2Stream` instance is no longer usable. @@ -1000,18 +1000,18 @@ The HTTP/2 error code used when closing the stream can be retrieved using the `http2stream.rstCode` property. If the code is any value other than `NGHTTP2_NO_ERROR` (`0`), an `'error'` event will have also been emitted. -##### `'error'` +##### `'error'` - + * `error` [`Error`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error) The `'error'` event is emitted when an error occurs during the processing of an `Http2Stream`. -##### `'frameError'` +##### `'frameError'` - + * `type` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The frame type. * `code` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The error code. @@ -1024,28 +1024,28 @@ argument identifying the frame type, and an integer argument identifying the error code. The `Http2Stream` instance will be destroyed immediately after the `'frameError'` event is emitted. -##### `'ready'` +##### `'ready'` - + The `'ready'` event is emitted when the `Http2Stream` has been opened, has been assigned an `id`, and can be used. The listener does not expect any arguments. -##### `'timeout'` +##### `'timeout'` - + The `'timeout'` event is emitted after no activity is received for this `Http2Stream` within the number of milliseconds set using `http2stream.setTimeout()`. Its listener does not expect any arguments. -##### `'trailers'` +##### `'trailers'` - + -* `headers` {HTTP/2 Headers Object} An object describing the headers +* `headers` ```{HTTP/2 Headers Object}``` An object describing the headers * `flags` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The associated numeric flags The `'trailers'` event is emitted when a block of headers associated with @@ -1062,36 +1062,36 @@ stream.on('trailers', (headers, flags) => { }); ``` -##### `'wantTrailers'` +##### `'wantTrailers'` - + The `'wantTrailers'` event is emitted when the `Http2Stream` has queued the final `DATA` frame to be sent on a frame and the `Http2Stream` is ready to send trailing headers. When initiating a request or response, the `waitForTrailers` option must be set for this event to be emitted. -##### `http2stream.aborted` +##### `http2stream.aborted` - + * [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) Set to `true` if the `Http2Stream` instance was aborted abnormally. When set, the `'aborted'` event will have been emitted. -##### `http2stream.bufferSize` +##### `http2stream.bufferSize` - + * [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) This property shows the number of characters currently buffered to be written. See [`net.Socket.bufferSize`][] for details. -##### `http2stream.close(code[, callback])` +##### `http2stream.close(code[, callback])` - + * `code` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Unsigned 32-bit integer identifying the error code. **Default:** `http2.constants.NGHTTP2_NO_ERROR` (`0x00`). @@ -1101,26 +1101,26 @@ See [`net.Socket.bufferSize`][] for details. Closes the `Http2Stream` instance by sending an `RST_STREAM` frame to the connected HTTP/2 peer. -##### `http2stream.closed` +##### `http2stream.closed` - + * [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) Set to `true` if the `Http2Stream` instance has been closed. -##### `http2stream.destroyed` +##### `http2stream.destroyed` - + * [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) Set to `true` if the `Http2Stream` instance has been destroyed and is no longer usable. -##### `http2stream.endAfterHeaders` +##### `http2stream.endAfterHeaders` - + * [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) @@ -1128,27 +1128,27 @@ Set to `true` if the `END_STREAM` flag was set in the request or response HEADERS frame received, indicating that no additional data should be received and the readable side of the `Http2Stream` will be closed. -##### `http2stream.id` +##### `http2stream.id` - + * [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) | [`undefined`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type) The numeric stream identifier of this `Http2Stream` instance. Set to `undefined` if the stream identifier has not yet been assigned. -##### `http2stream.pending` +##### `http2stream.pending` - + * [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) Set to `true` if the `Http2Stream` instance has not yet been assigned a numeric stream identifier. -##### `http2stream.priority(options)` +##### `http2stream.priority(options)` - + * `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) * `exclusive` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) When `true` and `parent` identifies a parent Stream, @@ -1165,9 +1165,9 @@ numeric stream identifier. Updates the priority for this `Http2Stream` instance. -##### `http2stream.rstCode` +##### `http2stream.rstCode` - + * [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) @@ -1176,43 +1176,43 @@ destroyed after either receiving an `RST_STREAM` frame from the connected peer, calling `http2stream.close()`, or `http2stream.destroy()`. Will be `undefined` if the `Http2Stream` has not been closed. -##### `http2stream.sentHeaders` +##### `http2stream.sentHeaders` - + -* {HTTP/2 Headers Object} +* ```{HTTP/2 Headers Object}``` An object containing the outbound headers sent for this `Http2Stream`. -##### `http2stream.sentInfoHeaders` +##### `http2stream.sentInfoHeaders` - + -* {HTTP/2 Headers Object\[]} +* ```{HTTP/2 Headers Object\[]}``` An array of objects containing the outbound informational (additional) headers sent for this `Http2Stream`. -##### `http2stream.sentTrailers` +##### `http2stream.sentTrailers` - + -* {HTTP/2 Headers Object} +* ```{HTTP/2 Headers Object}``` An object containing the outbound trailers sent for this `HttpStream`. -##### `http2stream.session` +##### `http2stream.session` - + -* {Http2Session} +* [`Http2Session`](/api/http2#http2session) A reference to the `Http2Session` instance that owns this `Http2Stream`. The value will be `undefined` after the `Http2Stream` instance is destroyed. -##### `http2stream.setTimeout(msecs, callback)` +##### `http2stream.setTimeout(msecs, callback)` - + * `msecs` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) * `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) @@ -1227,9 +1227,9 @@ const req = client.request({ ':path': '/' }); req.setTimeout(5000, () => req.close(NGHTTP2_CANCEL)); ``` -##### `http2stream.state` +##### `http2stream.state` - + Provides miscellaneous information about the current state of the `Http2Stream`. @@ -1249,11 +1249,11 @@ Provides miscellaneous information about the current state of the A current state of this `Http2Stream`. -##### `http2stream.sendTrailers(headers)` +##### `http2stream.sendTrailers(headers)` - + -* `headers` {HTTP/2 Headers Object} +* `headers` ```{HTTP/2 Headers Object}``` Sends a trailing `HEADERS` frame to the connected HTTP/2 peer. This method will cause the `Http2Stream` to be immediately closed and must only be @@ -1277,30 +1277,30 @@ server.on('stream', (stream) => { The HTTP/1 specification forbids trailers from containing HTTP/2 pseudo-header fields (e.g. `':method'`, `':path'`, etc). -#### `ClientHttp2Stream` +#### `ClientHttp2Stream` - + -* Extends {Http2Stream} +* Extends [`Http2Stream`](/api/http2#http2stream) The `ClientHttp2Stream` class is an extension of `Http2Stream` that is used exclusively on HTTP/2 Clients. `Http2Stream` instances on the client provide events such as `'response'` and `'push'` that are only relevant on the client. -##### `'continue'` +##### `'continue'` - + Emitted when the server sends a `100 Continue` status, usually because the request contained `Expect: 100-continue`. This is an instruction that the client should send the request body. -##### `'headers'` +##### `'headers'` - + -* `headers` {HTTP/2 Headers Object} +* `headers` ```{HTTP/2 Headers Object}``` * `flags` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The `'headers'` event is emitted when an additional block of headers is received @@ -1314,11 +1314,11 @@ stream.on('headers', (headers, flags) => { }); ``` -##### `'push'` +##### `'push'` - + -* `headers` {HTTP/2 Headers Object} +* `headers` ```{HTTP/2 Headers Object}``` * `flags` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The `'push'` event is emitted when response headers for a Server Push stream @@ -1331,11 +1331,11 @@ stream.on('push', (headers, flags) => { }); ``` -##### `'response'` +##### `'response'` - + -* `headers` {HTTP/2 Headers Object} +* `headers` ```{HTTP/2 Headers Object}``` * `flags` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The `'response'` event is emitted when a response `HEADERS` frame has been @@ -1352,36 +1352,36 @@ req.on('response', (headers, flags) => { }); ``` -#### `ServerHttp2Stream` +#### `ServerHttp2Stream` - + -* Extends: {Http2Stream} +* Extends: [`Http2Stream`](/api/http2#http2stream) The `ServerHttp2Stream` class is an extension of [`Http2Stream`][] that is used exclusively on HTTP/2 Servers. `Http2Stream` instances on the server provide additional methods such as `http2stream.pushStream()` and `http2stream.respond()` that are only relevant on the server. -##### `http2stream.additionalHeaders(headers)` +##### `http2stream.additionalHeaders(headers)` - + -* `headers` {HTTP/2 Headers Object} +* `headers` ```{HTTP/2 Headers Object}``` Sends an additional informational `HEADERS` frame to the connected HTTP/2 peer. -##### `http2stream.headersSent` +##### `http2stream.headersSent` - + * [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) True if headers were sent, false otherwise (read-only). -##### `http2stream.pushAllowed` +##### `http2stream.pushAllowed` - + * [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) @@ -1390,11 +1390,11 @@ client's most recent `SETTINGS` frame. Will be `true` if the remote peer accepts push streams, `false` otherwise. Settings are the same for every `Http2Stream` in the same `Http2Session`. -##### `http2stream.pushStream(headers[, options], callback)` +##### `http2stream.pushStream(headers[, options], callback)` - + -* `headers` {HTTP/2 Headers Object} +* `headers` ```{HTTP/2 Headers Object}``` * `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) * `exclusive` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) When `true` and `parent` identifies a parent Stream, the created stream is made the sole direct dependency of the parent, with @@ -1405,8 +1405,8 @@ accepts push streams, `false` otherwise. Settings are the same for every * `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) Callback that is called once the push stream has been initiated. * `err` [`Error`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error) - * `pushStream` {ServerHttp2Stream} The returned `pushStream` object. - * `headers` {HTTP/2 Headers Object} Headers object the `pushStream` was + * `pushStream` [`ServerHttp2Stream`](/api/http2#serverhttp2stream) The returned `pushStream` object. + * `headers` ```{HTTP/2 Headers Object}``` Headers object the `pushStream` was initiated with. Initiates a push stream. The callback is invoked with the new `Http2Stream` @@ -1434,11 +1434,11 @@ a `weight` value to `http2stream.priority` with the `silent` option set to Calling `http2stream.pushStream()` from within a pushed stream is not permitted and will throw an error. -##### `http2stream.respond([headers[, options]])` +##### `http2stream.respond([headers[, options]])` - + -* `headers` {HTTP/2 Headers Object} +* `headers` ```{HTTP/2 Headers Object}``` * `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) * `endStream` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) Set to `true` to indicate that the response will not include payload data. @@ -1476,12 +1476,12 @@ server.on('stream', (stream) => { }); ``` -##### `http2stream.respondWithFD(fd[, headers[, options]])` +##### `http2stream.respondWithFD(fd[, headers[, options]])` - + * `fd` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) | [`FileHandle`](/api/fs#filehandle) A readable file descriptor. -* `headers` {HTTP/2 Headers Object} +* `headers` ```{HTTP/2 Headers Object}``` * `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) * `statCheck` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) * `waitForTrailers` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) When `true`, the `Http2Stream` will emit the @@ -1565,12 +1565,12 @@ server.on('stream', (stream) => { }); ``` -##### `http2stream.respondWithFile(path[, headers[, options]])` +##### `http2stream.respondWithFile(path[, headers[, options]])` - + * `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api) -* `headers` {HTTP/2 Headers Object} +* `headers` ```{HTTP/2 Headers Object}``` * `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) * `statCheck` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) * `onError` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) Callback function invoked in the case of an @@ -1680,9 +1680,9 @@ server.on('stream', (stream) => { }); ``` -#### `Http2Server` +#### `Http2Server` - + * Extends: [`net.Server`](/api/net#netserver) @@ -1690,12 +1690,12 @@ Instances of `Http2Server` are created using the `http2.createServer()` function. The `Http2Server` class is not exported directly by the `node:http2` module. -##### `'checkContinue'` +##### `'checkContinue'` - + -* `request` {http2.Http2ServerRequest} -* `response` {http2.Http2ServerResponse} +* `request` [`http2.Http2ServerRequest`](/api/http2#http2http2serverrequest) +* `response` [`http2.Http2ServerResponse`](/api/http2#http2http2serverresponse) If a [`'request'`][] listener is registered or [`http2.createServer()`][] is supplied a callback function, the `'checkContinue'` event is emitted each time @@ -1711,9 +1711,9 @@ the request body. When this event is emitted and handled, the [`'request'`][] event will not be emitted. -##### `'connection'` +##### `'connection'` - + * `socket` [`stream.Duplex`](/api/stream#streamduplex) @@ -1724,41 +1724,41 @@ access this event. This event can also be explicitly emitted by users to inject connections into the HTTP server. In that case, any [`Duplex`][] stream can be passed. -##### `'request'` +##### `'request'` - + -* `request` {http2.Http2ServerRequest} -* `response` {http2.Http2ServerResponse} +* `request` [`http2.Http2ServerRequest`](/api/http2#http2http2serverrequest) +* `response` [`http2.Http2ServerResponse`](/api/http2#http2http2serverresponse) Emitted each time there is a request. There may be multiple requests per session. See the [Compatibility API][]. -##### `'session'` +##### `'session'` - + -* `session` {ServerHttp2Session} +* `session` [`ServerHttp2Session`](/api/http2#serverhttp2session) The `'session'` event is emitted when a new `Http2Session` is created by the `Http2Server`. -##### `'sessionError'` +##### `'sessionError'` - + * `error` [`Error`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error) -* `session` {ServerHttp2Session} +* `session` [`ServerHttp2Session`](/api/http2#serverhttp2session) The `'sessionError'` event is emitted when an `'error'` event is emitted by an `Http2Session` object associated with the `Http2Server`. -##### `'stream'` +##### `'stream'` - + -* `stream` {Http2Stream} A reference to the stream -* `headers` {HTTP/2 Headers Object} An object describing the headers +* `stream` [`Http2Stream`](/api/http2#http2stream) A reference to the stream +* `headers` ```{HTTP/2 Headers Object}``` An object describing the headers * `flags` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The associated numeric flags * `rawHeaders` [`Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array) An array containing the raw header names followed by their respective values. @@ -1791,17 +1791,17 @@ server.on('stream', (stream, headers, flags) => { }); ``` -##### `'timeout'` +##### `'timeout'` - + The `'timeout'` event is emitted when there is no activity on the Server for a given number of milliseconds set using `http2server.setTimeout()`. **Default:** 0 (no timeout) -##### `server.close([callback])` +##### `server.close([callback])` - + * `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) @@ -1814,13 +1814,13 @@ If `callback` is provided, it is not invoked until all active sessions have been closed, although the server has already stopped allowing new sessions. See [`net.Server.close()`][] for more details. -##### `server.setTimeout([msecs][, callback])` +##### `server.setTimeout([msecs][, callback])` - + * `msecs` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) **Default:** 0 (no timeout) * `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) -* Returns: {Http2Server} +* Returns: [`Http2Server`](/api/http2#http2server) Used to set the timeout value for http2 server requests, and sets a callback function that is called when there is no activity @@ -1831,9 +1831,9 @@ The given callback is registered as a listener on the `'timeout'` event. In case if `callback` is not a function, a new `ERR_INVALID_ARG_TYPE` error will be thrown. -##### `server.timeout` +##### `server.timeout` - + * [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Timeout in milliseconds. **Default:** 0 (no timeout) @@ -1845,11 +1845,11 @@ A value of `0` will disable the timeout behavior on incoming connections. The socket timeout logic is set up on connection, so changing this value only affects new connections to the server, not any existing connections. -##### `server.updateSettings([settings])` +##### `server.updateSettings([settings])` - + -* `settings` {HTTP/2 Settings Object} +* `settings` ```{HTTP/2 Settings Object}``` Used to update the server with the provided settings. @@ -1857,9 +1857,9 @@ Throws `ERR_HTTP2_INVALID_SETTING_VALUE` for invalid `settings` values. Throws `ERR_INVALID_ARG_TYPE` for invalid `settings` argument. -#### `Http2SecureServer` +#### `Http2SecureServer` - + * Extends: [`tls.Server`](/api/tls#tlsserver) @@ -1867,12 +1867,12 @@ Instances of `Http2SecureServer` are created using the `http2.createSecureServer()` function. The `Http2SecureServer` class is not exported directly by the `node:http2` module. -##### `'checkContinue'` +##### `'checkContinue'` - + -* `request` {http2.Http2ServerRequest} -* `response` {http2.Http2ServerResponse} +* `request` [`http2.Http2ServerRequest`](/api/http2#http2http2serverrequest) +* `response` [`http2.Http2ServerResponse`](/api/http2#http2http2serverresponse) If a [`'request'`][] listener is registered or [`http2.createSecureServer()`][] is supplied a callback function, the `'checkContinue'` event is emitted each @@ -1888,9 +1888,9 @@ the request body. When this event is emitted and handled, the [`'request'`][] event will not be emitted. -##### `'connection'` +##### `'connection'` - + * `socket` [`stream.Duplex`](/api/stream#streamduplex) @@ -1901,41 +1901,41 @@ Usually users will not want to access this event. This event can also be explicitly emitted by users to inject connections into the HTTP server. In that case, any [`Duplex`][] stream can be passed. -##### `'request'` +##### `'request'` - + -* `request` {http2.Http2ServerRequest} -* `response` {http2.Http2ServerResponse} +* `request` [`http2.Http2ServerRequest`](/api/http2#http2http2serverrequest) +* `response` [`http2.Http2ServerResponse`](/api/http2#http2http2serverresponse) Emitted each time there is a request. There may be multiple requests per session. See the [Compatibility API][]. -##### `'session'` +##### `'session'` - + -* `session` {ServerHttp2Session} +* `session` [`ServerHttp2Session`](/api/http2#serverhttp2session) The `'session'` event is emitted when a new `Http2Session` is created by the `Http2SecureServer`. -##### `'sessionError'` +##### `'sessionError'` - + * `error` [`Error`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error) -* `session` {ServerHttp2Session} +* `session` [`ServerHttp2Session`](/api/http2#serverhttp2session) The `'sessionError'` event is emitted when an `'error'` event is emitted by an `Http2Session` object associated with the `Http2SecureServer`. -##### `'stream'` +##### `'stream'` - + -* `stream` {Http2Stream} A reference to the stream -* `headers` {HTTP/2 Headers Object} An object describing the headers +* `stream` [`Http2Stream`](/api/http2#http2stream) A reference to the stream +* `headers` ```{HTTP/2 Headers Object}``` An object describing the headers * `flags` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The associated numeric flags * `rawHeaders` [`Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array) An array containing the raw header names followed by their respective values. @@ -1970,17 +1970,17 @@ server.on('stream', (stream, headers, flags) => { }); ``` -##### `'timeout'` +##### `'timeout'` - + The `'timeout'` event is emitted when there is no activity on the Server for a given number of milliseconds set using `http2secureServer.setTimeout()`. **Default:** 2 minutes. -##### `'unknownProtocol'` +##### `'unknownProtocol'` - + * `socket` [`stream.Duplex`](/api/stream#streamduplex) @@ -1991,9 +1991,9 @@ the connection is terminated. A timeout may be specified using the `'unknownProtocolTimeout'` option passed to [`http2.createSecureServer()`][]. See the [Compatibility API][]. -##### `server.close([callback])` +##### `server.close([callback])` - + * `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) @@ -2006,13 +2006,13 @@ If `callback` is provided, it is not invoked until all active sessions have been closed, although the server has already stopped allowing new sessions. See [`tls.Server.close()`][] for more details. -##### `server.setTimeout([msecs][, callback])` +##### `server.setTimeout([msecs][, callback])` - + * `msecs` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) **Default:** `120000` (2 minutes) * `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) -* Returns: {Http2SecureServer} +* Returns: [`Http2SecureServer`](/api/http2#http2secureserver) Used to set the timeout value for http2 secure server requests, and sets a callback function that is called when there is no activity @@ -2023,9 +2023,9 @@ The given callback is registered as a listener on the `'timeout'` event. In case if `callback` is not a function, a new `ERR_INVALID_ARG_TYPE` error will be thrown. -##### `server.timeout` +##### `server.timeout` - + * [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Timeout in milliseconds. **Default:** 0 (no timeout) @@ -2037,11 +2037,11 @@ A value of `0` will disable the timeout behavior on incoming connections. The socket timeout logic is set up on connection, so changing this value only affects new connections to the server, not any existing connections. -##### `server.updateSettings([settings])` +##### `server.updateSettings([settings])` - + -* `settings` {HTTP/2 Settings Object} +* `settings` ```{HTTP/2 Settings Object}``` Used to update the server with the provided settings. @@ -2049,9 +2049,9 @@ Throws `ERR_HTTP2_INVALID_SETTING_VALUE` for invalid `settings` values. Throws `ERR_INVALID_ARG_TYPE` for invalid `settings` argument. -#### `http2.createServer([options][, onRequestHandler])` +#### `http2.createServer([options][, onRequestHandler])` - + * `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) * `maxDeflateDynamicTableSize` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Sets the maximum dynamic table size @@ -2106,7 +2106,7 @@ Throws `ERR_INVALID_ARG_TYPE` for invalid `settings` argument. error that should tell the peer to not open any more streams, continuing to open streams is therefore regarded as a sign of a misbehaving peer. **Default:** `100`. - * `settings` {HTTP/2 Settings Object} The initial settings to send to the + * `settings` ```{HTTP/2 Settings Object}``` The initial settings to send to the remote peer upon connection. * `Http1IncomingMessage` [`http.IncomingMessage`](/api/http#httpincomingmessage) Specifies the `IncomingMessage` class to used for HTTP/1 fallback. Useful for extending @@ -2114,11 +2114,11 @@ Throws `ERR_INVALID_ARG_TYPE` for invalid `settings` argument. * `Http1ServerResponse` [`http.ServerResponse`](/api/http#httpserverresponse) Specifies the `ServerResponse` class to used for HTTP/1 fallback. Useful for extending the original `http.ServerResponse`. **Default:** `http.ServerResponse`. - * `Http2ServerRequest` {http2.Http2ServerRequest} Specifies the + * `Http2ServerRequest` [`http2.Http2ServerRequest`](/api/http2#http2http2serverrequest) Specifies the `Http2ServerRequest` class to use. Useful for extending the original `Http2ServerRequest`. **Default:** `Http2ServerRequest`. - * `Http2ServerResponse` {http2.Http2ServerResponse} Specifies the + * `Http2ServerResponse` [`http2.Http2ServerResponse`](/api/http2#http2http2serverresponse) Specifies the `Http2ServerResponse` class to use. Useful for extending the original `Http2ServerResponse`. **Default:** `Http2ServerResponse`. @@ -2128,7 +2128,7 @@ Throws `ERR_INVALID_ARG_TYPE` for invalid `settings` argument. **Default:** `10000`. * ...: Any [`net.createServer()`][] option can be provided. * `onRequestHandler` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) See [Compatibility API][] -* Returns: {Http2Server} +* Returns: [`Http2Server`](/api/http2#http2server) Returns a `net.Server` instance that creates and manages `Http2Session` instances. @@ -2158,9 +2158,9 @@ server.on('stream', (stream, headers) => { server.listen(80); ``` -#### `http2.createSecureServer(options[, onRequestHandler])` +#### `http2.createSecureServer(options[, onRequestHandler])` - + * `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) * `allowHTTP1` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) Incoming client connections that do not support @@ -2216,7 +2216,7 @@ server.listen(80); error that should tell the peer to not open any more streams, continuing to open streams is therefore regarded as a sign of a misbehaving peer. **Default:** `100`. - * `settings` {HTTP/2 Settings Object} The initial settings to send to the + * `settings` ```{HTTP/2 Settings Object}``` The initial settings to send to the remote peer upon connection. * ...: Any [`tls.createServer()`][] options can be provided. For servers, the identity options (`pfx` or `key`/`cert`) are usually required. @@ -2227,7 +2227,7 @@ server.listen(80); the socket has not been destroyed by that time the server will destroy it. **Default:** `10000`. * `onRequestHandler` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) See [Compatibility API][] -* Returns: {Http2SecureServer} +* Returns: [`Http2SecureServer`](/api/http2#http2secureserver) Returns a `tls.Server` instance that creates and manages `Http2Session` instances. @@ -2255,9 +2255,9 @@ server.on('stream', (stream, headers) => { server.listen(80); ``` -#### `http2.connect(authority[, options][, listener])` +#### `http2.connect(authority[, options][, listener])` - + * `authority` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`URL`](/api/url#the-whatwg-url-api) The remote HTTP/2 server to connect to. This must be in the form of a minimal, valid URL with the `http://` or `https://` @@ -2314,7 +2314,7 @@ server.listen(80); * `protocol` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The protocol to connect with, if not set in the `authority`. Value may be either `'http:'` or `'https:'`. **Default:** `'https:'` - * `settings` {HTTP/2 Settings Object} The initial settings to send to the + * `settings` ```{HTTP/2 Settings Object}``` The initial settings to send to the remote peer upon connection. * `createConnection` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) An optional callback that receives the `URL` instance passed to `connect` and the `options` object, and returns any @@ -2326,7 +2326,7 @@ server.listen(80); **Default:** `10000`. * `listener` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) Will be registered as a one-time listener of the [`'connect'`][] event. -* Returns: {ClientHttp2Session} +* Returns: [`ClientHttp2Session`](/api/http2#clienthttp2session) Returns a `ClientHttp2Session` instance. @@ -2339,9 +2339,9 @@ const client = http2.connect('https://localhost:1234'); client.close(); ``` -#### `http2.constants` +#### `http2.constants` - + ##### Error codes for `RST_STREAM` and `GOAWAY` @@ -2365,21 +2365,21 @@ client.close(); The `'timeout'` event is emitted when there is no activity on the Server for a given number of milliseconds set using `http2server.setTimeout()`. -#### `http2.getDefaultSettings()` +#### `http2.getDefaultSettings()` - + -* Returns: {HTTP/2 Settings Object} +* Returns: ```{HTTP/2 Settings Object}``` Returns an object containing the default settings for an `Http2Session` instance. This method returns a new object instance every time it is called so instances returned may be safely modified for use. -#### `http2.getPackedSettings([settings])` +#### `http2.getPackedSettings([settings])` - + -* `settings` {HTTP/2 Settings Object} +* `settings` ```{HTTP/2 Settings Object}``` * Returns: [`Buffer`](/api/buffer#buffer) Returns a `Buffer` instance containing serialized representation of the given @@ -2395,19 +2395,19 @@ console.log(packed.toString('base64')); // Prints: AAIAAAAA ``` -#### `http2.getUnpackedSettings(buf)` +#### `http2.getUnpackedSettings(buf)` - + * `buf` [`Buffer`](/api/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) The packed settings. -* Returns: {HTTP/2 Settings Object} +* Returns: ```{HTTP/2 Settings Object}``` Returns a [HTTP/2 Settings Object][] containing the deserialized settings from the given `Buffer` as generated by `http2.getPackedSettings()`. -#### `http2.sensitiveHeaders` +#### `http2.sensitiveHeaders` - + * [`symbol`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Symbol_type) @@ -2491,7 +2491,7 @@ all headers marked as sensitive, including ones marked that way automatically. #### Settings object - + The `http2.getDefaultSettings()`, `http2.getPackedSettings()`, `http2.createServer()`, `http2.createSecureServer()`, @@ -2607,7 +2607,7 @@ const server = net.createServer((socket) => { let name = ''; socket.setEncoding('utf8'); socket.on('data', (chunk) => name += chunk); - socket.on('end', () => socket.end(`hello $name`)); + socket.on('end', () => socket.end(`hello ${name}`)); }); server.listen(8000); @@ -2654,7 +2654,7 @@ const client = http2.connect('http://localhost:8001'); // for CONNECT requests or an error will be thrown. const req = client.request({ ':method': 'CONNECT', - ':authority': `localhost:$port` + ':authority': `localhost:${port}` }); req.on('response', (headers) => { @@ -2664,7 +2664,7 @@ let data = ''; req.setEncoding('utf8'); req.on('data', (chunk) => data += chunk); req.on('end', () => { - console.log(`The server says: $data`); + console.log(`The server says: ${data}`); client.close(); }); req.end('Jane'); @@ -2768,9 +2768,9 @@ function onRequest(req, res) { The `'request'` event works identically on both [HTTPS][] and HTTP/2. -#### `http2.Http2ServerRequest` +#### `http2.Http2ServerRequest` - + * Extends: [`stream.Readable`](/api/stream#streamreadable) @@ -2779,9 +2779,9 @@ A `Http2ServerRequest` object is created by [`http2.Server`][] or [`'request'`][] event. It may be used to access a request status, headers, and data. -##### `'aborted'` +##### `'aborted'` - + The `'aborted'` event is emitted whenever a `Http2ServerRequest` instance is abnormally aborted in mid-communication. @@ -2789,25 +2789,25 @@ abnormally aborted in mid-communication. The `'aborted'` event will only be emitted if the `Http2ServerRequest` writable side has not been ended. -##### `'close'` +##### `'close'` - + Indicates that the underlying [`Http2Stream`][] was closed. Just like `'end'`, this event occurs only once per response. -##### `request.aborted` +##### `request.aborted` - + * [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) The `request.aborted` property will be `true` if the request has been aborted. -##### `request.authority` +##### `request.authority` - + * [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) @@ -2816,28 +2816,28 @@ to set either `:authority` or `host`, this value is derived from `req.headers[':authority']` if present. Otherwise, it is derived from `req.headers['host']`. -##### `request.complete` +##### `request.complete` - + * [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) The `request.complete` property will be `true` if the request has been completed, aborted, or destroyed. -##### `request.connection` +##### `request.connection` - + - + * [`net.Socket`](/api/net#netsocket) | [`tls.TLSSocket`](/api/tls#tlstlssocket) See [`request.socket`][]. -##### `request.destroy([error])` +##### `request.destroy([error])` - + * `error` [`Error`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error) @@ -2847,9 +2847,9 @@ is emitted and `error` is passed as an argument to any listeners on the event. It does nothing if the stream was already destroyed. -##### `request.headers` +##### `request.headers` - + * [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) @@ -2879,9 +2879,9 @@ removeAllHeaders(request.headers); assert(request.url); // Fails because the :path header has been removed ``` -##### `request.httpVersion` +##### `request.httpVersion` - + * [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) @@ -2892,17 +2892,17 @@ client response, the HTTP version of the connected-to server. Returns Also `message.httpVersionMajor` is the first integer and `message.httpVersionMinor` is the second. -##### `request.method` +##### `request.method` - + * [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The request method as a string. Read-only. Examples: `'GET'`, `'DELETE'`. -##### `request.rawHeaders` +##### `request.rawHeaders` - + * string\[] @@ -2928,31 +2928,31 @@ Header names are not lowercased, and duplicates are not merged. console.log(request.rawHeaders); ``` -##### `request.rawTrailers` +##### `request.rawTrailers` - + * string\[] The raw request/response trailer keys and values exactly as they were received. Only populated at the `'end'` event. -##### `request.scheme` +##### `request.scheme` - + * [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The request scheme pseudo header field indicating the scheme portion of the target URL. -##### `request.setTimeout(msecs, callback)` +##### `request.setTimeout(msecs, callback)` - + * `msecs` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) * `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) -* Returns: {http2.Http2ServerRequest} +* Returns: [`http2.Http2ServerRequest`](/api/http2#http2http2serverrequest) Sets the [`Http2Stream`][]'s timeout value to `msecs`. If a callback is provided, then it is added as a listener on the `'timeout'` event on @@ -2963,9 +2963,9 @@ the server, then [`Http2Stream`][]s are destroyed when they time out. If a handler is assigned to the request, the response, or the server's `'timeout'` events, timed out sockets must be handled explicitly. -##### `request.socket` +##### `request.socket` - + * [`net.Socket`](/api/net#netsocket) | [`tls.TLSSocket`](/api/tls#tlstlssocket) @@ -2988,25 +2988,25 @@ All other interactions will be routed directly to the socket. With TLS support, use [`request.socket.getPeerCertificate()`][] to obtain the client's authentication details. -##### `request.stream` +##### `request.stream` - + -* {Http2Stream} +* [`Http2Stream`](/api/http2#http2stream) The [`Http2Stream`][] object backing the request. -##### `request.trailers` +##### `request.trailers` - + * [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) The request/response trailers object. Only populated at the `'end'` event. -##### `request.url` +##### `request.url` - + * [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) @@ -3047,25 +3047,25 @@ URL { } ``` -#### `http2.Http2ServerResponse` +#### `http2.Http2ServerResponse` - + * Extends: [`Stream`](/api/stream#stream) This object is created internally by an HTTP server, not by the user. It is passed as the second parameter to the [`'request'`][] event. -##### `'close'` +##### `'close'` - + Indicates that the underlying [`Http2Stream`][] was terminated before [`response.end()`][] was called or able to flush. -##### `'finish'` +##### `'finish'` - + Emitted when the response has been sent. More specifically, this event is emitted when the last segment of the response headers and body have been @@ -3074,9 +3074,9 @@ does not imply that the client has received anything yet. After this event, no more events will be emitted on the response object. -##### `response.addTrailers(headers)` +##### `response.addTrailers(headers)` - + * `headers` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) @@ -3086,27 +3086,27 @@ message) to the response. Attempting to set a header field name or value that contains invalid characters will result in a [`TypeError`][] being thrown. -##### `response.connection` +##### `response.connection` - + - + * [`net.Socket`](/api/net#netsocket) | [`tls.TLSSocket`](/api/tls#tlstlssocket) See [`response.socket`][]. -##### `response.createPushResponse(headers, callback)` +##### `response.createPushResponse(headers, callback)` - + -* `headers` {HTTP/2 Headers Object} An object describing the headers +* `headers` ```{HTTP/2 Headers Object}``` An object describing the headers * `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) Called once `http2stream.pushStream()` is finished, or either when the attempt to create the pushed `Http2Stream` has failed or has been rejected, or the state of `Http2ServerRequest` is closed prior to calling the `http2stream.pushStream()` method * `err` [`Error`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error) - * `res` {http2.Http2ServerResponse} The newly-created `Http2ServerResponse` + * `res` [`http2.Http2ServerResponse`](/api/http2#http2http2serverresponse) The newly-created `Http2ServerResponse` object Call [`http2stream.pushStream()`][] with the given headers, and wrap the @@ -3114,11 +3114,11 @@ given [`Http2Stream`][] on a newly created `Http2ServerResponse` as the callback parameter if successful. When `Http2ServerRequest` is closed, the callback is called with an error `ERR_HTTP2_INVALID_STREAM`. -##### `response.end([data[, encoding]][, callback])` +##### `response.end([data[, encoding]][, callback])` - + -* `data` {string|Buffer|Uint8Array} +* `data` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`Uint8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array) * `encoding` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) * `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) * Returns: [`this`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this) @@ -3133,20 +3133,20 @@ If `data` is specified, it is equivalent to calling If `callback` is specified, it will be called when the response stream is finished. -##### `response.finished` +##### `response.finished` - + - + * [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) Boolean value that indicates whether the response has completed. Starts as `false`. After [`response.end()`][] executes, the value will be `true`. -##### `response.getHeader(name)` +##### `response.getHeader(name)` - + * `name` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) * Returns: [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) @@ -3158,9 +3158,9 @@ The name is case-insensitive. const contentType = response.getHeader('content-type'); ``` -##### `response.getHeaderNames()` +##### `response.getHeaderNames()` - + * Returns: string\[] @@ -3175,9 +3175,9 @@ const headerNames = response.getHeaderNames(); // headerNames === ['foo', 'set-cookie'] ``` -##### `response.getHeaders()` +##### `response.getHeaders()` - + * Returns: [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) @@ -3200,9 +3200,9 @@ const headers = response.getHeaders(); // headers === { foo: 'bar', 'set-cookie': ['foo=bar', 'bar=baz'] } ``` -##### `response.hasHeader(name)` +##### `response.hasHeader(name)` - + * `name` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) * Returns: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) @@ -3214,17 +3214,17 @@ outgoing headers. The header name matching is case-insensitive. const hasContentType = response.hasHeader('content-type'); ``` -##### `response.headersSent` +##### `response.headersSent` - + * [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) True if headers were sent, false otherwise (read-only). -##### `response.removeHeader(name)` +##### `response.removeHeader(name)` - + * `name` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) @@ -3234,17 +3234,17 @@ Removes a header that has been queued for implicit sending. response.removeHeader('Content-Encoding'); ``` -#### `response.req` +#### `response.req` - + -* {http2.Http2ServerRequest} +* [`http2.Http2ServerRequest`](/api/http2#http2http2serverrequest) A reference to the original HTTP2 `request` object. -##### `response.sendDate` +##### `response.sendDate` - + * [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) @@ -3254,9 +3254,9 @@ the response if it is not already present in the headers. Defaults to true. This should only be disabled for testing; HTTP requires the Date header in responses. -##### `response.setHeader(name, value)` +##### `response.setHeader(name, value)` - + * `name` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) * `value` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) @@ -3292,13 +3292,13 @@ const server = http2.createServer((req, res) => { }); ``` -##### `response.setTimeout(msecs[, callback])` +##### `response.setTimeout(msecs[, callback])` - + * `msecs` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) * `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) -* Returns: {http2.Http2ServerResponse} +* Returns: [`http2.Http2ServerResponse`](/api/http2#http2http2serverresponse) Sets the [`Http2Stream`][]'s timeout value to `msecs`. If a callback is provided, then it is added as a listener on the `'timeout'` event on @@ -3309,9 +3309,9 @@ the server, then [`Http2Stream`][]s are destroyed when they time out. If a handler is assigned to the request, the response, or the server's `'timeout'` events, timed out sockets must be handled explicitly. -##### `response.socket` +##### `response.socket` - + * [`net.Socket`](/api/net#netsocket) | [`tls.TLSSocket`](/api/tls#tlstlssocket) @@ -3337,13 +3337,13 @@ const http2 = require('node:http2'); const server = http2.createServer((req, res) => { const ip = req.socket.remoteAddress; const port = req.socket.remotePort; - res.end(`Your IP address is $ip and your source port is $port.`); + res.end(`Your IP address is ${ip} and your source port is ${port}.`); }).listen(3000); ``` -##### `response.statusCode` +##### `response.statusCode` - + * [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) @@ -3358,26 +3358,26 @@ response.statusCode = 404; After response header was sent to the client, this property indicates the status code which was sent out. -##### `response.statusMessage` +##### `response.statusMessage` - + * [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) Status message is not supported by HTTP/2 (RFC 7540 8.1.2.4). It returns an empty string. -##### `response.stream` +##### `response.stream` - + -* {Http2Stream} +* [`Http2Stream`](/api/http2#http2stream) The [`Http2Stream`][] object backing the response. -##### `response.writableEnded` +##### `response.writableEnded` - + * [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) @@ -3385,11 +3385,11 @@ Is `true` after [`response.end()`][] has been called. This property does not indicate whether the data has been flushed, for this use [`writable.writableFinished`][] instead. -##### `response.write(chunk[, encoding][, callback])` +##### `response.write(chunk[, encoding][, callback])` - + -* `chunk` {string|Buffer|Uint8Array} +* `chunk` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`Uint8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array) * `encoding` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) * `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) * Returns: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) @@ -3422,22 +3422,22 @@ Returns `true` if the entire data was flushed successfully to the kernel buffer. Returns `false` if all or part of the data was queued in user memory. `'drain'` will be emitted when the buffer is free again. -##### `response.writeContinue()` +##### `response.writeContinue()` - + Sends a status `100 Continue` to the client, indicating that the request body should be sent. See the [`'checkContinue'`][] event on `Http2Server` and `Http2SecureServer`. -##### `response.writeHead(statusCode[, statusMessage][, headers])` +##### `response.writeHead(statusCode[, statusMessage][, headers])` - + * `statusCode` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) * `statusMessage` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) * `headers` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) | [`Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array) -* Returns: {http2.Http2ServerResponse} +* Returns: [`http2.Http2ServerResponse`](/api/http2#http2http2serverresponse) Sends a response header to the request. The status code is a 3-digit HTTP status code, like `404`. The last argument, `headers`, are the response headers. diff --git a/content/api/v18/https.en.md b/content/api/v18/https.en.md index 8404f88657..afc5e22638 100644 --- a/content/api/v18/https.en.md +++ b/content/api/v18/https.en.md @@ -2,15 +2,15 @@ title: 'https' displayTitle: 'HTTPS' category: 'api' -editPage: 'https://github.com/nodejs/node/blob/v18.8.0/doc/api/https.md' +editPage: 'https://github.com/nodejs/node/blob/v18.9.0/doc/api/https.md' version: 'v18' --- - + - + - + HTTPS is the HTTP protocol over TLS/SSL. In Node.js this is implemented as a separate module. @@ -52,16 +52,16 @@ try { } ``` -### `https.Agent` +### `https.Agent` - + An [`Agent`][] object for HTTPS similar to [`http.Agent`][]. See [`https.request()`][] for more information. -#### `new Agent([options])` +#### `new Agent([options])` - + * `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) Set of configurable options to set on the agent. Can have the same fields as for [`http.Agent(options)`][], and @@ -76,9 +76,9 @@ An [`Agent`][] object for HTTPS similar to [`http.Agent`][]. See See [`Session Resumption`][] for information about TLS session reuse. -##### `'keylog'` +##### `'keylog'` - + * `line` [`Buffer`](/api/buffer#buffer) Line of ASCII text, in NSS `SSLKEYLOGFILE` format. * `tlsSocket` [`tls.TLSSocket`](/api/tls#tlstlssocket) The `tls.TLSSocket` instance on which it was @@ -100,65 +100,65 @@ https.globalAgent.on('keylog', (line, tlsSocket) => { }); ``` -### `https.Server` +### `https.Server` - + * Extends: [`tls.Server`](/api/tls#tlsserver) See [`http.Server`][] for more information. -#### `server.close([callback])` +#### `server.close([callback])` - + * `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) * Returns: [`https.Server`](/api/https#httpsserver) See [`server.close()`][] in the `node:http` module. -#### `server.closeAllConnections()` +#### `server.closeAllConnections()` - + See [`server.closeAllConnections()`][] in the `node:http` module. -#### `server.closeIdleConnections()` +#### `server.closeIdleConnections()` - + See [`server.closeIdleConnections()`][] in the `node:http` module. -#### `server.headersTimeout` +#### `server.headersTimeout` - + * [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) **Default:** `60000` See [`server.headersTimeout`][] in the `node:http` module. -#### `server.listen()` +#### `server.listen()` Starts the HTTPS server listening for encrypted connections. This method is identical to [`server.listen()`][] from [`net.Server`][]. -#### `server.maxHeadersCount` +#### `server.maxHeadersCount` * [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) **Default:** `2000` See [`server.maxHeadersCount`][] in the `node:http` module. -#### `server.requestTimeout` +#### `server.requestTimeout` - + * [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) **Default:** `0` See [`server.requestTimeout`][] in the `node:http` module. -#### `server.setTimeout([msecs][, callback])` +#### `server.setTimeout([msecs][, callback])` - + * `msecs` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) **Default:** `120000` (2 minutes) * `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) @@ -166,25 +166,25 @@ See [`server.requestTimeout`][] in the `node:http` module. See [`server.setTimeout()`][] in the `node:http` module. -#### `server.timeout` +#### `server.timeout` - + * [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) **Default:** 0 (no timeout) See [`server.timeout`][] in the `node:http` module. -#### `server.keepAliveTimeout` +#### `server.keepAliveTimeout` - + * [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) **Default:** `5000` (5 seconds) See [`server.keepAliveTimeout`][] in the `node:http` module. -### `https.createServer([options][, requestListener])` +### `https.createServer([options][, requestListener])` - + * `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) Accepts `options` from [`tls.createServer()`][], [`tls.createSecureContext()`][] and [`http.createServer()`][]. @@ -224,14 +224,14 @@ https.createServer(options, (req, res) => { }).listen(8000); ``` -### `https.get(options[, callback])` +### `https.get(options[, callback])` -### `https.get(url[, options][, callback])` +### `https.get(url[, options][, callback])` - + -* `url` {string | URL} -* `options` {Object | string | URL} Accepts the same `options` as +* `url` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`URL`](/api/url#the-whatwg-url-api) +* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`URL`](/api/url#the-whatwg-url-api) Accepts the same `options` as [`https.request()`][], with the `method` always set to `GET`. * `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) @@ -257,20 +257,20 @@ https.get('https://encrypted.google.com/', (res) => { }); ``` -### `https.globalAgent` +### `https.globalAgent` - + Global instance of [`https.Agent`][] for all HTTPS client requests. -### `https.request(options[, callback])` +### `https.request(options[, callback])` -### `https.request(url[, options][, callback])` +### `https.request(url[, options][, callback])` - + -* `url` {string | URL} -* `options` {Object | string | URL} Accepts all `options` from +* `url` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`URL`](/api/url#the-whatwg-url-api) +* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`URL`](/api/url#the-whatwg-url-api) Accepts all `options` from [`http.request()`][], with some differences in default values: * `protocol` **Default:** `'https:'` * `port` **Default:** `443` @@ -392,7 +392,7 @@ const options = { const pubkey256 = 'pL1+qb9HTMRZJmuC/bB/ZI9d302BYrrqiVuRyW+DGrU='; if (sha256(cert.pubkey) !== pubkey256) { const msg = 'Certificate verification error: ' + - `The public key of '$cert.subject.CN' ` + + `The public key of '${cert.subject.CN}' ` + 'does not match our pinned fingerprint'; return new Error(msg); } @@ -402,7 +402,7 @@ const options = { 'D8:3E:4C:1D:98:DB:71:E4:1A:48:03:98:EA:22:6A:BD:8B:93:16'; if (cert.fingerprint256 !== cert256) { const msg = 'Certificate verification error: ' + - `The certificate of '$cert.subject.CN' ` + + `The certificate of '${cert.subject.CN}' ` + 'does not match our pinned fingerprint'; return new Error(msg); } diff --git a/content/api/v18/inspector.en.md b/content/api/v18/inspector.en.md index 10540d46da..3033a1564f 100644 --- a/content/api/v18/inspector.en.md +++ b/content/api/v18/inspector.en.md @@ -2,15 +2,15 @@ title: 'inspector' displayTitle: 'Inspector' category: 'api' -editPage: 'https://github.com/nodejs/node/blob/v18.8.0/doc/api/inspector.md' +editPage: 'https://github.com/nodejs/node/blob/v18.9.0/doc/api/inspector.md' version: 'v18' --- - + - + - + The `node:inspector` module provides an API for interacting with the V8 inspector. @@ -21,13 +21,13 @@ It can be accessed using: const inspector = require('node:inspector'); ``` -### `inspector.close()` +### `inspector.close()` Deactivate the inspector. Blocks until there are no active connections. This function is not available in [worker threads][]. -### `inspector.console` +### `inspector.console` * [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) An object to send messages to the remote inspector console. @@ -38,7 +38,7 @@ require('node:inspector').console.log('a message'); The inspector console does not have API parity with Node.js console. -### `inspector.open([port[, host[, wait]]])` +### `inspector.open([port[, host[, wait]]])` * `port` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Port to listen on for inspector connections. Optional. **Default:** what was specified on the CLI. @@ -57,7 +57,7 @@ and flow control has been passed to the debugger client. See the [security warning][] regarding the `host` parameter usage. -### `inspector.url()` +### `inspector.url()` * Returns: [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`undefined`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type) @@ -78,33 +78,33 @@ $ node -p 'inspector.url()' undefined ``` -### `inspector.waitForDebugger()` +### `inspector.waitForDebugger()` - + Blocks until a client (existing or connected later) has sent `Runtime.runIfWaitingForDebugger` command. An exception will be thrown if there is no active inspector. -### `inspector.Session` +### `inspector.Session` * Extends: [`EventEmitter`](/api/events#eventemitter) The `inspector.Session` is used for dispatching messages to the V8 inspector back-end and receiving message responses and notifications. -#### `new inspector.Session()` +#### `new inspector.Session()` - + Create a new instance of the `inspector.Session` class. The inspector session needs to be connected through [`session.connect()`][] before the messages can be dispatched to the inspector backend. -#### `'inspectorNotification'` +#### `'inspectorNotification'` - + * [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) The notification message object @@ -118,9 +118,9 @@ session.on('inspectorNotification', (message) => console.log(message.method)); It is also possible to subscribe only to notifications with specific method: -#### ``; +#### ``; - + * [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) The notification message object @@ -138,31 +138,31 @@ session.on('Debugger.paused', ({ params }) => { // [ '/the/file/that/has/the/breakpoint.js:11:0' ] ``` -#### `session.connect()` +#### `session.connect()` - + Connects a session to the inspector back-end. -#### `session.connectToMainThread()` +#### `session.connectToMainThread()` - + Connects a session to the main thread inspector back-end. An exception will be thrown if this API was not called on a Worker thread. -#### `session.disconnect()` +#### `session.disconnect()` - + Immediately close the session. All pending message callbacks will be called with an error. [`session.connect()`][] will need to be called to be able to send messages again. Reconnected session will lose all inspector state, such as enabled agents or configured breakpoints. -#### `session.post(method[, params][, callback])` +#### `session.post(method[, params][, callback])` - + * `method` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) * `params` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) diff --git a/content/api/v18/intl.en.md b/content/api/v18/intl.en.md index 77cb759ef1..63814ec612 100644 --- a/content/api/v18/intl.en.md +++ b/content/api/v18/intl.en.md @@ -2,13 +2,13 @@ title: 'intl' displayTitle: 'Internationalization support' category: 'api' -editPage: 'https://github.com/nodejs/node/blob/v18.8.0/doc/api/intl.md' +editPage: 'https://github.com/nodejs/node/blob/v18.9.0/doc/api/intl.md' version: 'v18' --- - + - + Node.js has many features that make it easier to write internationalized programs. Some of them are: diff --git a/content/api/v18/module.en.md b/content/api/v18/module.en.md index be86a92b5a..93af481eae 100644 --- a/content/api/v18/module.en.md +++ b/content/api/v18/module.en.md @@ -2,13 +2,13 @@ title: 'module' displayTitle: '`node:module` API' category: 'api' -editPage: 'https://github.com/nodejs/node/blob/v18.8.0/doc/api/module.md' +editPage: 'https://github.com/nodejs/node/blob/v18.9.0/doc/api/module.md' version: 'v18' --- - + - + ### The `Module` object @@ -18,9 +18,9 @@ Provides general utility methods when interacting with instances of `Module`, the [`module`][] variable often seen in [CommonJS][] modules. Accessed via `import 'node:module'` or `require('node:module')`. -#### `module.builtinModules` +#### `module.builtinModules` - + * string\[] @@ -42,9 +42,9 @@ import { builtinModules as builtin } from 'node:module'; const builtin = require('node:module').builtinModules; ``` -#### `module.createRequire(filename)` +#### `module.createRequire(filename)` - + * `filename` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`URL`](/api/url#the-whatwg-url-api) Filename to be used to construct the require function. Must be a file URL object, file URL string, or absolute path @@ -59,9 +59,9 @@ const require = createRequire(import.meta.url); const siblingModule = require('./sibling-module'); ``` -#### `module.isBuiltin(moduleName)` +#### `module.isBuiltin(moduleName)` - + * `moduleName` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) name of the module * Returns: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) returns true if the module is builtin else returns false @@ -73,9 +73,9 @@ isBuiltin('fs'); // true isBuiltin('wss'); // false ``` -#### `module.syncBuiltinESMExports()` +#### `module.syncBuiltinESMExports()` - + The `module.syncBuiltinESMExports()` method updates all the live bindings for builtin [ES Modules][] to match the properties of the [CommonJS][] exports. It @@ -112,9 +112,9 @@ import('node:fs').then((esmFS) => { ### Source map v3 support - + - + Helpers for interacting with the source map cache. This cache is populated when source map parsing is enabled and @@ -140,21 +140,22 @@ const { findSourceMap, SourceMap } = require('node:module'); -#### `module.findSourceMap(path)` +#### `module.findSourceMap(path)` - + * `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) -* Returns: [`module.SourceMap`](/api/module#modulesourcemap) +* Returns: [`module.SourceMap`](/api/module#modulesourcemap) | [`undefined`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type) Returns `module.SourceMap` if a source + map is found, `undefined` otherwise. `path` is the resolved path for the file for which a corresponding source map should be fetched. -#### `module.SourceMap` +#### `module.SourceMap` - + -##### `new SourceMap(payload)` +##### `new SourceMap(payload)` * `payload` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) @@ -170,13 +171,13 @@ Creates a new `sourceMap` instance. * `mappings`: [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) * `sourceRoot`: [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) -##### `sourceMap.payload` +##### `sourceMap.payload` * Returns: [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) Getter for the payload used to construct the [`SourceMap`][] instance. -##### `sourceMap.findEntry(lineNumber, columnNumber)` +##### `sourceMap.findEntry(lineNumber, columnNumber)` * `lineNumber` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) * `columnNumber` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) diff --git a/content/api/v18/modules.en.md b/content/api/v18/modules.en.md index 3f16b8b701..1a025e4398 100644 --- a/content/api/v18/modules.en.md +++ b/content/api/v18/modules.en.md @@ -2,15 +2,15 @@ title: 'modules' displayTitle: 'CommonJS modules' category: 'api' -editPage: 'https://github.com/nodejs/node/blob/v18.8.0/doc/api/modules.md' +editPage: 'https://github.com/nodejs/node/blob/v18.9.0/doc/api/modules.md' version: 'v18' --- - + - + - + CommonJS modules are the original way to package JavaScript code for Node.js. Node.js also supports the [ECMAScript modules][] standard used by browsers @@ -75,7 +75,7 @@ The CommonJS module system is implemented in the [`module` core module][]. ### Enabling - + Node.js has two module systems: CommonJS modules and [ECMAScript modules][]. @@ -106,7 +106,7 @@ always use the ECMAScript module loader. ### Accessing the main module - + When a file is run directly from Node.js, `require.main` is set to its `module`. That means that it is possible to determine whether a file has been @@ -120,7 +120,7 @@ and the main module is out of reach. ### Package manager tips - + The semantics of the Node.js `require()` function were designed to be general enough to support reasonable directory structures. Package manager programs @@ -183,7 +183,7 @@ regarding which files are parsed as ECMAScript modules. ### All together - + To get the exact filename that will be loaded when `require()` is called, use the `require.resolve()` function. @@ -278,7 +278,7 @@ LOAD_PACKAGE_SELF(X, DIR) 6. RESOLVE_ESM_MATCH(MATCH) RESOLVE_ESM_MATCH(MATCH) -1. let { RESOLVED, EXACT } = MATCH +1. let ```{ RESOLVED, EXACT }``` = MATCH 2. let RESOLVED_PATH = fileURLToPath(RESOLVED) 3. If EXACT is true, a. If the file at RESOLVED_PATH exists, load RESOLVED_PATH as its extension @@ -287,11 +287,11 @@ RESOLVE_ESM_MATCH(MATCH) a. LOAD_AS_FILE(RESOLVED_PATH) b. LOAD_AS_DIRECTORY(RESOLVED_PATH) 5. THROW "not found" -``` + ### Caching - + Modules are cached after the first time they are loaded. This means (among other things) that every call to `require('foo')` will get exactly the same object @@ -307,7 +307,7 @@ function. #### Module caching caveats - + Modules are cached based on their resolved filename. Since modules may resolve to a different filename based on the location of the calling module (loading @@ -322,9 +322,9 @@ irrespective of whether or not `./foo` and `./FOO` are the same file. ### Core modules - + - + Node.js has several modules compiled into the binary. These modules are described in greater detail elsewhere in this documentation. @@ -345,7 +345,7 @@ as [`module.builtinModules`][]. ### Cycles - + When there are circular `require()` calls, a module might not have finished executing when it is returned. @@ -409,7 +409,7 @@ correctly within an application. ### File modules - + If the exact filename is not found, then Node.js will attempt to load the required filename with the added extensions: `.js`, `.json`, and finally @@ -439,9 +439,9 @@ If the given path does not exist, `require()` will throw a ### Folders as modules - + - + There are three ways in which a folder may be passed to `require()` as an argument. @@ -482,7 +482,7 @@ folders as modules, and work for both `require` and `import`. ### Loading from `node_modules` folders - + If the module identifier passed to `require()` is not a [core](#core-modules) module, and does not begin with `'/'`, `'../'`, or @@ -514,7 +514,7 @@ same module resolution semantics. ### Loading from the global folders - + If the `NODE_PATH` environment variable is set to a colon-delimited list of absolute paths, then Node.js will search those paths for modules if they @@ -548,7 +548,7 @@ folder. These will be loaded faster, and more reliably. ### The module wrapper - + Before a module's code is executed, Node.js will wrap it with a function wrapper that looks like the following: @@ -572,11 +572,11 @@ By doing this, Node.js achieves a few things: ### The module scope -#### `__dirname` +#### `__dirname` - + - + * [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) @@ -592,11 +592,11 @@ console.log(path.dirname(__filename)); // Prints: /Users/mjr ``` -#### `__filename` +#### `__filename` - + - + * [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) @@ -629,11 +629,11 @@ References to `__filename` within `b.js` will return `/Users/mjr/app/node_modules/b/b.js` while references to `__filename` within `a.js` will return `/Users/mjr/app/a.js`. -#### `exports` +#### `exports` - + - + * [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) @@ -641,11 +641,11 @@ A reference to the `module.exports` that is shorter to type. See the section about the [exports shortcut][] for details on when to use `exports` and when to use `module.exports`. -#### `module` +#### `module` - + - + * [`module`](/api/modules#the-module-object) @@ -653,11 +653,11 @@ A reference to the current module, see the section about the [`module` object][]. In particular, `module.exports` is used for defining what a module exports and makes available through `require()`. -#### `require(id)` +#### `require(id)` - + - + * `id` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) module name or path * Returns: [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) exported module content @@ -682,9 +682,9 @@ const jsonData = require('./path/filename.json'); const crypto = require('node:crypto'); ``` -##### `require.cache` +##### `require.cache` - + * [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) @@ -711,11 +711,11 @@ assert.strictEqual(require('node:fs'), fakeFs); assert.strictEqual(require('node:fs'), realFs); ``` -##### `require.extensions` +##### `require.extensions` - + - + * [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) @@ -735,11 +735,11 @@ program, or compiling them to JavaScript ahead of time. Avoid using `require.extensions`. Use could cause subtle bugs and resolving the extensions gets slower with each registered extension. -##### `require.main` +##### `require.main` - + -* {module | undefined} +* [`module`](/api/modules#the-module-object) | [`undefined`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type) The `Module` object representing the entry script loaded when the Node.js process launched, or `undefined` if the entry point of the program is not a @@ -773,9 +773,9 @@ Module { '/node_modules' ] } ``` -##### `require.resolve(request[, options])` +##### `require.resolve(request[, options])` - + * `request` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The module path to resolve. * `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) @@ -794,7 +794,7 @@ If the module can not be found, a `MODULE_NOT_FOUND` error is thrown. ###### `require.resolve.paths(request)` - + * `request` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The module path whose lookup paths are being retrieved. * Returns: [`null`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type) @@ -805,11 +805,11 @@ Returns an array containing the paths searched during resolution of `request` or ### The `module` object - + - + - + * [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) @@ -818,17 +818,17 @@ representing the current module. For convenience, `module.exports` is also accessible via the `exports` module-global. `module` is not actually a global but rather local to each module. -#### `module.children` +#### `module.children` - + * module\[] The module objects required for the first time by this one. -#### `module.exports` +#### `module.exports` - + * [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) @@ -879,9 +879,9 @@ const x = require('./x'); console.log(x.a); ``` -##### `exports` shortcut +##### `exports` shortcut - + The `exports` variable is available within a module's file-level scope, and is assigned the value of `module.exports` before the module is evaluated. @@ -926,71 +926,71 @@ function require(/* ... */) { } ``` -#### `module.filename` +#### `module.filename` - + * [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The fully resolved filename of the module. -#### `module.id` +#### `module.id` - + * [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The identifier for the module. Typically this is the fully resolved filename. -#### `module.isPreloading` +#### `module.isPreloading` - + * Type: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) `true` if the module is running during the Node.js preload phase. -#### `module.loaded` +#### `module.loaded` - + * [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) Whether or not the module is done loading, or is in the process of loading. -#### `module.parent` +#### `module.parent` - + - [`module.children`][] instead."}}} /> + -* {module | null | undefined} +* [`module`](/api/modules#the-module-object) | [`null`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type) | [`undefined`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type) The module that first required this one, or `null` if the current module is the entry point of the current process, or `undefined` if the module was loaded by something that is not a CommonJS module (E.G.: REPL or `import`). -#### `module.path` +#### `module.path` - + * [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The directory name of the module. This is usually the same as the [`path.dirname()`][] of the [`module.id`][]. -#### `module.paths` +#### `module.paths` - + * string\[] The search paths for the module. -#### `module.require(id)` +#### `module.require(id)` - + * `id` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) * Returns: [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) exported module content diff --git a/content/api/v18/n-api.en.md b/content/api/v18/n-api.en.md index 2640faaa66..3de59355f4 100644 --- a/content/api/v18/n-api.en.md +++ b/content/api/v18/n-api.en.md @@ -2,15 +2,15 @@ title: 'n-api' displayTitle: 'Node-API' category: 'api' -editPage: 'https://github.com/nodejs/node/blob/v18.8.0/doc/api/n-api.md' +editPage: 'https://github.com/nodejs/node/blob/v18.9.0/doc/api/n-api.md' version: 'v18' --- - + - + - + Node-API (formerly N-API) is an API for building native Addons. It is independent from the underlying JavaScript runtime (for example, V8) and is @@ -488,9 +488,9 @@ the addon. To this end, Node-API provides a way to allocate data such that its life cycle is tied to the life cycle of the Agent. -#### `napi_set_instance_data` +#### `napi_set_instance_data` - + ```c napi_status napi_set_instance_data(napi_env env, @@ -515,9 +515,9 @@ the currently running Agent which was set by means of a previous call to `napi_set_instance_data()` will be overwritten. If a `finalize_cb` was provided by the previous call, it will not be called. -#### `napi_get_instance_data` +#### `napi_get_instance_data` - + ```c napi_status napi_get_instance_data(napi_env env, @@ -540,9 +540,9 @@ Node-API exposes the following fundamental datatypes as abstractions that are consumed by the various APIs. These APIs should be treated as opaque, introspectable only with other Node-API calls. -#### `napi_status` +#### `napi_status` - + Integral status code indicating the success or failure of a Node-API call. Currently, the following status codes are supported. @@ -577,9 +577,9 @@ typedef enum { If additional information is required upon an API returning a failed status, it can be obtained by calling `napi_get_last_error_info`. -#### `napi_extended_error_info` +#### `napi_extended_error_info` - + ```c typedef struct { @@ -600,7 +600,7 @@ typedef struct { See the [Error handling][] section for additional information. -#### `napi_env` +#### `napi_env` `napi_env` is used to represent a context that the underlying Node-API implementation can use to persist VM-specific state. This structure is passed @@ -614,21 +614,21 @@ when an instance of a native addon is unloaded. Notification of this event is delivered through the callbacks given to [`napi_add_env_cleanup_hook`][] and [`napi_set_instance_data`][]. -#### `napi_value` +#### `napi_value` This is an opaque pointer that is used to represent a JavaScript value. -#### `napi_threadsafe_function` +#### `napi_threadsafe_function` - + This is an opaque pointer that represents a JavaScript function which can be called asynchronously from multiple threads via `napi_call_threadsafe_function()`. -#### `napi_threadsafe_function_release_mode` +#### `napi_threadsafe_function_release_mode` - + A value to be given to `napi_release_threadsafe_function()` to indicate whether the thread-safe function is to be closed immediately (`napi_tsfn_abort`) or @@ -642,9 +642,9 @@ typedef enum { } napi_threadsafe_function_release_mode; ``` -#### `napi_threadsafe_function_call_mode` +#### `napi_threadsafe_function_call_mode` - + A value to be given to `napi_call_threadsafe_function()` to indicate whether the call should block whenever the queue associated with the thread-safe @@ -659,7 +659,7 @@ typedef enum { #### Node-API memory management types -##### `napi_handle_scope` +##### `napi_handle_scope` This is an abstraction used to control and modify the lifetime of objects created within a particular scope. In general, Node-API values are created @@ -678,16 +678,16 @@ longer referenced from the current stack frame. For more details, review the [Object lifetime management][]. -##### `napi_escapable_handle_scope` +##### `napi_escapable_handle_scope` - + Escapable handle scopes are a special type of handle scope to return values created within a particular handle scope to a parent scope. -##### `napi_ref` +##### `napi_ref` - + This is the abstraction to use to reference a `napi_value`. This allows for users to manage the lifetimes of JavaScript values, including defining their @@ -695,9 +695,9 @@ minimum lifetimes explicitly. For more details, review the [Object lifetime management][]. -##### `napi_type_tag` +##### `napi_type_tag` - + A 128-bit value stored as two unsigned 64-bit integers. It serves as a UUID with which JavaScript objects can be "tagged" in order to ensure that they are @@ -715,9 +715,9 @@ typedef struct { } napi_type_tag; ``` -##### `napi_async_cleanup_hook_handle` +##### `napi_async_cleanup_hook_handle` - + An opaque value returned by [`napi_add_async_cleanup_hook`][]. It must be passed to [`napi_remove_async_cleanup_hook`][] when the chain of asynchronous cleanup @@ -725,17 +725,17 @@ events completes. #### Node-API callback types -##### `napi_callback_info` +##### `napi_callback_info` - + Opaque datatype that is passed to a callback function. It can be used for getting additional information about the context in which the callback was invoked. -##### `napi_callback` +##### `napi_callback` - + Function pointer type for user-provided native functions which are to be exposed to JavaScript via Node-API. Callback functions should satisfy the @@ -748,9 +748,9 @@ typedef napi_value (*napi_callback)(napi_env, napi_callback_info); Unless for reasons discussed in [Object Lifetime Management][], creating a handle and/or callback scope inside a `napi_callback` is not necessary. -##### `napi_finalize` +##### `napi_finalize` - + Function pointer type for add-on provided functions that allow the user to be notified when externally-owned data is ready to be cleaned up because the @@ -768,9 +768,9 @@ typedef void (*napi_finalize)(napi_env env, Unless for reasons discussed in [Object Lifetime Management][], creating a handle and/or callback scope inside the function body is not necessary. -##### `napi_async_execute_callback` +##### `napi_async_execute_callback` - + Function pointer used with functions that support asynchronous operations. Callback functions must satisfy the following signature: @@ -784,9 +784,9 @@ JavaScript or interact with JavaScript objects. Node-API calls should be in the `napi_async_complete_callback` instead. Do not use the `napi_env` parameter as it will likely result in execution of JavaScript. -##### `napi_async_complete_callback` +##### `napi_async_complete_callback` - + Function pointer used with functions that support asynchronous operations. Callback functions must satisfy the following signature: @@ -800,9 +800,9 @@ typedef void (*napi_async_complete_callback)(napi_env env, Unless for reasons discussed in [Object Lifetime Management][], creating a handle and/or callback scope inside the function body is not necessary. -##### `napi_threadsafe_function_call_js` +##### `napi_threadsafe_function_call_js` - + Function pointer used with asynchronous thread-safe function calls. The callback will be called on the main thread. Its purpose is to use a data item arriving @@ -844,9 +844,9 @@ typedef void (*napi_threadsafe_function_call_js)(napi_env env, Unless for reasons discussed in [Object Lifetime Management][], creating a handle and/or callback scope inside the function body is not necessary. -##### `napi_async_cleanup_hook` +##### `napi_async_cleanup_hook` - + Function pointer used with [`napi_add_async_cleanup_hook`][]. It will be called when the environment is being torn down. @@ -900,7 +900,7 @@ In order to retrieve this information [`napi_get_last_error_info`][] is provided which returns a `napi_extended_error_info` structure. The format of the `napi_extended_error_info` structure is as follows: - + ```c typedef struct napi_extended_error_info { @@ -923,9 +923,9 @@ Do not rely on the content or format of any of the extended information as it is not subject to SemVer and may change at any time. It is intended only for logging purposes. -##### `napi_get_last_error_info` +##### `napi_get_last_error_info` - + ```c napi_status @@ -1035,9 +1035,9 @@ is `'ERR_ERROR_1'` and a `TypeError` is being created the name will be: TypeError [ERR_ERROR_1] ``` -##### `napi_throw` +##### `napi_throw` - + ```c NAPI_EXTERN napi_status napi_throw(napi_env env, napi_value error); @@ -1050,9 +1050,9 @@ Returns `napi_ok` if the API succeeded. This API throws the JavaScript value provided. -##### `napi_throw_error` +##### `napi_throw_error` - + ```c NAPI_EXTERN napi_status napi_throw_error(napi_env env, @@ -1068,9 +1068,9 @@ Returns `napi_ok` if the API succeeded. This API throws a JavaScript `Error` with the text provided. -##### `napi_throw_type_error` +##### `napi_throw_type_error` - + ```c NAPI_EXTERN napi_status napi_throw_type_error(napi_env env, @@ -1086,9 +1086,9 @@ Returns `napi_ok` if the API succeeded. This API throws a JavaScript `TypeError` with the text provided. -##### `napi_throw_range_error` +##### `napi_throw_range_error` - + ```c NAPI_EXTERN napi_status napi_throw_range_error(napi_env env, @@ -1104,13 +1104,13 @@ Returns `napi_ok` if the API succeeded. This API throws a JavaScript `RangeError` with the text provided. -##### `node_api_throw_syntax_error` +##### `node_api_throw_syntax_error` - + - + -````c +```c NAPI_EXTERN napi_status node_api_throw_syntax_error(napi_env env, const char* code, const char* msg); @@ -1124,15 +1124,15 @@ Returns `napi_ok` if the API succeeded. This API throws a JavaScript `SyntaxError` with the text provided. -##### `napi_is_error` +##### `napi_is_error` - + ```c NAPI_EXTERN napi_status napi_is_error(napi_env env, napi_value value, bool* result); -```` +``` * `[in] env`: The environment that the API is invoked under. * `[in] value`: The `napi_value` to be checked. @@ -1143,9 +1143,9 @@ Returns `napi_ok` if the API succeeded. This API queries a `napi_value` to check if it represents an error object. -##### `napi_create_error` +##### `napi_create_error` - + ```c NAPI_EXTERN napi_status napi_create_error(napi_env env, @@ -1165,9 +1165,9 @@ Returns `napi_ok` if the API succeeded. This API returns a JavaScript `Error` with the text provided. -##### `napi_create_type_error` +##### `napi_create_type_error` - + ```c NAPI_EXTERN napi_status napi_create_type_error(napi_env env, @@ -1187,9 +1187,9 @@ Returns `napi_ok` if the API succeeded. This API returns a JavaScript `TypeError` with the text provided. -##### `napi_create_range_error` +##### `napi_create_range_error` - + ```c NAPI_EXTERN napi_status napi_create_range_error(napi_env env, @@ -1209,11 +1209,11 @@ Returns `napi_ok` if the API succeeded. This API returns a JavaScript `RangeError` with the text provided. -##### `node_api_create_syntax_error` +##### `node_api_create_syntax_error` - + - + ```c NAPI_EXTERN napi_status node_api_create_syntax_error(napi_env env, @@ -1233,9 +1233,9 @@ Returns `napi_ok` if the API succeeded. This API returns a JavaScript `SyntaxError` with the text provided. -##### `napi_get_and_clear_last_exception` +##### `napi_get_and_clear_last_exception` - + ```c napi_status napi_get_and_clear_last_exception(napi_env env, @@ -1249,9 +1249,9 @@ Returns `napi_ok` if the API succeeded. This API can be called even if there is a pending JavaScript exception. -##### `napi_is_exception_pending` +##### `napi_is_exception_pending` - + ```c napi_status napi_is_exception_pending(napi_env env, bool* result); @@ -1264,9 +1264,9 @@ Returns `napi_ok` if the API succeeded. This API can be called even if there is a pending JavaScript exception. -##### `napi_fatal_exception` +##### `napi_fatal_exception` - + ```c napi_status napi_fatal_exception(napi_env env, napi_value err); @@ -1283,9 +1283,9 @@ callback throws an exception with no way to recover. In the event of an unrecoverable error in a native addon, a fatal error can be thrown to immediately terminate the process. -##### `napi_fatal_error` +##### `napi_fatal_error` - + ```c NAPI_NO_RETURN void napi_fatal_error(const char* location, @@ -1396,9 +1396,9 @@ The methods available to open/close escapable scopes are The request to promote a handle is made through [`napi_escape_handle`][] which can only be called once. -##### `napi_open_handle_scope` +##### `napi_open_handle_scope` - + ```c NAPI_EXTERN napi_status napi_open_handle_scope(napi_env env, @@ -1412,9 +1412,9 @@ Returns `napi_ok` if the API succeeded. This API opens a new scope. -##### `napi_close_handle_scope` +##### `napi_close_handle_scope` - + ```c NAPI_EXTERN napi_status napi_close_handle_scope(napi_env env, @@ -1431,9 +1431,9 @@ reverse order from which they were created. This API can be called even if there is a pending JavaScript exception. -##### `napi_open_escapable_handle_scope` +##### `napi_open_escapable_handle_scope` - + ```c NAPI_EXTERN napi_status @@ -1449,9 +1449,9 @@ Returns `napi_ok` if the API succeeded. This API opens a new scope from which one object can be promoted to the outer scope. -##### `napi_close_escapable_handle_scope` +##### `napi_close_escapable_handle_scope` - + ```c NAPI_EXTERN napi_status @@ -1469,9 +1469,9 @@ reverse order from which they were created. This API can be called even if there is a pending JavaScript exception. -##### `napi_escape_handle` +##### `napi_escape_handle` - + ```c napi_status napi_escape_handle(napi_env env, @@ -1541,9 +1541,9 @@ run and the native memory pointed by the earlier persistent reference will not be freed. This can be avoided by calling `napi_delete_reference` in addition to `napi_reference_unref` when possible. -##### `napi_create_reference` +##### `napi_create_reference` - + ```c NAPI_EXTERN napi_status napi_create_reference(napi_env env, @@ -1563,9 +1563,9 @@ Returns `napi_ok` if the API succeeded. This API creates a new reference with the specified reference count to the `Object` passed in. -##### `napi_delete_reference` +##### `napi_delete_reference` - + ```c NAPI_EXTERN napi_status napi_delete_reference(napi_env env, napi_ref ref); @@ -1580,9 +1580,9 @@ This API deletes the reference passed in. This API can be called even if there is a pending JavaScript exception. -##### `napi_reference_ref` +##### `napi_reference_ref` - + ```c NAPI_EXTERN napi_status napi_reference_ref(napi_env env, @@ -1599,9 +1599,9 @@ Returns `napi_ok` if the API succeeded. This API increments the reference count for the reference passed in and returns the resulting reference count. -##### `napi_reference_unref` +##### `napi_reference_unref` - + ```c NAPI_EXTERN napi_status napi_reference_unref(napi_env env, @@ -1618,9 +1618,9 @@ Returns `napi_ok` if the API succeeded. This API decrements the reference count for the reference passed in and returns the resulting reference count. -##### `napi_get_reference_value` +##### `napi_get_reference_value` - + ```c NAPI_EXTERN napi_status napi_get_reference_value(napi_env env, @@ -1652,9 +1652,9 @@ Node-API provides functions for registering and un-registering such callbacks. When those callbacks are run, all resources that are being held by the addon should be freed up. -##### `napi_add_env_cleanup_hook` +##### `napi_add_env_cleanup_hook` - + ```c NODE_EXTERN napi_status napi_add_env_cleanup_hook(napi_env env, @@ -1679,9 +1679,9 @@ is being torn down anyway. For asynchronous cleanup, [`napi_add_async_cleanup_hook`][] is available. -##### `napi_remove_env_cleanup_hook` +##### `napi_remove_env_cleanup_hook` - + ```c NAPI_EXTERN napi_status napi_remove_env_cleanup_hook(napi_env env, @@ -1696,9 +1696,9 @@ need to be exact matches. The function must have originally been registered with `napi_add_env_cleanup_hook`, otherwise the process will abort. -##### `napi_add_async_cleanup_hook` +##### `napi_add_async_cleanup_hook` - + ```c NAPI_EXTERN napi_status napi_add_async_cleanup_hook( @@ -1728,9 +1728,9 @@ regardless of whether the hook has already been invoked. Typically, that happens when the resource for which this hook was added is being torn down anyway. -##### `napi_remove_async_cleanup_hook` +##### `napi_remove_async_cleanup_hook` - + ```c NAPI_EXTERN napi_status napi_remove_async_cleanup_hook( @@ -1882,9 +1882,9 @@ the `napi_value` in question is of the JavaScript type expected by the API. #### Enum types -##### `napi_key_collection_mode` +##### `napi_key_collection_mode` - + ```c typedef enum { @@ -1901,9 +1901,9 @@ Describes the `Keys/Properties` filter enums: object only. `napi_key_include_prototypes` will include all keys of the objects's prototype chain as well. -##### `napi_key_filter` +##### `napi_key_filter` - + ```c typedef enum { @@ -1918,9 +1918,9 @@ typedef enum { Property filter bits. They can be or'ed to build a composite filter. -##### `napi_key_conversion` +##### `napi_key_conversion` - + ```c typedef enum { @@ -1933,7 +1933,7 @@ typedef enum { strings. `napi_key_keep_numbers` will return numbers for integer indices. -##### `napi_valuetype` +##### `napi_valuetype` ```c typedef enum { @@ -1959,7 +1959,7 @@ In addition to types in that section, `napi_valuetype` can also represent A JavaScript value of type `napi_external` appears in JavaScript as a plain object such that no properties can be set on it, and no prototype. -##### `napi_typedarray_type` +##### `napi_typedarray_type` ```c typedef enum { @@ -1983,9 +1983,9 @@ Elements of this enum correspond to #### Object creation functions -##### `napi_create_array` +##### `napi_create_array` - + ```c napi_status napi_create_array(napi_env env, napi_value* result) @@ -2000,9 +2000,9 @@ This API returns a Node-API value corresponding to a JavaScript `Array` type. JavaScript arrays are described in [Section 22.1][] of the ECMAScript Language Specification. -##### `napi_create_array_with_length` +##### `napi_create_array_with_length` - + ```c napi_status napi_create_array_with_length(napi_env env, @@ -2027,9 +2027,9 @@ directly read and/or written via C, consider using JavaScript arrays are described in [Section 22.1][] of the ECMAScript Language Specification. -##### `napi_create_arraybuffer` +##### `napi_create_arraybuffer` - + ```c napi_status napi_create_arraybuffer(napi_env env, @@ -2059,9 +2059,9 @@ a typed array or `DataView` object would need to be created. JavaScript `ArrayBuffer` objects are described in [Section 24.1][] of the ECMAScript Language Specification. -##### `napi_create_buffer` +##### `napi_create_buffer` - + ```c napi_status napi_create_buffer(napi_env env, @@ -2081,9 +2081,9 @@ Returns `napi_ok` if the API succeeded. This API allocates a `node::Buffer` object. While this is still a fully-supported data structure, in most cases using a `TypedArray` will suffice. -##### `napi_create_buffer_copy` +##### `napi_create_buffer_copy` - + ```c napi_status napi_create_buffer_copy(napi_env env, @@ -2107,9 +2107,9 @@ This API allocates a `node::Buffer` object and initializes it with data copied from the passed-in buffer. While this is still a fully-supported data structure, in most cases using a `TypedArray` will suffice. -##### `napi_create_date` +##### `napi_create_date` - + ```c napi_status napi_create_date(napi_env env, @@ -2131,9 +2131,9 @@ This API allocates a JavaScript `Date` object. JavaScript `Date` objects are described in [Section 20.3][] of the ECMAScript Language Specification. -##### `napi_create_external` +##### `napi_create_external` - + ```c napi_status napi_create_external(napi_env env, @@ -2169,9 +2169,9 @@ The created value is not an object, and therefore does not support additional properties. It is considered a distinct value type: calling `napi_typeof()` with an external value yields `napi_external`. -##### `napi_create_external_arraybuffer` +##### `napi_create_external_arraybuffer` - + ```c napi_status @@ -2211,9 +2211,9 @@ object just created is ready for garbage collection. It is similar to JavaScript `ArrayBuffer`s are described in [Section 24.1][] of the ECMAScript Language Specification. -##### `napi_create_external_buffer` +##### `napi_create_external_buffer` - + ```c napi_status napi_create_external_buffer(napi_env env, @@ -2250,9 +2250,9 @@ object just created is ready for garbage collection. It is similar to For Node.js >=4 `Buffers` are `Uint8Array`s. -##### `napi_create_object` +##### `napi_create_object` - + ```c napi_status napi_create_object(napi_env env, napi_value* result) @@ -2269,9 +2269,9 @@ It is the equivalent of doing `new Object()` in JavaScript. The JavaScript `Object` type is described in [Section 6.1.7][] of the ECMAScript Language Specification. -##### `napi_create_symbol` +##### `napi_create_symbol` - + ```c napi_status napi_create_symbol(napi_env env, @@ -2291,11 +2291,11 @@ This API creates a JavaScript `symbol` value from a UTF8-encoded C string. The JavaScript `symbol` type is described in [Section 19.4][] of the ECMAScript Language Specification. -##### `node_api_symbol_for` +##### `node_api_symbol_for` - + - + ```c napi_status node_api_symbol_for(napi_env env, @@ -2320,9 +2320,9 @@ symbol will be created in the registry. The JavaScript `symbol` type is described in [Section 19.4][] of the ECMAScript Language Specification. -##### `napi_create_typedarray` +##### `napi_create_typedarray` - + ```c napi_status napi_create_typedarray(napi_env env, @@ -2355,9 +2355,9 @@ is raised. JavaScript `TypedArray` objects are described in [Section 22.2][] of the ECMAScript Language Specification. -##### `napi_create_dataview` +##### `napi_create_dataview` - + ```c napi_status napi_create_dataview(napi_env env, @@ -2389,9 +2389,9 @@ JavaScript `DataView` objects are described in #### Functions to convert from C types to Node-API -##### `napi_create_int32` +##### `napi_create_int32` - + ```c napi_status napi_create_int32(napi_env env, int32_t value, napi_value* result) @@ -2409,9 +2409,9 @@ This API is used to convert from the C `int32_t` type to the JavaScript The JavaScript `number` type is described in [Section 6.1.6][] of the ECMAScript Language Specification. -##### `napi_create_uint32` +##### `napi_create_uint32` - + ```c napi_status napi_create_uint32(napi_env env, uint32_t value, napi_value* result) @@ -2429,9 +2429,9 @@ This API is used to convert from the C `uint32_t` type to the JavaScript The JavaScript `number` type is described in [Section 6.1.6][] of the ECMAScript Language Specification. -##### `napi_create_int64` +##### `napi_create_int64` - + ```c napi_status napi_create_int64(napi_env env, int64_t value, napi_value* result) @@ -2452,9 +2452,9 @@ cannot be represented with full precision in JavaScript. Integer values outside the range of [`Number.MIN_SAFE_INTEGER`][] `-(2**53 - 1)` - [`Number.MAX_SAFE_INTEGER`][] `(2**53 - 1)` will lose precision. -##### `napi_create_double` +##### `napi_create_double` - + ```c napi_status napi_create_double(napi_env env, double value, napi_value* result) @@ -2472,9 +2472,9 @@ This API is used to convert from the C `double` type to the JavaScript The JavaScript `number` type is described in [Section 6.1.6][] of the ECMAScript Language Specification. -##### `napi_create_bigint_int64` +##### `napi_create_bigint_int64` - + ```c napi_status napi_create_bigint_int64(napi_env env, @@ -2490,9 +2490,9 @@ Returns `napi_ok` if the API succeeded. This API converts the C `int64_t` type to the JavaScript `BigInt` type. -##### `napi_create_bigint_uint64` +##### `napi_create_bigint_uint64` - + ```c napi_status napi_create_bigint_uint64(napi_env env, @@ -2508,9 +2508,9 @@ Returns `napi_ok` if the API succeeded. This API converts the C `uint64_t` type to the JavaScript `BigInt` type. -##### `napi_create_bigint_words` +##### `napi_create_bigint_words` - + ```c napi_status napi_create_bigint_words(napi_env env, @@ -2535,9 +2535,9 @@ value. The resulting `BigInt` is calculated as: (–1)`sign_bit` (`words[0]` × (264)0 + `words[1]` × (264)1 + …) -##### `napi_create_string_latin1` +##### `napi_create_string_latin1` - + ```c napi_status napi_create_string_latin1(napi_env env, @@ -2560,9 +2560,9 @@ string. The native string is copied. The JavaScript `string` type is described in [Section 6.1.4][] of the ECMAScript Language Specification. -##### `napi_create_string_utf16` +##### `napi_create_string_utf16` - + ```c napi_status napi_create_string_utf16(napi_env env, @@ -2585,9 +2585,9 @@ The native string is copied. The JavaScript `string` type is described in [Section 6.1.4][] of the ECMAScript Language Specification. -##### `napi_create_string_utf8` +##### `napi_create_string_utf8` - + ```c napi_status napi_create_string_utf8(napi_env env, @@ -2612,9 +2612,9 @@ The JavaScript `string` type is described in #### Functions to convert from Node-API to C types -##### `napi_get_array_length` +##### `napi_get_array_length` - + ```c napi_status napi_get_array_length(napi_env env, @@ -2634,9 +2634,9 @@ This API returns the length of an array. `Array` length is described in [Section 22.1.4.1][] of the ECMAScript Language Specification. -##### `napi_get_arraybuffer_info` +##### `napi_get_arraybuffer_info` - + ```c napi_status napi_get_arraybuffer_info(napi_env env, @@ -2664,9 +2664,9 @@ lifetime of the `ArrayBuffer`. It's also safe to use the returned data buffer within the same callback as long as there are no calls to other APIs that might trigger a GC. -##### `napi_get_buffer_info` +##### `napi_get_buffer_info` - + ```c napi_status napi_get_buffer_info(napi_env env, @@ -2689,9 +2689,9 @@ and its length. _Warning_: Use caution while using this API since the underlying data buffer's lifetime is not guaranteed if it's managed by the VM. -##### `napi_get_prototype` +##### `napi_get_prototype` - + ```c napi_status napi_get_prototype(napi_env env, @@ -2707,9 +2707,9 @@ napi_status napi_get_prototype(napi_env env, Returns `napi_ok` if the API succeeded. -##### `napi_get_typedarray_info` +##### `napi_get_typedarray_info` - + ```c napi_status napi_get_typedarray_info(napi_env env, @@ -2746,9 +2746,9 @@ Any of the out parameters may be `NULL` if that property is unneeded. _Warning_: Use caution while using this API since the underlying data buffer is managed by the VM. -##### `napi_get_dataview_info` +##### `napi_get_dataview_info` - + ```c napi_status napi_get_dataview_info(napi_env env, @@ -2775,9 +2775,9 @@ Any of the out parameters may be `NULL` if that property is unneeded. This API returns various properties of a `DataView`. -##### `napi_get_date_value` +##### `napi_get_date_value` - + ```c napi_status napi_get_date_value(napi_env env, @@ -2799,9 +2799,9 @@ in it returns `napi_date_expected`. This API returns the C double primitive of time value for the given JavaScript `Date`. -##### `napi_get_value_bool` +##### `napi_get_value_bool` - + ```c napi_status napi_get_value_bool(napi_env env, napi_value value, bool* result) @@ -2818,9 +2818,9 @@ passed in it returns `napi_boolean_expected`. This API returns the C boolean primitive equivalent of the given JavaScript `Boolean`. -##### `napi_get_value_double` +##### `napi_get_value_double` - + ```c napi_status napi_get_value_double(napi_env env, @@ -2839,9 +2839,9 @@ in it returns `napi_number_expected`. This API returns the C double primitive equivalent of the given JavaScript `number`. -##### `napi_get_value_bigint_int64` +##### `napi_get_value_bigint_int64` - + ```c napi_status napi_get_value_bigint_int64(napi_env env, @@ -2863,9 +2863,9 @@ returns `napi_bigint_expected`. This API returns the C `int64_t` primitive equivalent of the given JavaScript `BigInt`. If needed it will truncate the value, setting `lossless` to `false`. -##### `napi_get_value_bigint_uint64` +##### `napi_get_value_bigint_uint64` - + ```c napi_status napi_get_value_bigint_uint64(napi_env env, @@ -2887,9 +2887,9 @@ returns `napi_bigint_expected`. This API returns the C `uint64_t` primitive equivalent of the given JavaScript `BigInt`. If needed it will truncate the value, setting `lossless` to `false`. -##### `napi_get_value_bigint_words` +##### `napi_get_value_bigint_words` - + ```c napi_status napi_get_value_bigint_words(napi_env env, @@ -2914,9 +2914,9 @@ This API converts a single `BigInt` value into a sign bit, 64-bit little-endian array, and the number of elements in the array. `sign_bit` and `words` may be both set to `NULL`, in order to get only `word_count`. -##### `napi_get_value_external` +##### `napi_get_value_external` - + ```c napi_status napi_get_value_external(napi_env env, @@ -2934,9 +2934,9 @@ passed in it returns `napi_invalid_arg`. This API retrieves the external data pointer that was previously passed to `napi_create_external()`. -##### `napi_get_value_int32` +##### `napi_get_value_int32` - + ```c napi_status napi_get_value_int32(napi_env env, @@ -2962,9 +2962,9 @@ positive number becoming a negative number if the value is > 231 - 1. Non-finite number values (`NaN`, `+Infinity`, or `-Infinity`) set the result to zero. -##### `napi_get_value_int64` +##### `napi_get_value_int64` - + ```c napi_status napi_get_value_int64(napi_env env, @@ -2990,9 +2990,9 @@ precision. Non-finite number values (`NaN`, `+Infinity`, or `-Infinity`) set the result to zero. -##### `napi_get_value_string_latin1` +##### `napi_get_value_string_latin1` - + ```c napi_status napi_get_value_string_latin1(napi_env env, @@ -3018,9 +3018,9 @@ is passed in it returns `napi_string_expected`. This API returns the ISO-8859-1-encoded string corresponding the value passed in. -##### `napi_get_value_string_utf8` +##### `napi_get_value_string_utf8` - + ```c napi_status napi_get_value_string_utf8(napi_env env, @@ -3045,9 +3045,9 @@ is passed in it returns `napi_string_expected`. This API returns the UTF8-encoded string corresponding the value passed in. -##### `napi_get_value_string_utf16` +##### `napi_get_value_string_utf16` - + ```c napi_status napi_get_value_string_utf16(napi_env env, @@ -3072,9 +3072,9 @@ is passed in it returns `napi_string_expected`. This API returns the UTF16-encoded string corresponding the value passed in. -##### `napi_get_value_uint32` +##### `napi_get_value_uint32` - + ```c napi_status napi_get_value_uint32(napi_env env, @@ -3095,9 +3095,9 @@ This API returns the C primitive equivalent of the given `napi_value` as a #### Functions to get global instances -##### `napi_get_boolean` +##### `napi_get_boolean` - + ```c napi_status napi_get_boolean(napi_env env, bool value, napi_value* result) @@ -3113,9 +3113,9 @@ Returns `napi_ok` if the API succeeded. This API is used to return the JavaScript singleton object that is used to represent the given boolean value. -##### `napi_get_global` +##### `napi_get_global` - + ```c napi_status napi_get_global(napi_env env, napi_value* result) @@ -3128,9 +3128,9 @@ Returns `napi_ok` if the API succeeded. This API returns the `global` object. -##### `napi_get_null` +##### `napi_get_null` - + ```c napi_status napi_get_null(napi_env env, napi_value* result) @@ -3143,9 +3143,9 @@ Returns `napi_ok` if the API succeeded. This API returns the `null` object. -##### `napi_get_undefined` +##### `napi_get_undefined` - + ```c napi_status napi_get_undefined(napi_env env, napi_value* result) @@ -3171,9 +3171,9 @@ These APIs support doing one of the following: 2. Check the type of a JavaScript value. 3. Check for equality between two JavaScript values. -#### `napi_coerce_to_bool` +#### `napi_coerce_to_bool` - + ```c napi_status napi_coerce_to_bool(napi_env env, @@ -3190,9 +3190,9 @@ Returns `napi_ok` if the API succeeded. This API implements the abstract operation `ToBoolean()` as defined in [Section 7.1.2][] of the ECMAScript Language Specification. -#### `napi_coerce_to_number` +#### `napi_coerce_to_number` - + ```c napi_status napi_coerce_to_number(napi_env env, @@ -3211,9 +3211,9 @@ This API implements the abstract operation `ToNumber()` as defined in This function potentially runs JS code if the passed-in value is an object. -#### `napi_coerce_to_object` +#### `napi_coerce_to_object` - + ```c napi_status napi_coerce_to_object(napi_env env, @@ -3230,9 +3230,9 @@ Returns `napi_ok` if the API succeeded. This API implements the abstract operation `ToObject()` as defined in [Section 7.1.13][] of the ECMAScript Language Specification. -#### `napi_coerce_to_string` +#### `napi_coerce_to_string` - + ```c napi_status napi_coerce_to_string(napi_env env, @@ -3251,9 +3251,9 @@ This API implements the abstract operation `ToString()` as defined in This function potentially runs JS code if the passed-in value is an object. -#### `napi_typeof` +#### `napi_typeof` - + ```c napi_status napi_typeof(napi_env env, napi_value value, napi_valuetype* result) @@ -3278,9 +3278,9 @@ Specification. However, there are some differences: If `value` has a type that is invalid, an error is returned. -#### `napi_instanceof` +#### `napi_instanceof` - + ```c napi_status napi_instanceof(napi_env env, @@ -3301,9 +3301,9 @@ Returns `napi_ok` if the API succeeded. This API represents invoking the `instanceof` Operator on the object as defined in [Section 12.10.4][] of the ECMAScript Language Specification. -#### `napi_is_array` +#### `napi_is_array` - + ```c napi_status napi_is_array(napi_env env, napi_value value, bool* result) @@ -3318,9 +3318,9 @@ Returns `napi_ok` if the API succeeded. This API represents invoking the `IsArray` operation on the object as defined in [Section 7.2.2][] of the ECMAScript Language Specification. -#### `napi_is_arraybuffer` +#### `napi_is_arraybuffer` - + ```c napi_status napi_is_arraybuffer(napi_env env, napi_value value, bool* result) @@ -3334,9 +3334,9 @@ Returns `napi_ok` if the API succeeded. This API checks if the `Object` passed in is an array buffer. -#### `napi_is_buffer` +#### `napi_is_buffer` - + ```c napi_status napi_is_buffer(napi_env env, napi_value value, bool* result) @@ -3351,9 +3351,9 @@ Returns `napi_ok` if the API succeeded. This API checks if the `Object` passed in is a buffer. -#### `napi_is_date` +#### `napi_is_date` - + ```c napi_status napi_is_date(napi_env env, napi_value value, bool* result) @@ -3368,9 +3368,9 @@ Returns `napi_ok` if the API succeeded. This API checks if the `Object` passed in is a date. -#### `napi_is_error` +#### `napi_is_error` - + ```c napi_status napi_is_error(napi_env env, napi_value value, bool* result) @@ -3384,9 +3384,9 @@ Returns `napi_ok` if the API succeeded. This API checks if the `Object` passed in is an `Error`. -#### `napi_is_typedarray` +#### `napi_is_typedarray` - + ```c napi_status napi_is_typedarray(napi_env env, napi_value value, bool* result) @@ -3400,9 +3400,9 @@ Returns `napi_ok` if the API succeeded. This API checks if the `Object` passed in is a typed array. -#### `napi_is_dataview` +#### `napi_is_dataview` - + ```c napi_status napi_is_dataview(napi_env env, napi_value value, bool* result) @@ -3416,9 +3416,9 @@ Returns `napi_ok` if the API succeeded. This API checks if the `Object` passed in is a `DataView`. -#### `napi_strict_equals` +#### `napi_strict_equals` - + ```c napi_status napi_strict_equals(napi_env env, @@ -3437,9 +3437,9 @@ Returns `napi_ok` if the API succeeded. This API represents the invocation of the Strict Equality algorithm as defined in [Section 7.2.14][] of the ECMAScript Language Specification. -#### `napi_detach_arraybuffer` +#### `napi_detach_arraybuffer` - + ```c napi_status napi_detach_arraybuffer(napi_env env, @@ -3460,9 +3460,9 @@ that is, created with [`napi_create_external_arraybuffer`][]. This API represents the invocation of the `ArrayBuffer` detach operation as defined in [Section 24.1.1.3][] of the ECMAScript Language Specification. -#### `napi_is_detached_arraybuffer` +#### `napi_is_detached_arraybuffer` - + ```c napi_status napi_is_detached_arraybuffer(napi_env env, @@ -3624,9 +3624,9 @@ if (status != napi_ok) return status; #### Structures -##### `napi_property_attributes` +##### `napi_property_attributes` - + ```c typedef enum { @@ -3669,7 +3669,7 @@ They can be one or more of the following bitflags: * `napi_default_jsproperty`: Like a property set via assignment in JavaScript, the property is writable, enumerable, and configurable. -##### `napi_property_descriptor` +##### `napi_property_descriptor` ```c typedef struct { @@ -3717,9 +3717,9 @@ typedef struct { #### Functions -##### `napi_get_property_names` +##### `napi_get_property_names` - + ```c napi_status napi_get_property_names(napi_env env, @@ -3740,9 +3740,9 @@ This API returns the names of the enumerable properties of `object` as an array of strings. The properties of `object` whose key is a symbol will not be included. -##### `napi_get_all_property_names` +##### `napi_get_all_property_names` - + ```c napi_get_all_property_names(napi_env env, @@ -3768,9 +3768,9 @@ Returns `napi_ok` if the API succeeded. This API returns an array containing the names of the available properties of this object. -##### `napi_set_property` +##### `napi_set_property` - + ```c napi_status napi_set_property(napi_env env, @@ -3788,9 +3788,9 @@ Returns `napi_ok` if the API succeeded. This API set a property on the `Object` passed in. -##### `napi_get_property` +##### `napi_get_property` - + ```c napi_status napi_get_property(napi_env env, @@ -3808,9 +3808,9 @@ Returns `napi_ok` if the API succeeded. This API gets the requested property from the `Object` passed in. -##### `napi_has_property` +##### `napi_has_property` - + ```c napi_status napi_has_property(napi_env env, @@ -3828,9 +3828,9 @@ Returns `napi_ok` if the API succeeded. This API checks if the `Object` passed in has the named property. -##### `napi_delete_property` +##### `napi_delete_property` - + ```c napi_status napi_delete_property(napi_env env, @@ -3849,9 +3849,9 @@ Returns `napi_ok` if the API succeeded. This API attempts to delete the `key` own property from `object`. -##### `napi_has_own_property` +##### `napi_has_own_property` - + ```c napi_status napi_has_own_property(napi_env env, @@ -3871,9 +3871,9 @@ This API checks if the `Object` passed in has the named own property. `key` must be a `string` or a `symbol`, or an error will be thrown. Node-API will not perform any conversion between data types. -##### `napi_set_named_property` +##### `napi_set_named_property` - + ```c napi_status napi_set_named_property(napi_env env, @@ -3892,9 +3892,9 @@ Returns `napi_ok` if the API succeeded. This method is equivalent to calling [`napi_set_property`][] with a `napi_value` created from the string passed in as `utf8Name`. -##### `napi_get_named_property` +##### `napi_get_named_property` - + ```c napi_status napi_get_named_property(napi_env env, @@ -3913,9 +3913,9 @@ Returns `napi_ok` if the API succeeded. This method is equivalent to calling [`napi_get_property`][] with a `napi_value` created from the string passed in as `utf8Name`. -##### `napi_has_named_property` +##### `napi_has_named_property` - + ```c napi_status napi_has_named_property(napi_env env, @@ -3934,9 +3934,9 @@ Returns `napi_ok` if the API succeeded. This method is equivalent to calling [`napi_has_property`][] with a `napi_value` created from the string passed in as `utf8Name`. -##### `napi_set_element` +##### `napi_set_element` - + ```c napi_status napi_set_element(napi_env env, @@ -3954,9 +3954,9 @@ Returns `napi_ok` if the API succeeded. This API sets an element on the `Object` passed in. -##### `napi_get_element` +##### `napi_get_element` - + ```c napi_status napi_get_element(napi_env env, @@ -3974,9 +3974,9 @@ Returns `napi_ok` if the API succeeded. This API gets the element at the requested index. -##### `napi_has_element` +##### `napi_has_element` - + ```c napi_status napi_has_element(napi_env env, @@ -3995,9 +3995,9 @@ Returns `napi_ok` if the API succeeded. This API returns if the `Object` passed in has an element at the requested index. -##### `napi_delete_element` +##### `napi_delete_element` - + ```c napi_status napi_delete_element(napi_env env, @@ -4016,9 +4016,9 @@ Returns `napi_ok` if the API succeeded. This API attempts to delete the specified `index` from `object`. -##### `napi_define_properties` +##### `napi_define_properties` - + ```c napi_status napi_define_properties(napi_env env, @@ -4041,9 +4041,9 @@ this API will set the properties on the object one at a time, as defined by `DefineOwnProperty()` (described in [Section 9.1.6][] of the ECMA-262 specification). -##### `napi_object_freeze` +##### `napi_object_freeze` - + ```c napi_status napi_object_freeze(napi_env env, @@ -4063,9 +4063,9 @@ It also prevents the object's prototype from being changed. This is described in [Section 19.1.2.6](https://tc39.es/ecma262/#sec-object.freeze) of the ECMA-262 specification. -##### `napi_object_seal` +##### `napi_object_seal` - + ```c napi_status napi_object_seal(napi_env env, @@ -4106,9 +4106,9 @@ Any non-`NULL` data which is passed to this API via the `data` field of the whenever `object` is garbage-collected by passing both `object` and the data to [`napi_add_finalizer`][]. -#### `napi_call_function` +#### `napi_call_function` - + ```c NAPI_EXTERN napi_status napi_call_function(napi_env env, @@ -4174,9 +4174,9 @@ status = napi_get_value_int32(env, return_val, &result); if (status != napi_ok) return; ``` -#### `napi_create_function` +#### `napi_create_function` - + ```c napi_status napi_create_function(napi_env env, @@ -4253,9 +4253,9 @@ passing both the JavaScript function and the data to [`napi_add_finalizer`][]. JavaScript `Function`s are described in [Section 19.2][] of the ECMAScript Language Specification. -#### `napi_get_cb_info` +#### `napi_get_cb_info` - + ```c napi_status napi_get_cb_info(napi_env env, @@ -4287,9 +4287,9 @@ Returns `napi_ok` if the API succeeded. This method is used within a callback function to retrieve details about the call like the arguments and the `this` pointer from a given callback info. -#### `napi_get_new_target` +#### `napi_get_new_target` - + ```c napi_status napi_get_new_target(napi_env env, @@ -4306,9 +4306,9 @@ Returns `napi_ok` if the API succeeded. This API returns the `new.target` of the constructor call. If the current callback is not a constructor call, the result is `NULL`. -#### `napi_new_instance` +#### `napi_new_instance` - + ```c napi_status napi_new_instance(napi_env env, @@ -4539,9 +4539,9 @@ query(napi_env env, napi_callback_info info) { } ``` -#### `napi_define_class` +#### `napi_define_class` - + ```c napi_status napi_define_class(napi_env env, @@ -4609,9 +4609,9 @@ with the resulting JavaScript constructor (which is returned in the `result` parameter) and freed whenever the class is garbage-collected by passing both the JavaScript function and the data to [`napi_add_finalizer`][]. -#### `napi_wrap` +#### `napi_wrap` - + ```c napi_status napi_wrap(napi_env env, @@ -4670,9 +4670,9 @@ Calling `napi_wrap()` a second time on an object will return an error. To associate another native instance with the object, use `napi_remove_wrap()` first. -#### `napi_unwrap` +#### `napi_unwrap` - + ```c napi_status napi_unwrap(napi_env env, @@ -4695,9 +4695,9 @@ method or accessor, then the `this` argument to the callback is the wrapper object; the wrapped C++ instance that is the target of the call can be obtained then by calling `napi_unwrap()` on the wrapper object. -#### `napi_remove_wrap` +#### `napi_remove_wrap` - + ```c napi_status napi_remove_wrap(napi_env env, @@ -4716,9 +4716,9 @@ object `js_object` using `napi_wrap()` and removes the wrapping. If a finalize callback was associated with the wrapping, it will no longer be called when the JavaScript object becomes garbage-collected. -#### `napi_type_tag_object` +#### `napi_type_tag_object` - + ```c napi_status napi_type_tag_object(napi_env env, @@ -4740,9 +4740,9 @@ has the right type. If the object already has an associated type tag, this API will return `napi_invalid_arg`. -#### `napi_check_object_type_tag` +#### `napi_check_object_type_tag` - + ```c napi_status napi_check_object_type_tag(napi_env env, @@ -4764,9 +4764,9 @@ Compares the pointer given as `type_tag` with any that can be found on not match `type_tag`, then `result` is set to `false`. If a tag is found and it matches `type_tag`, then `result` is set to `true`. -#### `napi_add_finalizer` +#### `napi_add_finalizer` - + ```c napi_status napi_add_finalizer(napi_env env, @@ -4862,9 +4862,9 @@ will be invoked with a status value of `napi_cancelled`. The work should not be deleted before the `complete` callback invocation, even when it was cancelled. -#### `napi_create_async_work` +#### `napi_create_async_work` - + ```c napi_status napi_create_async_work(napi_env env, @@ -4906,9 +4906,9 @@ representative of the type of async work being performed. It is also recommended to apply namespacing to the identifier, e.g. by including the module name. See the [`async_hooks` documentation][async_hooks `type`] for more information. -#### `napi_delete_async_work` +#### `napi_delete_async_work` - + ```c napi_status napi_delete_async_work(napi_env env, @@ -4924,9 +4924,9 @@ This API frees a previously allocated work object. This API can be called even if there is a pending JavaScript exception. -#### `napi_queue_async_work` +#### `napi_queue_async_work` - + ```c napi_status napi_queue_async_work(napi_env env, @@ -4942,9 +4942,9 @@ This API requests that the previously allocated work be scheduled for execution. Once it returns successfully, this API must not be called again with the same `napi_async_work` item or the result will be undefined. -#### `napi_cancel_async_work` +#### `napi_cancel_async_work` - + ```c napi_status napi_cancel_async_work(napi_env env, @@ -4972,9 +4972,9 @@ scenario. When using any other asynchronous mechanism, the following APIs are necessary to ensure an asynchronous operation is properly tracked by the runtime. -#### `napi_async_init` +#### `napi_async_init` - + ```c napi_status napi_async_init(napi_env env, @@ -5010,9 +5010,9 @@ recommended as this will result poor results with `async_hooks` now required by the underlying `async_hooks` implementation in order to provide the linkage between async callbacks. -#### `napi_async_destroy` +#### `napi_async_destroy` - + ```c napi_status napi_async_destroy(napi_env env, @@ -5026,9 +5026,9 @@ Returns `napi_ok` if the API succeeded. This API can be called even if there is a pending JavaScript exception. -#### `napi_make_callback` +#### `napi_make_callback` - + ```c NAPI_EXTERN napi_status napi_make_callback(napi_env env, @@ -5074,9 +5074,9 @@ may be required when implementing custom async behavior that does not use Any `process.nextTick`s or Promises scheduled on the microtask queue by JavaScript during the callback are ran before returning back to C/C++. -#### `napi_open_callback_scope` +#### `napi_open_callback_scope` - + ```c NAPI_EXTERN napi_status napi_open_callback_scope(napi_env env, @@ -5101,9 +5101,9 @@ the stack the [`napi_open_callback_scope`][] and [`napi_close_callback_scope`][] functions can be used to open/close the required scope. -#### `napi_close_callback_scope` +#### `napi_close_callback_scope` - + ```c NAPI_EXTERN napi_status napi_close_callback_scope(napi_env env, @@ -5117,9 +5117,9 @@ This API can be called even if there is a pending JavaScript exception. ### Version management -#### `napi_get_node_version` +#### `napi_get_node_version` - + ```c typedef struct { @@ -5144,9 +5144,9 @@ value of [`process.release.name`][`process.release`]. The returned buffer is statically allocated and does not need to be freed. -#### `napi_get_version` +#### `napi_get_version` - + ```c napi_status napi_get_version(napi_env env, @@ -5174,9 +5174,9 @@ support it: ### Memory management -#### `napi_adjust_external_memory` +#### `napi_adjust_external_memory` - + ```c NAPI_EXTERN napi_status napi_adjust_external_memory(napi_env env, @@ -5253,9 +5253,9 @@ if (status != napi_ok) return NULL; deferred = NULL; ``` -#### `napi_create_promise` +#### `napi_create_promise` - + ```c napi_status napi_create_promise(napi_env env, @@ -5273,9 +5273,9 @@ Returns `napi_ok` if the API succeeded. This API creates a deferred object and a JavaScript promise. -#### `napi_resolve_deferred` +#### `napi_resolve_deferred` - + ```c napi_status napi_resolve_deferred(napi_env env, @@ -5296,9 +5296,9 @@ have been retained in order to be passed to this API. The deferred object is freed upon successful completion. -#### `napi_reject_deferred` +#### `napi_reject_deferred` - + ```c napi_status napi_reject_deferred(napi_env env, @@ -5319,9 +5319,9 @@ have been retained in order to be passed to this API. The deferred object is freed upon successful completion. -#### `napi_is_promise` +#### `napi_is_promise` - + ```c napi_status napi_is_promise(napi_env env, @@ -5339,9 +5339,9 @@ napi_status napi_is_promise(napi_env env, Node-API provides an API for executing a string containing JavaScript using the underlying JavaScript engine. -#### `napi_run_script` +#### `napi_run_script` - + ```c NAPI_EXTERN napi_status napi_run_script(napi_env env, @@ -5371,9 +5371,9 @@ the following caveats: Node-API provides a function for getting the current event loop associated with a specific `napi_env`. -#### `napi_get_uv_event_loop` +#### `napi_get_uv_event_loop` - + ```c NAPI_EXTERN napi_status napi_get_uv_event_loop(napi_env env, @@ -5507,9 +5507,9 @@ Neither does `napi_unref_threadsafe_function` mark the thread-safe functions as able to be destroyed nor does `napi_ref_threadsafe_function` prevent it from being destroyed. -#### `napi_create_threadsafe_function` +#### `napi_create_threadsafe_function` - + ```c NAPI_EXTERN napi_status @@ -5550,9 +5550,9 @@ napi_create_threadsafe_function(napi_env env, [`napi_threadsafe_function_call_js`][] provides more details. * `[out] result`: The asynchronous thread-safe JavaScript function. -#### `napi_get_threadsafe_function_context` +#### `napi_get_threadsafe_function_context` - + ```c NAPI_EXTERN napi_status @@ -5565,9 +5565,9 @@ napi_get_threadsafe_function_context(napi_threadsafe_function func, This API may be called from any thread which makes use of `func`. -#### `napi_call_threadsafe_function` +#### `napi_call_threadsafe_function` - + ```c NAPI_EXTERN napi_status @@ -5594,9 +5594,9 @@ added to the queue if the API returns `napi_ok`. This API may be called from any thread which makes use of `func`. -#### `napi_acquire_threadsafe_function` +#### `napi_acquire_threadsafe_function` - + ```c NAPI_EXTERN napi_status @@ -5613,9 +5613,9 @@ it. This API may be called from any thread which will start making use of `func`. -#### `napi_release_threadsafe_function` +#### `napi_release_threadsafe_function` - + ```c NAPI_EXTERN napi_status @@ -5639,9 +5639,9 @@ to any thread-safe APIs after having called this API has undefined results, as This API may be called from any thread which will stop making use of `func`. -#### `napi_ref_threadsafe_function` +#### `napi_ref_threadsafe_function` - + ```c NAPI_EXTERN napi_status @@ -5662,9 +5662,9 @@ being destroyed. `napi_acquire_threadsafe_function` and This API may only be called from the main thread. -#### `napi_unref_threadsafe_function` +#### `napi_unref_threadsafe_function` - + ```c NAPI_EXTERN napi_status @@ -5682,11 +5682,11 @@ This API may only be called from the main thread. ### Miscellaneous utilities -#### `node_api_get_module_file_name` +#### `node_api_get_module_file_name` - + - + ```c NAPI_EXTERN napi_status @@ -5705,7 +5705,7 @@ the add-on's file name during loading. [ABI Stability]: https://nodejs.org/en/docs/guides/abi-stability/ [AppVeyor]: https://www.appveyor.com -[C++ Addons]: (/api/addons) +[C++ Addons]: addons.md [CMake]: https://cmake.org [CMake.js]: https://github.com/cmake-js/cmake-js [ECMAScript Language Specification]: https://tc39.github.io/ecma262/ @@ -5752,7 +5752,7 @@ the add-on's file name during loading. [`Number.MIN_SAFE_INTEGER`]: https://tc39.github.io/ecma262/#sec-number.min_safe_integer [`Worker`]: worker_threads.md#class-worker [`async_hooks.executionAsyncResource()`]: async_hooks.md#async_hooksexecutionasyncresource -[`global`]: (/api/globals#global) +[`global`]: globals.md#global [`init` hooks]: async_hooks.md#initasyncid-type-triggerasyncid-resource [`napi_add_async_cleanup_hook`]: #napi_add_async_cleanup_hook [`napi_add_env_cleanup_hook`]: #napi_add_env_cleanup_hook @@ -5812,15 +5812,15 @@ the add-on's file name during loading. [`node_api.h`]: https://github.com/nodejs/node/blob/HEAD/src/node_api.h [`node_api_create_syntax_error`]: #node_api_create_syntax_error [`node_api_throw_syntax_error`]: #node_api_throw_syntax_error -[`process.release`]: (/api/process#processrelease) +[`process.release`]: process.md#processrelease [`uv_ref`]: https://docs.libuv.org/en/v1.x/handle.html#c.uv_ref [`uv_unref`]: https://docs.libuv.org/en/v1.x/handle.html#c.uv_unref [async_hooks `type`]: async_hooks.md#type -[context-aware addons]: (/api/addons#context-aware-addons) +[context-aware addons]: addons.md#context-aware-addons [docs]: https://github.com/nodejs/node-addon-api#api-documentation -[global scope]: (/api/globals) +[global scope]: globals.md [gyp-next]: https://github.com/nodejs/gyp-next -[module scope]: (/api/modules#the-module-scope) +[module scope]: modules.md#the-module-scope [node-gyp]: https://github.com/nodejs/node-gyp [node-pre-gyp]: https://github.com/mapbox/node-pre-gyp [prebuild]: https://github.com/prebuild/prebuild diff --git a/content/api/v18/navigation.json b/content/api/v18/navigation.json index e539466c9b..ed9d96628c 100644 --- a/content/api/v18/navigation.json +++ b/content/api/v18/navigation.json @@ -1,12 +1,6 @@ { "version": "v18", "items": [ - { - "slug": "/api/v18/addons/", - "title": "C addons", - "type": "module", - "name": "addons" - }, { "slug": "/api/v18/cluster/", "title": "Cluster", @@ -19,6 +13,24 @@ "type": "class", "name": "cluster" }, + { + "slug": "/api/v18/async_context/", + "title": "Asynchronous context tracking", + "type": "module", + "name": "async_context" + }, + { + "slug": "/api/v18/async_context/#asynclocalstorage", + "title": "AsyncLocalStorage", + "type": "class", + "name": "async_context" + }, + { + "slug": "/api/v18/async_context/#asyncresource", + "title": "AsyncResource", + "type": "class", + "name": "async_context" + }, { "slug": "/api/v18/async_hooks/", "title": "Async hooks", @@ -43,6 +55,12 @@ "type": "class", "name": "async_hooks" }, + { + "slug": "/api/v18/addons/", + "title": "C addons", + "type": "module", + "name": "addons" + }, { "slug": "/api/v18/assert/", "title": "Assert", @@ -103,30 +121,6 @@ "type": "class", "name": "buffer" }, - { - "slug": "/api/v18/async_context/", - "title": "Asynchronous context tracking", - "type": "module", - "name": "async_context" - }, - { - "slug": "/api/v18/async_context/#asynclocalstorage", - "title": "AsyncLocalStorage", - "type": "class", - "name": "async_context" - }, - { - "slug": "/api/v18/async_context/#asyncresource", - "title": "AsyncResource", - "type": "class", - "name": "async_context" - }, - { - "slug": "/api/v18/corepack/", - "title": "Corepack", - "type": "module", - "name": "corepack" - }, { "slug": "/api/v18/console/", "title": "Console", @@ -140,10 +134,16 @@ "name": "console" }, { - "slug": "/api/v18/console/#console", - "title": "Console", - "type": "class", - "name": "console" + "slug": "/api/v18/debugger/", + "title": "Debugger", + "type": "module", + "name": "debugger" + }, + { + "slug": "/api/v18/corepack/", + "title": "Corepack", + "type": "module", + "name": "corepack" }, { "slug": "/api/v18/crypto/", @@ -223,12 +223,6 @@ "type": "class", "name": "crypto" }, - { - "slug": "/api/v18/debugger/", - "title": "Debugger", - "type": "module", - "name": "debugger" - }, { "slug": "/api/v18/diagnostics_channel/", "title": "Diagnostics Channel", @@ -241,24 +235,6 @@ "type": "class", "name": "diagnostics_channel" }, - { - "slug": "/api/v18/dgram/", - "title": "UDPdatagram sockets", - "type": "module", - "name": "dgram" - }, - { - "slug": "/api/v18/dgram/#dgramsocket", - "title": "dgramSocket", - "type": "class", - "name": "dgram" - }, - { - "slug": "/api/v18/deprecations/", - "title": "Deprecated APIs", - "type": "module", - "name": "deprecations" - }, { "slug": "/api/v18/dns/", "title": "DNS", @@ -278,16 +254,22 @@ "name": "dns" }, { - "slug": "/api/v18/documentation/", - "title": "About this documentation", + "slug": "/api/v18/deprecations/", + "title": "Deprecated APIs", "type": "module", - "name": "documentation" + "name": "deprecations" }, { - "slug": "/api/v18/embedding/", - "title": "C embedder API", + "slug": "/api/v18/dgram/", + "title": "UDPdatagram sockets", "type": "module", - "name": "embedding" + "name": "dgram" + }, + { + "slug": "/api/v18/dgram/#dgramsocket", + "title": "dgramSocket", + "type": "class", + "name": "dgram" }, { "slug": "/api/v18/domain/", @@ -301,6 +283,54 @@ "type": "class", "name": "domain" }, + { + "slug": "/api/v18/events/", + "title": "Events", + "type": "module", + "name": "events" + }, + { + "slug": "/api/v18/events/#eventemitter", + "title": "EventEmitter", + "type": "class", + "name": "events" + }, + { + "slug": "/api/v18/events/#eventseventemitterasyncresource-extends-eventemitter", + "title": "eventsEventEmitterAsyncResource extends EventEmitter", + "type": "class", + "name": "events" + }, + { + "slug": "/api/v18/events/#event", + "title": "Event", + "type": "class", + "name": "events" + }, + { + "slug": "/api/v18/events/#eventtarget", + "title": "EventTarget", + "type": "class", + "name": "events" + }, + { + "slug": "/api/v18/events/#customevent", + "title": "CustomEvent", + "type": "class", + "name": "events" + }, + { + "slug": "/api/v18/events/#nodeeventtarget", + "title": "NodeEventTarget", + "type": "class", + "name": "events" + }, + { + "slug": "/api/v18/embedding/", + "title": "C embedder API", + "type": "module", + "name": "embedding" + }, { "slug": "/api/v18/esm/", "title": "ECMAScript modules", @@ -319,12 +349,6 @@ "type": "class", "name": "errors" }, - { - "slug": "/api/v18/errors/#error", - "title": "Error", - "type": "class", - "name": "errors" - }, { "slug": "/api/v18/errors/#assertionerror", "title": "AssertionError", @@ -373,12 +397,6 @@ "type": "class", "name": "globals" }, - { - "slug": "/api/v18/globals/#abortcontroller", - "title": "AbortController", - "type": "global", - "name": "globals" - }, { "slug": "/api/v18/globals/#abortsignal", "title": "AbortSignal", @@ -391,60 +409,24 @@ "type": "class", "name": "globals" }, - { - "slug": "/api/v18/globals/#blob", - "title": "Blob", - "type": "global", - "name": "globals" - }, { "slug": "/api/v18/globals/#buffer", "title": "Buffer", "type": "class", "name": "globals" }, - { - "slug": "/api/v18/globals/#buffer", - "title": "Buffer", - "type": "global", - "name": "globals" - }, { "slug": "/api/v18/globals/#bytelengthqueuingstrategy", "title": "ByteLengthQueuingStrategy", "type": "class", "name": "globals" }, - { - "slug": "/api/v18/globals/#clearimmediateimmediateobject", - "title": "clearImmediate", - "type": "global", - "name": "globals" - }, - { - "slug": "/api/v18/globals/#clearintervalintervalobject", - "title": "clearInterval", - "type": "global", - "name": "globals" - }, - { - "slug": "/api/v18/globals/#cleartimeouttimeoutobject", - "title": "clearTimeout", - "type": "global", - "name": "globals" - }, { "slug": "/api/v18/globals/#compressionstream", "title": "CompressionStream", "type": "class", "name": "globals" }, - { - "slug": "/api/v18/globals/#console", - "title": "console", - "type": "global", - "name": "globals" - }, { "slug": "/api/v18/globals/#countqueuingstrategy", "title": "CountQueuingStrategy", @@ -457,54 +439,6 @@ "type": "class", "name": "globals" }, - { - "slug": "/api/v18/globals/#event", - "title": "Event", - "type": "global", - "name": "globals" - }, - { - "slug": "/api/v18/globals/#eventtarget", - "title": "EventTarget", - "type": "global", - "name": "globals" - }, - { - "slug": "/api/v18/globals/#global", - "title": "global", - "type": "global", - "name": "globals" - }, - { - "slug": "/api/v18/globals/#messagechannel", - "title": "MessageChannel", - "type": "global", - "name": "globals" - }, - { - "slug": "/api/v18/globals/#messageevent", - "title": "MessageEvent", - "type": "global", - "name": "globals" - }, - { - "slug": "/api/v18/globals/#messageport", - "title": "MessagePort", - "type": "global", - "name": "globals" - }, - { - "slug": "/api/v18/globals/#process", - "title": "process", - "type": "global", - "name": "globals" - }, - { - "slug": "/api/v18/globals/#queuemicrotaskcallback", - "title": "queueMicrotask", - "type": "global", - "name": "globals" - }, { "slug": "/api/v18/globals/#readablebytestreamcontroller", "title": "ReadableByteStreamController", @@ -541,42 +475,6 @@ "type": "class", "name": "globals" }, - { - "slug": "/api/v18/globals/#setimmediatecallback-args", - "title": "setImmediate", - "type": "global", - "name": "globals" - }, - { - "slug": "/api/v18/globals/#setintervalcallback-delay-args", - "title": "setInterval", - "type": "global", - "name": "globals" - }, - { - "slug": "/api/v18/globals/#settimeoutcallback-delay-args", - "title": "setTimeout", - "type": "global", - "name": "globals" - }, - { - "slug": "/api/v18/globals/#structuredclonevalue-options", - "title": "structuredClone", - "type": "global", - "name": "globals" - }, - { - "slug": "/api/v18/globals/#domexception", - "title": "DOMException", - "type": "global", - "name": "globals" - }, - { - "slug": "/api/v18/globals/#textdecoder", - "title": "TextDecoder", - "type": "global", - "name": "globals" - }, { "slug": "/api/v18/globals/#textdecoderstream", "title": "TextDecoderStream", @@ -584,106 +482,40 @@ "name": "globals" }, { - "slug": "/api/v18/globals/#textencoder", - "title": "TextEncoder", - "type": "global", - "name": "globals" - }, - { - "slug": "/api/v18/globals/#textencoderstream", - "title": "TextEncoderStream", - "type": "class", - "name": "globals" - }, - { - "slug": "/api/v18/globals/#transformstream", - "title": "TransformStream", - "type": "class", - "name": "globals" - }, - { - "slug": "/api/v18/globals/#transformstreamdefaultcontroller", - "title": "TransformStreamDefaultController", - "type": "class", - "name": "globals" - }, - { - "slug": "/api/v18/globals/#url", - "title": "URL", - "type": "global", - "name": "globals" - }, - { - "slug": "/api/v18/globals/#urlsearchparams", - "title": "URLSearchParams", - "type": "global", - "name": "globals" - }, - { - "slug": "/api/v18/globals/#webassembly", - "title": "WebAssembly", - "type": "global", - "name": "globals" - }, - { - "slug": "/api/v18/globals/#writablestream", - "title": "WritableStream", - "type": "class", - "name": "globals" - }, - { - "slug": "/api/v18/globals/#writablestreamdefaultcontroller", - "title": "WritableStreamDefaultController", - "type": "class", - "name": "globals" - }, - { - "slug": "/api/v18/globals/#writablestreamdefaultwriter", - "title": "WritableStreamDefaultWriter", - "type": "class", - "name": "globals" - }, - { - "slug": "/api/v18/events/", - "title": "Events", - "type": "module", - "name": "events" - }, - { - "slug": "/api/v18/events/#eventemitter", - "title": "EventEmitter", + "slug": "/api/v18/globals/#textencoderstream", + "title": "TextEncoderStream", "type": "class", - "name": "events" + "name": "globals" }, { - "slug": "/api/v18/events/#eventseventemitterasyncresource-extends-eventemitter", - "title": "eventsEventEmitterAsyncResource extends EventEmitter", + "slug": "/api/v18/globals/#transformstream", + "title": "TransformStream", "type": "class", - "name": "events" + "name": "globals" }, { - "slug": "/api/v18/events/#event", - "title": "Event", + "slug": "/api/v18/globals/#transformstreamdefaultcontroller", + "title": "TransformStreamDefaultController", "type": "class", - "name": "events" + "name": "globals" }, { - "slug": "/api/v18/events/#eventtarget", - "title": "EventTarget", + "slug": "/api/v18/globals/#writablestream", + "title": "WritableStream", "type": "class", - "name": "events" + "name": "globals" }, { - "slug": "/api/v18/events/#customevent", - "title": "CustomEvent", + "slug": "/api/v18/globals/#writablestreamdefaultcontroller", + "title": "WritableStreamDefaultController", "type": "class", - "name": "events" + "name": "globals" }, { - "slug": "/api/v18/events/#nodeeventtarget", - "title": "NodeEventTarget", + "slug": "/api/v18/globals/#writablestreamdefaultwriter", + "title": "WritableStreamDefaultWriter", "type": "class", - "name": "events" + "name": "globals" }, { "slug": "/api/v18/fs/", @@ -739,6 +571,12 @@ "type": "class", "name": "fs" }, + { + "slug": "/api/v18/documentation/", + "title": "About this documentation", + "type": "module", + "name": "documentation" + }, { "slug": "/api/v18/https/", "title": "HTTPS", @@ -823,12 +661,6 @@ "type": "class", "name": "http2" }, - { - "slug": "/api/v18/intl/", - "title": "Internationalization support", - "type": "module", - "name": "intl" - }, { "slug": "/api/v18/inspector/", "title": "Inspector", @@ -884,10 +716,10 @@ "name": "http" }, { - "slug": "/api/v18/modules/", - "title": "CommonJS modules", + "slug": "/api/v18/intl/", + "title": "Internationalization support", "type": "module", - "name": "modules" + "name": "intl" }, { "slug": "/api/v18/module/", @@ -901,6 +733,12 @@ "type": "class", "name": "module" }, + { + "slug": "/api/v18/modules/", + "title": "CommonJS modules", + "type": "module", + "name": "modules" + }, { "slug": "/api/v18/n-api/", "title": "Node-API", @@ -955,6 +793,24 @@ "type": "module", "name": "path" }, + { + "slug": "/api/v18/policy/", + "title": "Policies", + "type": "module", + "name": "policy" + }, + { + "slug": "/api/v18/process/", + "title": "Process", + "type": "module", + "name": "process" + }, + { + "slug": "/api/v18/punycode/", + "title": "Punycode", + "type": "module", + "name": "punycode" + }, { "slug": "/api/v18/perf_hooks/", "title": "Performance measurement APIs", @@ -1009,60 +865,12 @@ "type": "class", "name": "perf_hooks" }, - { - "slug": "/api/v18/policy/", - "title": "Policies", - "type": "module", - "name": "policy" - }, - { - "slug": "/api/v18/punycode/", - "title": "Punycode", - "type": "module", - "name": "punycode" - }, - { - "slug": "/api/v18/process/", - "title": "Process", - "type": "module", - "name": "process" - }, { "slug": "/api/v18/querystring/", "title": "Query string", "type": "module", "name": "querystring" }, - { - "slug": "/api/v18/readline/", - "title": "Readline", - "type": "module", - "name": "readline" - }, - { - "slug": "/api/v18/readline/#interfaceconstructor", - "title": "InterfaceConstructor", - "type": "class", - "name": "readline" - }, - { - "slug": "/api/v18/readline/#readlinepromisesinterface", - "title": "readlinePromisesInterface", - "type": "class", - "name": "readline" - }, - { - "slug": "/api/v18/readline/#readlinepromisesreadline", - "title": "readlinePromisesReadline", - "type": "class", - "name": "readline" - }, - { - "slug": "/api/v18/readline/#readlineinterface", - "title": "readlineInterface", - "type": "class", - "name": "readline" - }, { "slug": "/api/v18/repl/", "title": "REPL", @@ -1105,18 +913,6 @@ "type": "class", "name": "stream" }, - { - "slug": "/api/v18/stream/#streamwritable", - "title": "streamWritable", - "type": "class", - "name": "stream" - }, - { - "slug": "/api/v18/stream/#streamreadable", - "title": "streamReadable", - "type": "class", - "name": "stream" - }, { "slug": "/api/v18/stream/#streamreadable", "title": "streamReadable", @@ -1129,18 +925,6 @@ "type": "class", "name": "stream" }, - { - "slug": "/api/v18/stream/#streamduplex", - "title": "streamDuplex", - "type": "class", - "name": "stream" - }, - { - "slug": "/api/v18/stream/#streamtransform", - "title": "streamTransform", - "type": "class", - "name": "stream" - }, { "slug": "/api/v18/stream/#streamtransform", "title": "streamTransform", @@ -1165,6 +949,12 @@ "type": "module", "name": "test" }, + { + "slug": "/api/v18/test/#tapstream", + "title": "TapStream", + "type": "class", + "name": "test" + }, { "slug": "/api/v18/test/#testcontext", "title": "TestContext", @@ -1231,6 +1021,36 @@ "type": "module", "name": "tracing" }, + { + "slug": "/api/v18/readline/", + "title": "Readline", + "type": "module", + "name": "readline" + }, + { + "slug": "/api/v18/readline/#interfaceconstructor", + "title": "InterfaceConstructor", + "type": "class", + "name": "readline" + }, + { + "slug": "/api/v18/readline/#readlinepromisesinterface", + "title": "readlinePromisesInterface", + "type": "class", + "name": "readline" + }, + { + "slug": "/api/v18/readline/#readlinepromisesreadline", + "title": "readlinePromisesReadline", + "type": "class", + "name": "readline" + }, + { + "slug": "/api/v18/readline/#readlineinterface", + "title": "readlineInterface", + "type": "class", + "name": "readline" + }, { "slug": "/api/v18/tty/", "title": "TTY", @@ -1345,18 +1165,6 @@ "type": "class", "name": "vm" }, - { - "slug": "/api/v18/wasi/", - "title": "WebAssembly System Interface ", - "type": "module", - "name": "wasi" - }, - { - "slug": "/api/v18/wasi/#wasi", - "title": "WASI", - "type": "class", - "name": "wasi" - }, { "slug": "/api/v18/webcrypto/", "title": "Web Crypto API", @@ -1495,6 +1303,36 @@ "type": "class", "name": "webcrypto" }, + { + "slug": "/api/v18/worker_threads/", + "title": "Worker threads", + "type": "module", + "name": "worker_threads" + }, + { + "slug": "/api/v18/worker_threads/#broadcastchannel-extends-eventtarget", + "title": "BroadcastChannel extends EventTarget", + "type": "class", + "name": "worker_threads" + }, + { + "slug": "/api/v18/worker_threads/#messagechannel", + "title": "MessageChannel", + "type": "class", + "name": "worker_threads" + }, + { + "slug": "/api/v18/worker_threads/#messageport", + "title": "MessagePort", + "type": "class", + "name": "worker_threads" + }, + { + "slug": "/api/v18/worker_threads/#worker", + "title": "Worker", + "type": "class", + "name": "worker_threads" + }, { "slug": "/api/v18/webstreams/", "title": "Web Streams API", @@ -1604,34 +1442,16 @@ "name": "webstreams" }, { - "slug": "/api/v18/worker_threads/", - "title": "Worker threads", + "slug": "/api/v18/wasi/", + "title": "WebAssembly System Interface ", "type": "module", - "name": "worker_threads" - }, - { - "slug": "/api/v18/worker_threads/#broadcastchannel-extends-eventtarget", - "title": "BroadcastChannel extends EventTarget", - "type": "class", - "name": "worker_threads" - }, - { - "slug": "/api/v18/worker_threads/#messagechannel", - "title": "MessageChannel", - "type": "class", - "name": "worker_threads" - }, - { - "slug": "/api/v18/worker_threads/#messageport", - "title": "MessagePort", - "type": "class", - "name": "worker_threads" + "name": "wasi" }, { - "slug": "/api/v18/worker_threads/#worker", - "title": "Worker", + "slug": "/api/v18/wasi/#wasi", + "title": "WASI", "type": "class", - "name": "worker_threads" + "name": "wasi" }, { "slug": "/api/v18/zlib/", diff --git a/content/api/v18/net.en.md b/content/api/v18/net.en.md index 93302c4703..c3d6d0b659 100644 --- a/content/api/v18/net.en.md +++ b/content/api/v18/net.en.md @@ -2,17 +2,17 @@ title: 'net' displayTitle: 'Net' category: 'api' -editPage: 'https://github.com/nodejs/node/blob/v18.8.0/doc/api/net.md' +editPage: 'https://github.com/nodejs/node/blob/v18.9.0/doc/api/net.md' version: 'v18' --- - + - + - + The `node:net` module provides an asynchronous network API for creating stream-based TCP or [IPC][] servers ([`net.createServer()`][]) and clients @@ -62,26 +62,26 @@ net.createServer().listen( path.join('\\\\?\\pipe', process.cwd(), 'myctl')); ``` -### `net.BlockList` +### `net.BlockList` - + The `BlockList` object can be used with some network APIs to specify rules for disabling inbound or outbound access to specific IP addresses, IP ranges, or IP subnets. -#### `blockList.addAddress(address[, type])` +#### `blockList.addAddress(address[, type])` - + * `address` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`net.SocketAddress`](/api/net#netsocketaddress) An IPv4 or IPv6 address. * `type` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) Either `'ipv4'` or `'ipv6'`. **Default:** `'ipv4'`. Adds a rule to block the given IP address. -#### `blockList.addRange(start, end[, type])` +#### `blockList.addRange(start, end[, type])` - + * `start` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`net.SocketAddress`](/api/net#netsocketaddress) The starting IPv4 or IPv6 address in the range. @@ -91,9 +91,9 @@ Adds a rule to block the given IP address. Adds a rule to block a range of IP addresses from `start` (inclusive) to `end` (inclusive). -#### `blockList.addSubnet(net, prefix[, type])` +#### `blockList.addSubnet(net, prefix[, type])` - + * `net` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`net.SocketAddress`](/api/net#netsocketaddress) The network IPv4 or IPv6 address. * `prefix` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The number of CIDR prefix bits. For IPv4, this @@ -103,9 +103,9 @@ Adds a rule to block a range of IP addresses from `start` (inclusive) to Adds a rule to block a range of IP addresses specified as a subnet mask. -#### `blockList.check(address[, type])` +#### `blockList.check(address[, type])` - + * `address` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`net.SocketAddress`](/api/net#netsocketaddress) The IP address to check * `type` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) Either `'ipv4'` or `'ipv6'`. **Default:** `'ipv4'`. @@ -129,21 +129,21 @@ console.log(blockList.check('::ffff:7b7b:7b7b', 'ipv6')); // Prints: true console.log(blockList.check('::ffff:123.123.123.123', 'ipv6')); // Prints: true ``` -#### `blockList.rules` +#### `blockList.rules` - + * Type: string\[] The list of rules added to the blocklist. -### `net.SocketAddress` +### `net.SocketAddress` - + -#### `new net.SocketAddress([options])` +#### `new net.SocketAddress([options])` - + * `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) * `address` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The network address as either an IPv4 or IPv6 string. @@ -154,39 +154,39 @@ The list of rules added to the blocklist. * `flowlabel` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) An IPv6 flow-label used only if `family` is `'ipv6'`. * `port` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) An IP port. -#### `socketaddress.address` +#### `socketaddress.address` - + * Type [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) -#### `socketaddress.family` +#### `socketaddress.family` - + * Type [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) Either `'ipv4'` or `'ipv6'`. -#### `socketaddress.flowlabel` +#### `socketaddress.flowlabel` - + * Type [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) -#### `socketaddress.port` +#### `socketaddress.port` - + * Type [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) -### `net.Server` +### `net.Server` - + * Extends: [`EventEmitter`](/api/events#eventemitter) This class is used to create a TCP or [IPC][] server. -#### `new net.Server([options][, connectionListener])` +#### `new net.Server([options][, connectionListener])` * `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) See [`net.createServer([options][, connectionListener])`][`net.createServer()`]. @@ -196,25 +196,25 @@ This class is used to create a TCP or [IPC][] server. `net.Server` is an [`EventEmitter`][] with the following events: -#### `'close'` +#### `'close'` - + Emitted when the server closes. If connections exist, this event is not emitted until all connections are ended. -#### `'connection'` +#### `'connection'` - + * [`net.Socket`](/api/net#netsocket) The connection object Emitted when a new connection is made. `socket` is an instance of `net.Socket`. -#### `'error'` +#### `'error'` - + * [`Error`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error) @@ -223,15 +223,15 @@ event will **not** be emitted directly following this event unless [`server.close()`][] is manually called. See the example in discussion of [`server.listen()`][]. -#### `'listening'` +#### `'listening'` - + Emitted when the server has been bound after calling [`server.listen()`][]. -#### `'drop'` +#### `'drop'` - + When the number of connections reaches the threshold of `server.maxConnections`, the server will drop new connections and emit `'drop'` event instead. If it is a @@ -245,16 +245,16 @@ TCP server, the argument is as follows, otherwise the argument is `undefined`. * `remotePort` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Remote port. * `remoteFamily` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) Remote IP family. `'IPv4'` or `'IPv6'`. -#### `server.address()` +#### `server.address()` - + * Returns: [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`null`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type) Returns the bound `address`, the address `family` name, and `port` of the server as reported by the operating system if listening on an IP socket (useful to find which port was assigned when getting an OS-assigned address): -`{ port: 12346, family: 'IPv4', address: '127.0.0.1' }`. +````{ port: 12346, family: 'IPv4', address: '127.0.0.1' }````. For a server listening on a pipe or Unix domain socket, the name is returned as a string. @@ -276,9 +276,9 @@ server.listen(() => { `server.address()` returns `null` before the `'listening'` event has been emitted or after calling `server.close()`. -#### `server.close([callback])` +#### `server.close([callback])` - + * `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) Called when the server is closed. * Returns: [`net.Server`](/api/net#netserver) @@ -290,9 +290,9 @@ The optional `callback` will be called once the `'close'` event occurs. Unlike that event, it will be called with an `Error` as its only argument if the server was not open when it was closed. -#### `server.getConnections(callback)` +#### `server.getConnections(callback)` - + * `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) * Returns: [`net.Server`](/api/net#netserver) @@ -302,7 +302,7 @@ when sockets were sent to forks. Callback should take two arguments `err` and `count`. -#### `server.listen()` +#### `server.listen()` Start a server listening for connections. A `net.Server` can be a TCP or an [IPC][] server depending on what it listens to. @@ -349,9 +349,9 @@ server.on('error', (e) => { }); ``` -##### `server.listen(handle[, backlog][, callback])` +##### `server.listen(handle[, backlog][, callback])` - + * `handle` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) * `backlog` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Common parameter of [`server.listen()`][] functions @@ -367,9 +367,9 @@ valid file descriptor. Listening on a file descriptor is not supported on Windows. -##### `server.listen(options[, callback])` +##### `server.listen(options[, callback])` - + * `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) Required. Supports the following properties: * `port` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) @@ -433,9 +433,9 @@ server.listen({ controller.abort(); ``` -##### `server.listen(path[, backlog][, callback])` +##### `server.listen(path[, backlog][, callback])` - + * `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) Path the server should listen to. See [Identifying paths for IPC connections][]. @@ -445,9 +445,9 @@ controller.abort(); Start an [IPC][] server listening for connections on the given `path`. -##### `server.listen([port[, host[, backlog]]][, callback])` +##### `server.listen([port[, host[, backlog]]][, callback])` - + * `port` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) * `host` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) @@ -469,15 +469,15 @@ In most operating systems, listening to the [unspecified IPv6 address][] (`::`) may cause the `net.Server` to also listen on the [unspecified IPv4 address][] (`0.0.0.0`). -#### `server.listening` +#### `server.listening` - + * [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) Indicates whether or not the server is listening for connections. -#### `server.maxConnections` +#### `server.maxConnections` - + * [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) @@ -487,9 +487,9 @@ high. It is not recommended to use this option once a socket has been sent to a child with [`child_process.fork()`][]. -#### `server.ref()` +#### `server.ref()` - + * Returns: [`net.Server`](/api/net#netserver) @@ -497,9 +497,9 @@ Opposite of `unref()`, calling `ref()` on a previously `unref`ed server will _not_ let the program exit if it's the only server left (the default behavior). If the server is `ref`ed calling `ref()` again will have no effect. -#### `server.unref()` +#### `server.unref()` - + * Returns: [`net.Server`](/api/net#netserver) @@ -507,9 +507,9 @@ Calling `unref()` on a server will allow the program to exit if this is the only active server in the event system. If the server is already `unref`ed calling `unref()` again will have no effect. -### `net.Socket` +### `net.Socket` - + * Extends: [`stream.Duplex`](/api/stream#streamduplex) @@ -526,9 +526,9 @@ is received. For example, it is passed to the listeners of a [`'connection'`][] event emitted on a [`net.Server`][], so the user can use it to interact with the client. -#### `new net.Socket([options])` +#### `new net.Socket([options])` - + * `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) Available options are: * `fd` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) If specified, wrap around an existing socket with @@ -550,25 +550,25 @@ Creates a new socket object. The newly created socket can be either a TCP socket or a streaming [IPC][] endpoint, depending on what it [`connect()`][`socket.connect()`] to. -#### `'close'` +#### `'close'` - + * `hadError` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) `true` if the socket had a transmission error. Emitted once the socket is fully closed. The argument `hadError` is a boolean which says if the socket was closed due to a transmission error. -#### `'connect'` +#### `'connect'` - + Emitted when a socket connection is successfully established. See [`net.createConnection()`][]. -#### `'data'` +#### `'data'` - + * [`Buffer`](/api/buffer#buffer) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) @@ -578,17 +578,17 @@ Emitted when data is received. The argument `data` will be a `Buffer` or The data will be lost if there is no listener when a `Socket` emits a `'data'` event. -#### `'drain'` +#### `'drain'` - + Emitted when the write buffer becomes empty. Can be used to throttle uploads. See also: the return values of `socket.write()`. -#### `'end'` +#### `'end'` - + Emitted when the other end of the socket signals the end of transmission, thus ending the readable side of the socket. @@ -601,18 +601,18 @@ allowing the user to write arbitrary amounts of data. The user must call [`end()`][`socket.end()`] explicitly to close the connection (i.e. sending a FIN packet back). -#### `'error'` +#### `'error'` - + * [`Error`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error) Emitted when an error occurs. The `'close'` event will be called directly following this event. -#### `'lookup'` +#### `'lookup'` - + Emitted after resolving the host name but before connecting. Not applicable to Unix sockets. @@ -622,38 +622,38 @@ Not applicable to Unix sockets. * `family` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) | [`null`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type) The address type. See [`dns.lookup()`][]. * `host` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The host name. -#### `'ready'` +#### `'ready'` - + Emitted when a socket is ready to be used. Triggered immediately after `'connect'`. -#### `'timeout'` +#### `'timeout'` - + Emitted if the socket times out from inactivity. This is only to notify that the socket has been idle. The user must manually close the connection. See also: [`socket.setTimeout()`][]. -#### `socket.address()` +#### `socket.address()` - + * Returns: [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) Returns the bound `address`, the address `family` name and `port` of the socket as reported by the operating system: -`{ port: 12346, family: 'IPv4', address: '127.0.0.1' }` +````{ port: 12346, family: 'IPv4', address: '127.0.0.1' }```` -#### `socket.bufferSize` +#### `socket.bufferSize` - + - + * [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) @@ -672,23 +672,23 @@ Users who experience large or growing `bufferSize` should attempt to "throttle" the data flows in their program with [`socket.pause()`][] and [`socket.resume()`][]. -#### `socket.bytesRead` +#### `socket.bytesRead` - + * [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The amount of received bytes. -#### `socket.bytesWritten` +#### `socket.bytesWritten` - + * [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The amount of bytes sent. -#### `socket.connect()` +#### `socket.connect()` Initiate a connection on a given socket. @@ -712,9 +712,9 @@ This function should only be used for reconnecting a socket after `'close'` has been emitted or otherwise it may lead to undefined behavior. -##### `socket.connect(options[, connectListener])` +##### `socket.connect(options[, connectListener])` - + * `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) * `connectListener` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) Common parameter of [`socket.connect()`][] @@ -758,7 +758,7 @@ For both types, available `options` include: The socket will emit events like `'error'`, `'end'`, and `'close'` as usual. Methods like `pause()` and `resume()` will also behave as expected. - * `buffer` {Buffer|Uint8Array|Function} Either a reusable chunk of memory to + * `buffer` [`Buffer`](/api/buffer#buffer) | [`Uint8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array) | [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) Either a reusable chunk of memory to use for storing incoming data or a function that returns such. * `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) This function is called for every chunk of incoming data. Two arguments are passed to it: the number of bytes written to @@ -783,7 +783,7 @@ net.connect({ }); ``` -##### `socket.connect(path[, connectListener])` +##### `socket.connect(path[, connectListener])` * `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) Path the client should connect to. See [Identifying paths for IPC connections][]. @@ -795,11 +795,11 @@ Initiate an [IPC][] connection on the given socket. Alias to [`socket.connect(options[, connectListener])`][`socket.connect(options)`] -called with `{ path: path }` as `options`. +called with ````{ path: path }```` as `options`. -##### `socket.connect(port[, host][, connectListener])` +##### `socket.connect(port[, host][, connectListener])` - + * `port` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Port the client should connect to. * `host` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) Host the client should connect to. @@ -811,11 +811,11 @@ Initiate a TCP connection on the given socket. Alias to [`socket.connect(options[, connectListener])`][`socket.connect(options)`] -called with `{port: port, host: host}` as `options`. +called with ````{port: port, host: host}```` as `options`. -#### `socket.connecting` +#### `socket.connecting` - + * [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) @@ -827,9 +827,9 @@ that the [`socket.connect(options[, connectListener])`][`socket.connect(options)`] callback is a listener for the `'connect'` event. -#### `socket.destroy([error])` +#### `socket.destroy([error])` - + * `error` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) * Returns: [`net.Socket`](/api/net#netsocket) @@ -839,18 +839,18 @@ Destroys the stream and closes the connection. See [`writable.destroy()`][] for further details. -#### `socket.destroyed` +#### `socket.destroyed` * [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) Indicates if the connection is destroyed or not. Once a connection is destroyed no further data can be transferred using it. See [`writable.destroyed`][] for further details. -#### `socket.end([data[, encoding]][, callback])` +#### `socket.end([data[, encoding]][, callback])` - + -* `data` {string|Buffer|Uint8Array} +* `data` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`Uint8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array) * `encoding` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) Only used when data is `string`. **Default:** `'utf8'`. * `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) Optional callback for when the socket is finished. * Returns: [`net.Socket`](/api/net#netsocket) The socket itself. @@ -860,9 +860,9 @@ server will still send some data. See [`writable.end()`][] for further details. -#### `socket.localAddress` +#### `socket.localAddress` - + * [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) @@ -871,32 +871,32 @@ connecting on. For example, in a server listening on `'0.0.0.0'`, if a client connects on `'192.168.1.1'`, the value of `socket.localAddress` would be `'192.168.1.1'`. -#### `socket.localPort` +#### `socket.localPort` - + * [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The numeric representation of the local port. For example, `80` or `21`. -#### `socket.localFamily` +#### `socket.localFamily` - + * [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The string representation of the local IP family. `'IPv4'` or `'IPv6'`. -#### `socket.pause()` +#### `socket.pause()` * Returns: [`net.Socket`](/api/net#netsocket) The socket itself. Pauses the reading of data. That is, [`'data'`][] events will not be emitted. Useful to throttle back an upload. -#### `socket.pending` +#### `socket.pending` - + * [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) @@ -904,9 +904,9 @@ This is `true` if the socket is not connected yet, either because `.connect()` has not yet been called or because it is still in the process of connecting (see [`socket.connecting`][]). -#### `socket.ref()` +#### `socket.ref()` - + * Returns: [`net.Socket`](/api/net#netsocket) The socket itself. @@ -914,9 +914,9 @@ Opposite of `unref()`, calling `ref()` on a previously `unref`ed socket will _not_ let the program exit if it's the only socket left (the default behavior). If the socket is `ref`ed calling `ref` again will have no effect. -#### `socket.remoteAddress` +#### `socket.remoteAddress` - + * [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) @@ -924,25 +924,25 @@ The string representation of the remote IP address. For example, `'74.125.127.100'` or `'2001:4860:a005::68'`. Value may be `undefined` if the socket is destroyed (for example, if the client disconnected). -#### `socket.remoteFamily` +#### `socket.remoteFamily` - + * [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The string representation of the remote IP family. `'IPv4'` or `'IPv6'`. -#### `socket.remotePort` +#### `socket.remotePort` - + * [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The numeric representation of the remote port. For example, `80` or `21`. -#### `socket.resetAndDestroy()` +#### `socket.resetAndDestroy()` - + * Returns: [`net.Socket`](/api/net#netsocket) @@ -951,15 +951,15 @@ If this TCP socket is in connecting status, it will send an RST packet and destr Otherwise, it will call `socket.destroy` with an `ERR_SOCKET_CLOSED` Error. If this is not a TCP socket (for example, a pipe), calling this method will immediately throw an `ERR_INVALID_HANDLE_TYPE` Error. -#### `socket.resume()` +#### `socket.resume()` * Returns: [`net.Socket`](/api/net#netsocket) The socket itself. Resumes reading after a call to [`socket.pause()`][]. -#### `socket.setEncoding([encoding])` +#### `socket.setEncoding([encoding])` - + * `encoding` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) * Returns: [`net.Socket`](/api/net#netsocket) The socket itself. @@ -967,9 +967,9 @@ Resumes reading after a call to [`socket.pause()`][]. Set the encoding for the socket as a [Readable Stream][]. See [`readable.setEncoding()`][] for more information. -#### `socket.setKeepAlive([enable][, initialDelay])` +#### `socket.setKeepAlive([enable][, initialDelay])` - + * `enable` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) **Default:** `false` * `initialDelay` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) **Default:** `0` @@ -990,9 +990,9 @@ Enabling the keep-alive functionality will set the following socket options: * `TCP_KEEPCNT=10` * `TCP_KEEPINTVL=1` -#### `socket.setNoDelay([noDelay])` +#### `socket.setNoDelay([noDelay])` - + * `noDelay` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) **Default:** `true` * Returns: [`net.Socket`](/api/net#netsocket) The socket itself. @@ -1008,9 +1008,9 @@ Passing `true` for `noDelay` or not passing an argument will disable Nagle's algorithm for the socket. Passing `false` for `noDelay` will enable Nagle's algorithm. -#### `socket.setTimeout(timeout[, callback])` +#### `socket.setTimeout(timeout[, callback])` - + * `timeout` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) * `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) @@ -1036,18 +1036,18 @@ If `timeout` is 0, then the existing idle timeout is disabled. The optional `callback` parameter will be added as a one-time listener for the [`'timeout'`][] event. -#### `socket.timeout` +#### `socket.timeout` - + * [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) | [`undefined`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type) The socket timeout in milliseconds as set by [`socket.setTimeout()`][]. It is `undefined` if a timeout has not been set. -#### `socket.unref()` +#### `socket.unref()` - + * Returns: [`net.Socket`](/api/net#netsocket) The socket itself. @@ -1055,11 +1055,11 @@ Calling `unref()` on a socket will allow the program to exit if this is the only active socket in the event system. If the socket is already `unref`ed calling `unref()` again will have no effect. -#### `socket.write(data[, encoding][, callback])` +#### `socket.write(data[, encoding][, callback])` - + -* `data` {string|Buffer|Uint8Array} +* `data` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`Uint8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array) * `encoding` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) Only used when data is `string`. **Default:** `utf8`. * `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) * Returns: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) @@ -1077,9 +1077,9 @@ written out, which may not be immediately. See `Writable` stream [`write()`][stream_writable_write] method for more information. -#### `socket.readyState` +#### `socket.readyState` - + * [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) @@ -1090,7 +1090,7 @@ This property represents the state of the connection as a string. * If the stream is readable and not writable, it is `readOnly`. * If the stream is not readable and writable, it is `writeOnly`. -### `net.connect()` +### `net.connect()` Aliases to [`net.createConnection()`][`net.createConnection()`]. @@ -1103,9 +1103,9 @@ Possible signatures: * [`net.connect(port[, host][, connectListener])`][`net.connect(port, host)`] for TCP connections. -#### `net.connect(options[, connectListener])` +#### `net.connect(options[, connectListener])` - + * `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) * `connectListener` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) @@ -1114,9 +1114,9 @@ Possible signatures: Alias to [`net.createConnection(options[, connectListener])`][`net.createConnection(options)`]. -#### `net.connect(path[, connectListener])` +#### `net.connect(path[, connectListener])` - + * `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) * `connectListener` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) @@ -1125,9 +1125,9 @@ Alias to Alias to [`net.createConnection(path[, connectListener])`][`net.createConnection(path)`]. -#### `net.connect(port[, host][, connectListener])` +#### `net.connect(port[, host][, connectListener])` - + * `port` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) * `host` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) @@ -1137,7 +1137,7 @@ Alias to Alias to [`net.createConnection(port[, host][, connectListener])`][`net.createConnection(port, host)`]. -### `net.createConnection()` +### `net.createConnection()` A factory function, which creates a new [`net.Socket`][], immediately initiates connection with [`socket.connect()`][], @@ -1157,9 +1157,9 @@ Possible signatures: The [`net.connect()`][] function is an alias to this function. -#### `net.createConnection(options[, connectListener])` +#### `net.createConnection(options[, connectListener])` - + * `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) Required. Will be passed to both the [`new net.Socket([options])`][`new net.Socket(options)`] call and the @@ -1205,9 +1205,9 @@ To connect on the socket `/tmp/echo.sock`: const client = net.createConnection({ path: '/tmp/echo.sock' }); ``` -#### `net.createConnection(path[, connectListener])` +#### `net.createConnection(path[, connectListener])` - + * `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) Path the socket should connect to. Will be passed to [`socket.connect(path[, connectListener])`][`socket.connect(path)`]. @@ -1225,9 +1225,9 @@ immediately initiates connection with [`socket.connect(path[, connectListener])`][`socket.connect(path)`], then returns the `net.Socket` that starts the connection. -#### `net.createConnection(port[, host][, connectListener])` +#### `net.createConnection(port[, host][, connectListener])` - + * `port` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Port the socket should connect to. Will be passed to [`socket.connect(port[, host][, connectListener])`][`socket.connect(port)`]. @@ -1247,9 +1247,9 @@ immediately initiates connection with [`socket.connect(port[, host][, connectListener])`][`socket.connect(port)`], then returns the `net.Socket` that starts the connection. -### `net.createServer([options][, connectionListener])` +### `net.createServer([options][, connectionListener])` - + * `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) * `allowHalfOpen` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) If set to `false`, then the socket will @@ -1332,9 +1332,9 @@ Use `nc` to connect to a Unix domain socket server: $ nc -U /tmp/echo.sock ``` -### `net.isIP(input)` +### `net.isIP(input)` - + * `input` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) * Returns: [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) @@ -1351,9 +1351,9 @@ net.isIP('127.0.0.1/24'); // returns 0 net.isIP('fhqwhgads'); // returns 0 ``` -### `net.isIPv4(input)` +### `net.isIPv4(input)` - + * `input` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) * Returns: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) @@ -1368,9 +1368,9 @@ net.isIPv4('127.0.0.1/24'); // returns false net.isIPv4('fhqwhgads'); // returns false ``` -### `net.isIPv6(input)` +### `net.isIPv6(input)` - + * `input` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) * Returns: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) diff --git a/content/api/v18/os.en.md b/content/api/v18/os.en.md index 3f42b3d67f..bf762cf39d 100644 --- a/content/api/v18/os.en.md +++ b/content/api/v18/os.en.md @@ -2,15 +2,15 @@ title: 'os' displayTitle: 'OS' category: 'api' -editPage: 'https://github.com/nodejs/node/blob/v18.8.0/doc/api/os.md' +editPage: 'https://github.com/nodejs/node/blob/v18.9.0/doc/api/os.md' version: 'v18' --- - + - + - + The `node:os` module provides operating system-related utility methods and properties. It can be accessed using: @@ -19,9 +19,9 @@ properties. It can be accessed using: const os = require('node:os'); ``` -### `os.EOL` +### `os.EOL` - + * [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) @@ -30,9 +30,9 @@ The operating system-specific end-of-line marker. * `\n` on POSIX * `\r\n` on Windows -### `os.arch()` +### `os.arch()` - + * Returns: [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) @@ -42,9 +42,9 @@ compiled. Possible values are `'arm'`, `'arm64'`, `'ia32'`, `'mips'`, The return value is equivalent to [`process.arch`][]. -### `os.constants` +### `os.constants` - + * [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) @@ -52,9 +52,9 @@ Contains commonly used operating system-specific constants for error codes, process signals, and so on. The specific constants defined are described in [OS constants](#os-constants). -### `os.cpus()` +### `os.cpus()` - + * Returns: Object\[] @@ -125,9 +125,9 @@ The properties included on each object include: `nice` values are POSIX-only. On Windows, the `nice` values of all processors are always 0. -### `os.devNull` +### `os.devNull` - + * [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) @@ -136,9 +136,9 @@ The platform-specific file path of the null device. * `\\.\nul` on Windows * `/dev/null` on POSIX -### `os.endianness()` +### `os.endianness()` - + * Returns: [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) @@ -147,17 +147,17 @@ binary was compiled. Possible values are `'BE'` for big endian and `'LE'` for little endian. -### `os.freemem()` +### `os.freemem()` - + * Returns: [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Returns the amount of free system memory in bytes as an integer. -### `os.getPriority([pid])` +### `os.getPriority([pid])` - + * `pid` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The process ID to retrieve scheduling priority for. **Default:** `0`. @@ -166,9 +166,9 @@ Returns the amount of free system memory in bytes as an integer. Returns the scheduling priority for the process specified by `pid`. If `pid` is not provided or is `0`, the priority of the current process is returned. -### `os.homedir()` +### `os.homedir()` - + * Returns: [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) @@ -180,17 +180,17 @@ uses the [effective UID][EUID] to look up the user's home directory. On Windows, it uses the `USERPROFILE` environment variable if defined. Otherwise it uses the path to the profile directory of the current user. -### `os.hostname()` +### `os.hostname()` - + * Returns: [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) Returns the host name of the operating system as a string. -### `os.loadavg()` +### `os.loadavg()` - + * Returns: number\[] @@ -202,9 +202,9 @@ system and expressed as a fractional number. The load average is a Unix-specific concept. On Windows, the return value is always `[0, 0, 0]`. -### `os.networkInterfaces()` +### `os.networkInterfaces()` - + * Returns: [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) @@ -273,9 +273,9 @@ The properties available on the assigned network address object include: } ``` -### `os.platform()` +### `os.platform()` - + * Returns: [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) @@ -289,9 +289,9 @@ The return value is equivalent to [`process.platform`][]. The value `'android'` may also be returned if Node.js is built on the Android operating system. [Android support is experimental][Android building]. -### `os.release()` +### `os.release()` - + * Returns: [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) @@ -299,11 +299,11 @@ Returns the operating system as a string. On POSIX systems, the operating system release is determined by calling [`uname(3)`][]. On Windows, `GetVersionExW()` is used. See - for more information. +(https://en.wikipedia.org/wiki/Uname#Examples)[https://en.wikipedia.org/wiki/Uname#Examples] for more information. -### `os.setPriority([pid, ]priority)` +### `os.setPriority([pid, ]priority)` - + * `pid` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The process ID to set scheduling priority for. **Default:** `0`. @@ -323,46 +323,46 @@ On Windows, setting priority to `PRIORITY_HIGHEST` requires elevated user privileges. Otherwise the set priority will be silently reduced to `PRIORITY_HIGH`. -### `os.tmpdir()` +### `os.tmpdir()` - + * Returns: [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) Returns the operating system's default directory for temporary files as a string. -### `os.totalmem()` +### `os.totalmem()` - + * Returns: [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Returns the total amount of system memory in bytes as an integer. -### `os.type()` +### `os.type()` - + * Returns: [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) Returns the operating system name as returned by [`uname(3)`][]. For example, it returns `'Linux'` on Linux, `'Darwin'` on macOS, and `'Windows_NT'` on Windows. -See for additional information +See (https://en.wikipedia.org/wiki/Uname#Examples)[https://en.wikipedia.org/wiki/Uname#Examples] for additional information about the output of running [`uname(3)`][] on various operating systems. -### `os.uptime()` +### `os.uptime()` - + * Returns: [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Returns the system uptime in number of seconds. -### `os.userInfo([options])` +### `os.userInfo([options])` - + * `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) * `encoding` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) Character encoding used to interpret resulting strings. @@ -382,9 +382,9 @@ operating system response. Throws a [`SystemError`][] if a user has no `username` or `homedir`. -### `os.version()` +### `os.version()` - + * Returns [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) @@ -393,7 +393,21 @@ Returns a string identifying the kernel version. On POSIX systems, the operating system release is determined by calling [`uname(3)`][]. On Windows, `RtlGetVersion()` is used, and if it is not available, `GetVersionExW()` will be used. See - for more information. +(https://en.wikipedia.org/wiki/Uname#Examples)[https://en.wikipedia.org/wiki/Uname#Examples] for more information. + +### `os.machine()` + + + +* Returns [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) + +Returns the machine type as a string, such as `arm`, `aarch64`, `mips`, +`mips64`, `ppc64`, `ppc64le`, `s390`, `s390x`, `i386`, `i686`, `x86_64`. + +On POSIX systems, the machine type is determined by calling +[`uname(3)`][]. On Windows, `RtlGetVersion()` is used, and if it is not +available, `GetVersionExW()` will be used. See +(https://en.wikipedia.org/wiki/Uname#Examples)[https://en.wikipedia.org/wiki/Uname#Examples] for more information. ### OS constants @@ -403,7 +417,7 @@ Not all constants will be available on every operating system. #### Signal constants - + The following signal constants are exported by `os.constants.signals`. @@ -1188,7 +1202,7 @@ information. #### Priority constants - + The following process scheduling constants are exported by `os.constants.priority`. diff --git a/content/api/v18/packages.en.md b/content/api/v18/packages.en.md index 36facf4591..5935496bd9 100644 --- a/content/api/v18/packages.en.md +++ b/content/api/v18/packages.en.md @@ -2,15 +2,15 @@ title: 'packages' displayTitle: 'Packages' category: 'api' -editPage: 'https://github.com/nodejs/node/blob/v18.8.0/doc/api/packages.md' +editPage: 'https://github.com/nodejs/node/blob/v18.9.0/doc/api/packages.md' version: 'v18' --- - + - + - + ### Introduction @@ -100,7 +100,7 @@ There is the ECMAScript module loader: Imported CommonJS modules have their URLs converted to absolute paths and are then loaded via the CommonJS module loader. -#### `package.json` and file extensions +#### `package.json` and file extensions Within a package, the [`package.json`][] [`"type"`][] field defines how Node.js should interpret `.js` files. If a `package.json` file does not have a @@ -156,9 +156,9 @@ package: extension (since both `.js` and `.cjs` files are treated as CommonJS within a `"commonjs"` package). -#### `--input-type` flag +#### `--input-type` flag - + Strings passed in as an argument to `--eval` (or `-e`), or piped to `node` via `STDIN`, are treated as [ES modules][] when the `--input-type=module` flag @@ -176,7 +176,7 @@ unspecified. ### Determining package manager - + While all Node.js projects are expected to be installable by all package managers once published, their development teams are often required to use one @@ -312,7 +312,7 @@ alongside `"exports"` pointing to the same module: #### Subpath exports - + When using the [`"exports"`][] field, custom subpaths can be defined along with the main entry point by treating the main entry point as the @@ -363,7 +363,7 @@ in relative and absolute import specifiers. #### Exports sugar - + If the `"."` export is the only export, the [`"exports"`][] field provides sugar for this case being the direct [`"exports"`][] field value. @@ -386,7 +386,7 @@ can be written: #### Subpath imports - + In addition to the [`"exports"`][] field, there is a package `"imports"` field to create private mappings that only apply to import specifiers from within the @@ -425,7 +425,7 @@ exports field. #### Subpath patterns - + For packages with a small number of exports or imports, we recommend explicitly listing each exports subpath entry. But for packages that have @@ -495,7 +495,7 @@ import featureX from 'es-module-package/features/x.js'; #### Conditional exports - + Conditional exports provide a way to map to different paths depending on certain conditions. They are supported for both CommonJS and ES module imports. @@ -604,7 +604,7 @@ conditions behave analogously to nested JavaScript `if` statements. #### Resolving user conditions - + When running Node.js, custom user conditions can be added with the `--conditions` flag: @@ -662,7 +662,7 @@ course. #### Self-referencing a package using its name - + Within a package, the values defined in the package's `package.json` [`"exports"`][] field can be referenced via the package's name. @@ -801,7 +801,7 @@ following conditions: 3. The package main entry point, e.g. `'pkg'` can be used by both `require` to resolve to a CommonJS file and by `import` to resolve to an ES module file. (And likewise for exported paths, e.g. `'pkg/feature'`.) -4. The package provides named exports, e.g. `import { name } from 'pkg'` rather +4. The package provides named exports, e.g. `import name from 'pkg'` rather than `import pkg from 'pkg'; pkg.name`. 5. The package is potentially usable in other ES module environments such as browsers. @@ -842,13 +842,13 @@ import cjsModule from './index.cjs'; export const name = cjsModule.name; ``` -In this example, the `name` from `import { name } from 'pkg'` is the same -singleton as the `name` from `const { name } = require('pkg')`. Therefore `===` +In this example, the `name` from `import name from 'pkg'` is the same +singleton as the `name` from `const name = require('pkg')`. Therefore `===` returns `true` when comparing the two `name`s and the divergent specifier hazard is avoided. If the module is not simply a list of named exports, but rather contains a -unique function or object export like `module.exports = function () { ... }`, +unique function or object export like `module.exports = function () ... `, or if support in the wrapper for the `import pkg from 'pkg'` pattern is desired, then the wrapper would instead be written to export the default optionally along with any named exports as well: @@ -952,9 +952,9 @@ CommonJS and ES module instances of the package: ```js // ./node_modules/pkg/index.mjs import state from './state.cjs'; - export { + export state - }; + ; ``` Even if `pkg` is used via both `require` and `import` in an application (for @@ -1014,9 +1014,9 @@ The following fields in `package.json` files are used in Node.js: * [`"imports"`][] - Package imports, for use by modules within the package itself. -#### `"name"` +#### `"name"` - + * Type: [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) @@ -1033,9 +1033,9 @@ _npm_ registry requires a name that satisfies The `"name"` field can be used in addition to the [`"exports"`][] field to [self-reference][] a package using its name. -#### `"main"` +#### `"main"` - + * Type: [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) @@ -1059,11 +1059,11 @@ via `require()`](modules.md#folders-as-modules). require('./path/to/directory'); ``` -#### `"packageManager"` +#### `"packageManager"` - + - + * Type: [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) @@ -1082,9 +1082,9 @@ Node.js. This field is currently experimental and needs to be opted-in; check the [Corepack][] page for details about the procedure. -#### `"type"` +#### `"type"` - + * Type: [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) @@ -1127,9 +1127,9 @@ import './startup.js'; // Loaded as ES module because of package.json Regardless of the value of the `"type"` field, `.mjs` files are always treated as ES modules and `.cjs` files are always treated as CommonJS. -#### `"exports"` +#### `"exports"` - + * Type: [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | string\[] @@ -1152,9 +1152,9 @@ referenced via `require` or via `import`. All paths defined in the `"exports"` must be relative file URLs starting with `./`. -#### `"imports"` +#### `"imports"` - + * Type: [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) diff --git a/content/api/v18/path.en.md b/content/api/v18/path.en.md index 6c43e78977..d7e046b02e 100644 --- a/content/api/v18/path.en.md +++ b/content/api/v18/path.en.md @@ -2,15 +2,15 @@ title: 'path' displayTitle: 'Path' category: 'api' -editPage: 'https://github.com/nodejs/node/blob/v18.8.0/doc/api/path.md' +editPage: 'https://github.com/nodejs/node/blob/v18.9.0/doc/api/path.md' version: 'v18' --- - + - + - + The `node:path` module provides utilities for working with file and directory paths. It can be accessed using: @@ -68,9 +68,9 @@ example, `path.resolve('C:\\')` can potentially return a different result than `path.resolve('C:')`. For more information, see [this MSDN page][MSDN-Rel-Path]. -### `path.basename(path[, ext])` +### `path.basename(path[, ext])` - + * `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) * `ext` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) An optional file extension @@ -104,9 +104,9 @@ path.win32.basename('C:\\foo.HTML', '.html'); A [`TypeError`][] is thrown if `path` is not a string or if `ext` is given and is not a string. -### `path.delimiter` +### `path.delimiter` - + * [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) @@ -135,9 +135,9 @@ process.env.PATH.split(path.delimiter); // Returns ['C:\\Windows\\system32', 'C:\\Windows', 'C:\\Program Files\\node\\'] ``` -### `path.dirname(path)` +### `path.dirname(path)` - + * `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) * Returns: [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) @@ -153,9 +153,9 @@ path.dirname('/foo/bar/baz/asdf/quux'); A [`TypeError`][] is thrown if `path` is not a string. -### `path.extname(path)` +### `path.extname(path)` - + * `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) * Returns: [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) @@ -188,9 +188,9 @@ path.extname('.index.md'); A [`TypeError`][] is thrown if `path` is not a string. -### `path.format(pathObject)` +### `path.format(pathObject)` - + * `pathObject` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) Any JavaScript object having the following properties: * `dir` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) @@ -213,7 +213,7 @@ For example, on POSIX: ```js // If `dir`, `root` and `base` are provided, -// `$dir$path.sep$base` +// `${dir}${path.sep}${base}` // will be returned. `root` is ignored. path.format({ root: '/ignored', @@ -251,9 +251,9 @@ path.format({ // Returns: 'C:\\path\\dir\\file.txt' ``` -### `path.isAbsolute(path)` +### `path.isAbsolute(path)` - + * `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) * Returns: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) @@ -285,9 +285,9 @@ path.isAbsolute('.'); // false A [`TypeError`][] is thrown if `path` is not a string. -### `path.join([...paths])` +### `path.join([...paths])` - + * `...paths` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) A sequence of path segments * Returns: [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) @@ -309,9 +309,9 @@ path.join('foo', {}, 'bar'); A [`TypeError`][] is thrown if any of the path segments is not a string. -### `path.normalize(path)` +### `path.normalize(path)` - + * `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) * Returns: [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) @@ -351,9 +351,9 @@ path.win32.normalize('C:////temp\\\\/\\/\\/foo/bar'); A [`TypeError`][] is thrown if `path` is not a string. -### `path.parse(path)` +### `path.parse(path)` - + * `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) * Returns: [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) @@ -416,9 +416,9 @@ path.parse('C:\\path\\dir\\file.txt'); A [`TypeError`][] is thrown if `path` is not a string. -### `path.posix` +### `path.posix` - + * [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) @@ -427,9 +427,9 @@ of the `path` methods. The API is accessible via `require('node:path').posix` or `require('node:path/posix')`. -### `path.relative(from, to)` +### `path.relative(from, to)` - + * `from` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) * `to` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) @@ -458,9 +458,9 @@ path.relative('C:\\orandea\\test\\aaa', 'C:\\orandea\\impl\\bbb'); A [`TypeError`][] is thrown if either `from` or `to` is not a string. -### `path.resolve([...paths])` +### `path.resolve([...paths])` - + * `...paths` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) A sequence of paths or path segments * Returns: [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) @@ -499,9 +499,9 @@ path.resolve('wwwroot', 'static_files/png/', '../gif/image.gif'); A [`TypeError`][] is thrown if any of the arguments is not a string. -### `path.sep` +### `path.sep` - + * [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) @@ -528,9 +528,9 @@ On Windows, both the forward slash (`/`) and backward slash (`\`) are accepted as path segment separators; however, the `path` methods only add backward slashes (`\`). -### `path.toNamespacedPath(path)` +### `path.toNamespacedPath(path)` - + * `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) * Returns: [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) @@ -542,9 +542,9 @@ modifications. This method is meaningful only on Windows systems. On POSIX systems, the method is non-operational and always returns `path` without modifications. -### `path.win32` +### `path.win32` - + * [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) diff --git a/content/api/v18/perf_hooks.en.md b/content/api/v18/perf_hooks.en.md index 959c34e52f..f9806d5172 100644 --- a/content/api/v18/perf_hooks.en.md +++ b/content/api/v18/perf_hooks.en.md @@ -2,15 +2,15 @@ title: 'perf_hooks' displayTitle: 'Performance measurement APIs' category: 'api' -editPage: 'https://github.com/nodejs/node/blob/v18.8.0/doc/api/perf_hooks.md' +editPage: 'https://github.com/nodejs/node/blob/v18.9.0/doc/api/perf_hooks.md' version: 'v18' --- - + - + - + This module provides an implementation of a subset of the W3C [Web Performance APIs][] as well as additional APIs for @@ -42,43 +42,43 @@ doSomeLongRunningProcess(() => { }); ``` -### `perf_hooks.performance` +### `perf_hooks.performance` - + An object that can be used to collect performance metrics from the current Node.js instance. It is similar to [`window.performance`][] in browsers. -#### `performance.clearMarks([name])` +#### `performance.clearMarks([name])` - + * `name` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) If `name` is not provided, removes all `PerformanceMark` objects from the Performance Timeline. If `name` is provided, removes only the named mark. -#### `performance.clearMeasures([name])` +#### `performance.clearMeasures([name])` - + * `name` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) If `name` is not provided, removes all `PerformanceMeasure` objects from the Performance Timeline. If `name` is provided, removes only the named measure. -#### `performance.clearResourceTimings([name])` +#### `performance.clearResourceTimings([name])` - + * `name` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) If `name` is not provided, removes all `PerformanceResourceTiming` objects from the Resource Timeline. If `name` is provided, removes only the named resource. -#### `performance.eventLoopUtilization([utilization1[, utilization2]])` +#### `performance.eventLoopUtilization([utilization1[, utilization2]])` - + * `utilization1` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) The result of a previous call to `eventLoopUtilization()`. @@ -135,9 +135,9 @@ Passing in a user-defined object instead of the result of a previous call to `eventLoopUtilization()` will lead to undefined behavior. The return values are not guaranteed to reflect any correct state of the event loop. -#### `performance.getEntries()` +#### `performance.getEntries()` - + * Returns: PerformanceEntry\[] @@ -146,9 +146,9 @@ respect to `performanceEntry.startTime`. If you are only interested in performance entries of certain types or that have certain names, see `performance.getEntriesByType()` and `performance.getEntriesByName()`. -#### `performance.getEntriesByName(name[, type])` +#### `performance.getEntriesByName(name[, type])` - + * `name` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) * `type` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) @@ -159,9 +159,9 @@ with respect to `performanceEntry.startTime` whose `performanceEntry.name` is equal to `name`, and optionally, whose `performanceEntry.entryType` is equal to `type`. -#### `performance.getEntriesByType(type)` +#### `performance.getEntriesByType(type)` - + * `type` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) * Returns: PerformanceEntry\[] @@ -170,9 +170,9 @@ Returns a list of `PerformanceEntry` objects in chronological order with respect to `performanceEntry.startTime` whose `performanceEntry.entryType` is equal to `type`. -#### `performance.mark([name[, options]])` +#### `performance.mark([name[, options]])` - + * `name` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) * `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) @@ -192,9 +192,9 @@ and can be queried with `performance.getEntries`, observation is performed, the entries should be cleared from the global Performance Timeline manually with `performance.clearMarks`. -#### `performance.markResourceTiming(timingInfo, requestedUrl, initiatorType, global, cacheMode)` +#### `performance.markResourceTiming(timingInfo, requestedUrl, initiatorType, global, cacheMode)` - + * `timingInfo` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) [Fetch Timing Info][] * `requestedUrl` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The resource url @@ -215,9 +215,9 @@ and can be queried with `performance.getEntries`, observation is performed, the entries should be cleared from the global Performance Timeline manually with `performance.clearResourceTimings`. -#### `performance.measure(name[, startMarkOrOptions[, endMark]])` +#### `performance.measure(name[, startMarkOrOptions[, endMark]])` - + * `name` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) * `startMarkOrOptions` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) Optional. @@ -253,9 +253,9 @@ and can be queried with `performance.getEntries`, observation is performed, the entries should be cleared from the global Performance Timeline manually with `performance.clearMeasures`. -#### `performance.nodeTiming` +#### `performance.nodeTiming` - + * [`PerformanceNodeTiming`](/api/perf_hooks#performancenodetiming) @@ -264,36 +264,36 @@ _This property is an extension by Node.js. It is not available in Web browsers._ An instance of the `PerformanceNodeTiming` class that provides performance metrics for specific Node.js operational milestones. -#### `performance.now()` +#### `performance.now()` - + * Returns: [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Returns the current high resolution millisecond timestamp, where 0 represents the start of the current `node` process. -#### `performance.setResourceTimingBufferSize(maxSize)` +#### `performance.setResourceTimingBufferSize(maxSize)` - + Sets the global performance resource timing buffer size to the specified number of "resource" type performance entry objects. By default the max buffer size is set to 250. -#### `performance.timeOrigin` +#### `performance.timeOrigin` - + * [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The [`timeOrigin`][] specifies the high resolution millisecond timestamp at which the current `node` process began, measured in Unix time. -#### `performance.timerify(fn[, options])` +#### `performance.timerify(fn[, options])` - + * `fn` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) * `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) @@ -336,16 +336,16 @@ If the wrapped function returns a promise, a finally handler will be attached to the promise and the duration will be reported once the finally handler is invoked. -#### `performance.toJSON()` +#### `performance.toJSON()` - + An object which is JSON representation of the `performance` object. It is similar to [`window.performance.toJSON`][] in browsers. -##### `'resourcetimingbufferfull'` +##### `'resourcetimingbufferfull'` - + The `'resourcetimingbufferfull'` event is fired when the global performance resource timing buffer is full. Adjust resource timing buffer size with @@ -353,30 +353,30 @@ resource timing buffer is full. Adjust resource timing buffer size with `performance.clearResourceTimings()` in the event listener to allow more entries to be added to the performance timeline buffer. -### `PerformanceEntry` +### `PerformanceEntry` - + -#### `performanceEntry.detail` +#### `performanceEntry.detail` - + * [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) Additional detail specific to the `entryType`. -#### `performanceEntry.duration` +#### `performanceEntry.duration` - + * [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The total number of milliseconds elapsed for this entry. This value will not be meaningful for all Performance Entry types. -#### `performanceEntry.entryType` +#### `performanceEntry.entryType` - + * [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) @@ -390,9 +390,9 @@ The type of the performance entry. It may be one of: * `'http2'` (Node.js only) * `'http'` (Node.js only) -#### `performanceEntry.flags` +#### `performanceEntry.flags` - + * [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) @@ -410,17 +410,17 @@ The value may be one of: * `perf_hooks.constants.NODE_PERFORMANCE_GC_FLAGS_ALL_EXTERNAL_MEMORY` * `perf_hooks.constants.NODE_PERFORMANCE_GC_FLAGS_SCHEDULE_IDLE` -#### `performanceEntry.name` +#### `performanceEntry.name` - + * [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The name of the performance entry. -#### `performanceEntry.kind` +#### `performanceEntry.kind` - + * [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) @@ -435,9 +435,9 @@ The value may be one of: * `perf_hooks.constants.NODE_PERFORMANCE_GC_INCREMENTAL` * `perf_hooks.constants.NODE_PERFORMANCE_GC_WEAKCB` -#### `performanceEntry.startTime` +#### `performanceEntry.startTime` - + * [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) @@ -554,9 +554,9 @@ If `performanceEntry.name` is equal to `queryxxx` or `getHostByAddr`, the `detai contain the following properties: `host`, `ttl`, `result`. The value of `result` is same as the result of `queryxxx` or `getHostByAddr`. -### `PerformanceNodeTiming` +### `PerformanceNodeTiming` - + * Extends: [`PerformanceEntry`](/api/perf_hooks#performanceentry) @@ -565,9 +565,9 @@ _This property is an extension by Node.js. It is not available in Web browsers._ Provides timing details for Node.js itself. The constructor of this class is not exposed to users. -#### `performanceNodeTiming.bootstrapComplete` +#### `performanceNodeTiming.bootstrapComplete` - + * [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) @@ -575,18 +575,18 @@ The high resolution millisecond timestamp at which the Node.js process completed bootstrapping. If bootstrapping has not yet finished, the property has the value of -1. -#### `performanceNodeTiming.environment` +#### `performanceNodeTiming.environment` - + * [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The high resolution millisecond timestamp at which the Node.js environment was initialized. -#### `performanceNodeTiming.idleTime` +#### `performanceNodeTiming.idleTime` - + * [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) @@ -596,9 +596,9 @@ does not take CPU usage into consideration. If the event loop has not yet started (e.g., in the first tick of the main script), the property has the value of 0. -#### `performanceNodeTiming.loopExit` +#### `performanceNodeTiming.loopExit` - + * [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) @@ -606,9 +606,9 @@ The high resolution millisecond timestamp at which the Node.js event loop exited. If the event loop has not yet exited, the property has the value of -1. It can only have a value of not -1 in a handler of the [`'exit'`][] event. -#### `performanceNodeTiming.loopStart` +#### `performanceNodeTiming.loopStart` - + * [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) @@ -616,27 +616,27 @@ The high resolution millisecond timestamp at which the Node.js event loop started. If the event loop has not yet started (e.g., in the first tick of the main script), the property has the value of -1. -#### `performanceNodeTiming.nodeStart` +#### `performanceNodeTiming.nodeStart` - + * [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The high resolution millisecond timestamp at which the Node.js process was initialized. -#### `performanceNodeTiming.v8Start` +#### `performanceNodeTiming.v8Start` - + * [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The high resolution millisecond timestamp at which the V8 platform was initialized. -### `PerformanceResourceTiming` +### `PerformanceResourceTiming` - + * Extends: [`PerformanceEntry`](/api/perf_hooks#performanceentry) @@ -645,9 +645,9 @@ resources. The constructor of this class is not exposed to users directly. -#### `performanceResourceTiming.workerStart` +#### `performanceResourceTiming.workerStart` - + * [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) @@ -655,54 +655,54 @@ The high resolution millisecond timestamp at immediately before dispatching the `fetch` request. If the resource is not intercepted by a worker the property will always return 0. -#### `performanceResourceTiming.redirectStart` +#### `performanceResourceTiming.redirectStart` - + * [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The high resolution millisecond timestamp that represents the start time of the fetch which initiates the redirect. -#### `performanceResourceTiming.redirectEnd` +#### `performanceResourceTiming.redirectEnd` - + * [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The high resolution millisecond timestamp that will be created immediately after receiving the last byte of the response of the last redirect. -#### `performanceResourceTiming.fetchStart` +#### `performanceResourceTiming.fetchStart` - + * [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The high resolution millisecond timestamp immediately before the Node.js starts to fetch the resource. -#### `performanceResourceTiming.domainLookupStart` +#### `performanceResourceTiming.domainLookupStart` - + * [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The high resolution millisecond timestamp immediately before the Node.js starts the domain name lookup for the resource. -#### `performanceResourceTiming.domainLookupEnd` +#### `performanceResourceTiming.domainLookupEnd` - + * [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The high resolution millisecond timestamp representing the time immediately after the Node.js finished the domain name lookup for the resource. -#### `performanceResourceTiming.connectStart` +#### `performanceResourceTiming.connectStart` - + * [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) @@ -710,9 +710,9 @@ The high resolution millisecond timestamp representing the time immediately before Node.js starts to establish the connection to the server to retrieve the resource. -#### `performanceResourceTiming.connectEnd` +#### `performanceResourceTiming.connectEnd` - + * [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) @@ -720,27 +720,27 @@ The high resolution millisecond timestamp representing the time immediately after Node.js finishes establishing the connection to the server to retrieve the resource. -#### `performanceResourceTiming.secureConnectionStart` +#### `performanceResourceTiming.secureConnectionStart` - + * [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The high resolution millisecond timestamp representing the time immediately before Node.js starts the handshake process to secure the current connection. -#### `performanceResourceTiming.requestStart` +#### `performanceResourceTiming.requestStart` - + * [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The high resolution millisecond timestamp representing the time immediately before Node.js receives the first byte of the response from the server. -#### `performanceResourceTiming.responseEnd` +#### `performanceResourceTiming.responseEnd` - + * [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) @@ -748,18 +748,18 @@ The high resolution millisecond timestamp representing the time immediately after Node.js receives the last byte of the resource or immediately before the transport connection is closed, whichever comes first. -#### `performanceResourceTiming.transferSize` +#### `performanceResourceTiming.transferSize` - + * [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) A number representing the size (in octets) of the fetched resource. The size includes the response header fields plus the response payload body. -#### `performanceResourceTiming.encodedBodySize` +#### `performanceResourceTiming.encodedBodySize` - + * [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) @@ -767,9 +767,9 @@ A number representing the size (in octets) received from the fetch (HTTP or cache), of the payload body, before removing any applied content-codings. -#### `performanceResourceTiming.decodedBodySize` +#### `performanceResourceTiming.decodedBodySize` - + * [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) @@ -777,18 +777,18 @@ A number representing the size (in octets) received from the fetch (HTTP or cache), of the message body, after removing any applied content-codings. -#### `performanceResourceTiming.toJSON()` +#### `performanceResourceTiming.toJSON()` - + Returns a `object` that is the JSON representation of the `PerformanceResourceTiming` object -### `perf_hooks.PerformanceObserver` +### `perf_hooks.PerformanceObserver` -#### `new PerformanceObserver(callback)` +#### `new PerformanceObserver(callback)` - + * `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) * `list` [`PerformanceObserverEntryList`](/api/perf_hooks#performanceobserverentrylist) @@ -825,15 +825,15 @@ notified about new `PerformanceEntry` instances. The callback receives a `PerformanceObserverEntryList` instance and a reference to the `PerformanceObserver`. -#### `performanceObserver.disconnect()` +#### `performanceObserver.disconnect()` - + Disconnects the `PerformanceObserver` instance from all notifications. -#### `performanceObserver.observe(options)` +#### `performanceObserver.observe(options)` - + * `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) * `type` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) A single [`PerformanceEntry`](/api/perf_hooks#performanceentry) type. Must not be given @@ -862,20 +862,20 @@ const obs = new PerformanceObserver((list, observer) => { obs.observe({ type: 'mark' }); for (let n = 0; n < 3; n++) - performance.mark(`test$n`); + performance.mark(`test${n}`); ``` -### `PerformanceObserverEntryList` +### `PerformanceObserverEntryList` - + The `PerformanceObserverEntryList` class is used to provide access to the `PerformanceEntry` instances passed to a `PerformanceObserver`. The constructor of this class is not exposed to users. -#### `performanceObserverEntryList.getEntries()` +#### `performanceObserverEntryList.getEntries()` - + * Returns: PerformanceEntry\[] @@ -917,9 +917,9 @@ performance.mark('test'); performance.mark('meow'); ``` -#### `performanceObserverEntryList.getEntriesByName(name[, type])` +#### `performanceObserverEntryList.getEntriesByName(name[, type])` - + * `name` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) * `type` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) @@ -973,9 +973,9 @@ performance.mark('test'); performance.mark('meow'); ``` -#### `performanceObserverEntryList.getEntriesByType(type)` +#### `performanceObserverEntryList.getEntriesByType(type)` - + * `type` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) * Returns: PerformanceEntry\[] @@ -1018,9 +1018,9 @@ performance.mark('test'); performance.mark('meow'); ``` -### `perf_hooks.createHistogram([options])` +### `perf_hooks.createHistogram([options])` - + * `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) * `lowest` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) | [`bigint`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt) The lowest discernible value. Must be an integer @@ -1034,9 +1034,9 @@ performance.mark('meow'); Returns a [`RecordableHistogram`](/api/perf_hooks#recordablehistogram-extends-histogram). -### `perf_hooks.monitorEventLoopDelay([options])` +### `perf_hooks.monitorEventLoopDelay([options])` - + * `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) * `resolution` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The sampling rate in milliseconds. Must be greater @@ -1069,148 +1069,148 @@ console.log(h.percentile(50)); console.log(h.percentile(99)); ``` -### `Histogram` +### `Histogram` - + -#### `histogram.count` +#### `histogram.count` - + * [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The number of samples recorded by the histogram. -#### `histogram.countBigInt` +#### `histogram.countBigInt` - + * [`bigint`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt) The number of samples recorded by the histogram. -#### `histogram.exceeds` +#### `histogram.exceeds` - + * [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The number of times the event loop delay exceeded the maximum 1 hour event loop delay threshold. -#### `histogram.exceedsBigInt` +#### `histogram.exceedsBigInt` - + * [`bigint`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt) The number of times the event loop delay exceeded the maximum 1 hour event loop delay threshold. -#### `histogram.max` +#### `histogram.max` - + * [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The maximum recorded event loop delay. -#### `histogram.maxBigInt` +#### `histogram.maxBigInt` - + * [`bigint`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt) The maximum recorded event loop delay. -#### `histogram.mean` +#### `histogram.mean` - + * [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The mean of the recorded event loop delays. -#### `histogram.min` +#### `histogram.min` - + * [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The minimum recorded event loop delay. -#### `histogram.minBigInt` +#### `histogram.minBigInt` - + * [`bigint`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt) The minimum recorded event loop delay. -#### `histogram.percentile(percentile)` +#### `histogram.percentile(percentile)` - + * `percentile` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) A percentile value in the range (0, 100]. * Returns: [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Returns the value at the given percentile. -#### `histogram.percentileBigInt(percentile)` +#### `histogram.percentileBigInt(percentile)` - + * `percentile` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) A percentile value in the range (0, 100]. * Returns: [`bigint`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt) Returns the value at the given percentile. -#### `histogram.percentiles` +#### `histogram.percentiles` - + * [`Map`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map) Returns a `Map` object detailing the accumulated percentile distribution. -#### `histogram.percentilesBigInt` +#### `histogram.percentilesBigInt` - + * [`Map`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map) Returns a `Map` object detailing the accumulated percentile distribution. -#### `histogram.reset()` +#### `histogram.reset()` - + Resets the collected histogram data. -#### `histogram.stddev` +#### `histogram.stddev` - + * [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The standard deviation of the recorded event loop delays. -### `IntervalHistogram extends Histogram` +### `IntervalHistogram extends Histogram` A `Histogram` that is periodically updated on a given interval. -#### `histogram.disable()` +#### `histogram.disable()` - + * Returns: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) Disables the update interval timer. Returns `true` if the timer was stopped, `false` if it was already stopped. -#### `histogram.enable()` +#### `histogram.enable()` - + * Returns: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) @@ -1223,27 +1223,27 @@ started, `false` if it was already started. end, the histogram is cloned as a plain [`Histogram`](/api/perf_hooks#histogram) object that does not implement the `enable()` and `disable()` methods. -### `RecordableHistogram extends Histogram` +### `RecordableHistogram extends Histogram` - + -#### `histogram.add(other)` +#### `histogram.add(other)` - + * `other` [`RecordableHistogram`](/api/perf_hooks#recordablehistogram-extends-histogram) Adds the values from `other` to this histogram. -#### `histogram.record(val)` +#### `histogram.record(val)` - + * `val` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) | [`bigint`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt) The amount to record in the histogram. -#### `histogram.recordDelta()` +#### `histogram.recordDelta()` - + Calculates the amount of time (in nanoseconds) that has passed since the previous call to `recordDelta()` and records that amount in the histogram. @@ -1268,17 +1268,17 @@ const set = new Set(); const hook = async_hooks.createHook({ init(id, type) { if (type === 'Timeout') { - performance.mark(`Timeout-$id-Init`); + performance.mark(`Timeout-${id}-Init`); set.add(id); } }, destroy(id) { if (set.has(id)) { set.delete(id); - performance.mark(`Timeout-$id-Destroy`); - performance.measure(`Timeout-$id`, - `Timeout-$id-Init`, - `Timeout-$id-Destroy`); + performance.mark(`Timeout-${id}-Destroy`); + performance.measure(`Timeout-${id}`, + `Timeout-${id}-Init`, + `Timeout-${id}-Destroy`); } } }); @@ -1356,7 +1356,7 @@ const PORT = 8080; http.createServer((req, res) => { res.end('ok'); }).listen(PORT, () => { - http.get(`http://127.0.0.1:$PORT`); + http.get(`http://127.0.0.1:${PORT}`); }); ``` diff --git a/content/api/v18/policy.en.md b/content/api/v18/policy.en.md index eed2fdb40a..01eb5d0bdd 100644 --- a/content/api/v18/policy.en.md +++ b/content/api/v18/policy.en.md @@ -2,17 +2,17 @@ title: 'policy' displayTitle: 'Policies' category: 'api' -editPage: 'https://github.com/nodejs/node/blob/v18.8.0/doc/api/policy.md' +editPage: 'https://github.com/nodejs/node/blob/v18.9.0/doc/api/policy.md' version: 'v18' --- - + - + - + - + Node.js contains experimental support for creating policies on loading code. @@ -30,7 +30,7 @@ and granting read permissions to the user id running Node.js. ### Enabling - + The `--experimental-policy` flag can be used to enable features for policies when loading modules. diff --git a/content/api/v18/process.en.md b/content/api/v18/process.en.md index 246906b568..6e4b8ba150 100644 --- a/content/api/v18/process.en.md +++ b/content/api/v18/process.en.md @@ -2,15 +2,15 @@ title: 'process' displayTitle: 'Process' category: 'api' -editPage: 'https://github.com/nodejs/node/blob/v18.8.0/doc/api/process.md' +editPage: 'https://github.com/nodejs/node/blob/v18.9.0/doc/api/process.md' version: 'v18' --- - + - + - + The `process` object provides information about, and control over, the current Node.js process. @@ -27,9 +27,9 @@ const process = require('node:process'); The `process` object is an instance of [`EventEmitter`][]. -#### `'beforeExit'` +#### `'beforeExit'` - + The `'beforeExit'` event is emitted when Node.js empties its event loop and has no additional work to schedule. Normally, the Node.js process will exit when @@ -84,17 +84,17 @@ console.log('This message is displayed first.'); // Process exit event with code: 0 ``` -#### `'disconnect'` +#### `'disconnect'` - + If the Node.js process is spawned with an IPC channel (see the [Child Process][] and [Cluster][] documentation), the `'disconnect'` event will be emitted when the IPC channel is closed. -#### `'exit'` +#### `'exit'` - + * `code` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) @@ -115,7 +115,7 @@ by the [`process.exitCode`][] property, or the `exitCode` argument passed to the import process from 'node:process'; process.on('exit', (code) => { - console.log(`About to exit with code: $code`); + console.log(`About to exit with code: ${code}`); }); ``` @@ -123,7 +123,7 @@ process.on('exit', (code) => { const process = require('node:process'); process.on('exit', (code) => { - console.log(`About to exit with code: $code`); + console.log(`About to exit with code: ${code}`); }); ``` @@ -152,11 +152,11 @@ process.on('exit', (code) => { }); ``` -#### `'message'` +#### `'message'` - + -* `message` { Object | boolean | number | string | null } a parsed JSON object +* `message` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) | [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) | [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`null`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type) a parsed JSON object or a serializable primitive value. * `sendHandle` [`net.Server`](/api/net#netserver) | [`net.Socket`](/api/net#netsocket) a [`net.Server`][] or [`net.Socket`][] object, or undefined. @@ -174,11 +174,11 @@ process, the `message` argument can contain data that JSON is not able to represent. See [Advanced serialization for `child_process`][] for more details. -#### `'multipleResolves'` +#### `'multipleResolves'` - + - + * `type` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The resolution type. One of `'resolve'` or `'reject'`. * `promise` [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) The promise that resolved or rejected more than once. @@ -258,9 +258,9 @@ main().then(console.log); // First call ``` -#### `'rejectionHandled'` +#### `'rejectionHandled'` - + * `promise` [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) The late handled promise. @@ -318,9 +318,9 @@ possible to record such errors in an error log, either periodically (which is likely best for long-running application) or upon process exit (which is likely most convenient for scripts). -#### `'uncaughtException'` +#### `'uncaughtException'` - + * `err` [`Error`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error) The uncaught exception. * `origin` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) Indicates if the exception originates from an unhandled @@ -347,8 +347,8 @@ import process from 'node:process'; process.on('uncaughtException', (err, origin) => { fs.writeSync( process.stderr.fd, - `Caught exception: $err\n` + - `Exception origin: $origin` + `Caught exception: ${err}\n` + + `Exception origin: ${origin}` ); }); @@ -367,8 +367,8 @@ const process = require('node:process'); process.on('uncaughtException', (err, origin) => { fs.writeSync( process.stderr.fd, - `Caught exception: $err\n` + - `Exception origin: $origin` + `Caught exception: ${err}\n` + + `Exception origin: ${origin}` ); }); @@ -412,9 +412,9 @@ To restart a crashed application in a more reliable way, whether in a separate process to detect application failures and recover or restart as needed. -#### `'uncaughtExceptionMonitor'` +#### `'uncaughtExceptionMonitor'` - + * `err` [`Error`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error) The uncaught exception. * `origin` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) Indicates if the exception originates from an unhandled @@ -457,9 +457,9 @@ nonexistentFunc(); // Still crashes Node.js ``` -#### `'unhandledRejection'` +#### `'unhandledRejection'` - + * `reason` [`Error`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error) | [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) The object with which the promise was rejected (typically an [`Error`][] object). @@ -529,13 +529,13 @@ const resource = new SomeResource(); In this example case, it is possible to track the rejection as a developer error as would typically be the case for other `'unhandledRejection'` events. To address such failures, a non-operational -[`.catch(() => { })`][`promise.catch()`] handler may be attached to +[`.catch(() => )`][`promise.catch()`] handler may be attached to `resource.loaded`, which would prevent the `'unhandledRejection'` event from being emitted. -#### `'warning'` +#### `'warning'` - + * `warning` [`Error`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error) Key properties of the warning are: * `name` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The name of the warning. **Default:** `'Warning'`. @@ -614,9 +614,9 @@ of the custom deprecation. The `*-deprecation` command-line flags only affect warnings that use the name `'DeprecationWarning'`. -#### `'worker'` +#### `'worker'` - + * `worker` [`Worker`](/api/worker_threads#worker) The [`Worker`](/api/worker_threads#worker) that was created. @@ -652,9 +652,9 @@ A few of the warning types that are most common include: #### Signal events - + - + Signal events will be emitted when the Node.js process receives a signal. Please refer to signal(7) for a listing of standard POSIX signal names such as @@ -680,7 +680,7 @@ process.on('SIGINT', () => { // Using a single function to handle multiple signals function handle(signal) { - console.log(`Received $signal`); + console.log(`Received ${signal}`); } process.on('SIGINT', handle); @@ -699,7 +699,7 @@ process.on('SIGINT', () => { // Using a single function to handle multiple signals function handle(signal) { - console.log(`Received $signal`); + console.log(`Received ${signal}`); } process.on('SIGINT', handle); @@ -750,18 +750,18 @@ but Node.js offers some emulation with [`process.kill()`][], and * Sending signal `0` can be used as a platform independent way to test for the existence of a process. -### `process.abort()` +### `process.abort()` - + The `process.abort()` method causes the Node.js process to exit immediately and generate a core file. This feature is not available in [`Worker`][] threads. -### `process.allowedNodeEnvironmentFlags` +### `process.allowedNodeEnvironmentFlags` - + * [`Set`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set) @@ -820,9 +820,9 @@ If Node.js was compiled _without_ [`NODE_OPTIONS`][] support (shown in [`process.config`][]), `process.allowedNodeEnvironmentFlags` will contain what _would have_ been allowable. -### `process.arch` +### `process.arch` - + * [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) @@ -833,18 +833,18 @@ Possible values are: `'arm'`, `'arm64'`, `'ia32'`, `'mips'`,`'mipsel'`, `'ppc'`, ```mjs import { arch } from 'node:process'; -console.log(`This processor architecture is $arch`); +console.log(`This processor architecture is ${arch}`); ``` ```cjs const { arch } = require('node:process'); -console.log(`This processor architecture is $arch`); +console.log(`This processor architecture is ${arch}`); ``` -### `process.argv` +### `process.argv` - + * string\[] @@ -862,7 +862,7 @@ import { argv } from 'node:process'; // print process.argv argv.forEach((val, index) => { - console.log(`$index: $val`); + console.log(`${index}: ${val}`); }); ``` @@ -871,7 +871,7 @@ const { argv } = require('node:process'); // print process.argv argv.forEach((val, index) => { - console.log(`$index: $val`); + console.log(`${index}: ${val}`); }); ``` @@ -891,9 +891,9 @@ Would generate the output: 4: four ``` -### `process.argv0` +### `process.argv0` - + * [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) @@ -908,9 +908,9 @@ $ bash -c 'exec -a customArgv0 ./node' 'customArgv0' ``` -### `process.channel` +### `process.channel` - + * [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) @@ -919,9 +919,9 @@ If the Node.js process was spawned with an IPC channel (see the property is a reference to the IPC channel. If no IPC channel exists, this property is `undefined`. -#### `process.channel.ref()` +#### `process.channel.ref()` - + This method makes the IPC channel keep the event loop of the process running if `.unref()` has been called before. @@ -930,9 +930,9 @@ Typically, this is managed through the number of `'disconnect'` and `'message'` listeners on the `process` object. However, this method can be used to explicitly request a specific behavior. -#### `process.channel.unref()` +#### `process.channel.unref()` - + This method makes the IPC channel not keep the event loop of the process running, and lets it finish even while the channel is open. @@ -941,9 +941,9 @@ Typically, this is managed through the number of `'disconnect'` and `'message'` listeners on the `process` object. However, this method can be used to explicitly request a specific behavior. -### `process.chdir(directory)` +### `process.chdir(directory)` - + * `directory` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) @@ -959,7 +959,7 @@ try { chdir('/tmp'); console.log(`New directory: ${cwd()}`); } catch (err) { - console.error(`chdir: $err`); + console.error(`chdir: ${err}`); } ``` @@ -971,15 +971,15 @@ try { chdir('/tmp'); console.log(`New directory: ${cwd()}`); } catch (err) { - console.error(`chdir: $err`); + console.error(`chdir: ${err}`); } ``` This feature is not available in [`Worker`][] threads. -### `process.config` +### `process.config` - + * [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) @@ -1028,9 +1028,9 @@ Modifying the `process.config` property, or any child-property of the `process.config` object has been deprecated. The `process.config` will be made read-only in a future release. -### `process.connected` +### `process.connected` - + * [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) @@ -1042,9 +1042,9 @@ and [Cluster][] documentation), the `process.connected` property will return Once `process.connected` is `false`, it is no longer possible to send messages over the IPC channel using `process.send()`. -### `process.cpuUsage([previousValue])` +### `process.cpuUsage([previousValue])` - + * `previousValue` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) A previous return value from calling `process.cpuUsage()` @@ -1089,9 +1089,9 @@ console.log(cpuUsage(startUsage)); // { user: 514883, system: 11226 } ``` -### `process.cwd()` +### `process.cwd()` - + * Returns: [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) @@ -1110,9 +1110,9 @@ const { cwd } = require('node:process'); console.log(`Current directory: ${cwd()}`); ``` -### `process.debugPort` +### `process.debugPort` - + * [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) @@ -1130,9 +1130,9 @@ const process = require('node:process'); process.debugPort = 5858; ``` -### `process.disconnect()` +### `process.disconnect()` - + If the Node.js process is spawned with an IPC channel (see the [Child Process][] and [Cluster][] documentation), the `process.disconnect()` method will close the @@ -1145,9 +1145,9 @@ The effect of calling `process.disconnect()` is the same as calling If the Node.js process was not spawned with an IPC channel, `process.disconnect()` will be `undefined`. -### `process.dlopen(module, filename[, flags])` +### `process.dlopen(module, filename[, flags])` - + * `module` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) * `filename` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) @@ -1192,9 +1192,9 @@ dlopen(module, join(__dirname, 'local.node'), constants.dlopen.RTLD_NOW); module.exports.foo(); ``` -### `process.emitWarning(warning[, options])` +### `process.emitWarning(warning[, options])` - + * `warning` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Error`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error) The warning to emit. * `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) @@ -1266,9 +1266,9 @@ process.on('warning', (warning) => { If `warning` is passed as an `Error` object, the `options` argument is ignored. -### `process.emitWarning(warning[, type[, code]][, ctor])` +### `process.emitWarning(warning[, type[, code]][, ctor])` - + * `warning` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Error`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error) The warning to emit. * `type` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) When `warning` is a `String`, `type` is the name to use @@ -1435,9 +1435,9 @@ emitMyWarning(); // Emits nothing ``` -### `process.env` +### `process.env` - + * [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) @@ -1559,9 +1559,9 @@ to the [`Worker`][] constructor. Changes to `process.env` will not be visible across [`Worker`][] threads, and only the main thread can make changes that are visible to the operating system or to native add-ons. -### `process.execArgv` +### `process.execArgv` - + * string\[] @@ -1595,9 +1595,9 @@ And `process.argv`: Refer to [`Worker` constructor][] for the detailed behavior of worker threads with this property. -### `process.execPath` +### `process.execPath` - + * [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) @@ -1610,9 +1610,9 @@ that started the Node.js process. Symbolic links, if any, are resolved. '/usr/local/bin/node' ``` -### `process.exit([code])` +### `process.exit([code])` - + * `code` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The exit code. **Default:** `0`. @@ -1710,9 +1710,9 @@ is safer than calling `process.exit()`. In [`Worker`][] threads, this function stops the current thread rather than the current process. -### `process.exitCode` +### `process.exitCode` - + * [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) @@ -1723,11 +1723,11 @@ a code. Specifying a code to [`process.exit(code)`][`process.exit()`] will override any previous setting of `process.exitCode`. -### `process.getActiveResourcesInfo()` +### `process.getActiveResourcesInfo()` - + - + * Returns: string\[] @@ -1759,9 +1759,9 @@ console.log('After:', getActiveResourcesInfo()); // After: [ 'TTYWrap', 'TTYWrap', 'TTYWrap', 'Timeout' ] ``` -### `process.getegid()` +### `process.getegid()` - + The `process.getegid()` method returns the numerical effective group identity of the Node.js process. (See getegid(2).) @@ -1785,9 +1785,9 @@ if (process.getegid) { This function is only available on POSIX platforms (i.e. not Windows or Android). -### `process.geteuid()` +### `process.geteuid()` - + * Returns: [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) @@ -1813,9 +1813,9 @@ if (process.geteuid) { This function is only available on POSIX platforms (i.e. not Windows or Android). -### `process.getgid()` +### `process.getgid()` - + * Returns: [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) @@ -1841,9 +1841,9 @@ if (process.getgid) { This function is only available on POSIX platforms (i.e. not Windows or Android). -### `process.getgroups()` +### `process.getgroups()` - + * Returns: integer\[] @@ -1870,9 +1870,9 @@ if (process.getgroups) { This function is only available on POSIX platforms (i.e. not Windows or Android). -### `process.getuid()` +### `process.getuid()` - + * Returns: [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) @@ -1898,20 +1898,20 @@ if (process.getuid) { This function is only available on POSIX platforms (i.e. not Windows or Android). -### `process.hasUncaughtExceptionCaptureCallback()` +### `process.hasUncaughtExceptionCaptureCallback()` - + * Returns: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) Indicates whether a callback has been set using [`process.setUncaughtExceptionCaptureCallback()`][]. -### `process.hrtime([time])` +### `process.hrtime([time])` - + - + * `time` integer\[] The result of a previous call to `process.hrtime()` * Returns: integer\[] @@ -1965,9 +1965,9 @@ setTimeout(() => { }, 1000); ``` -### `process.hrtime.bigint()` +### `process.hrtime.bigint()` - + * Returns: [`bigint`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt) @@ -2008,9 +2008,9 @@ setTimeout(() => { }, 1000); ``` -### `process.initgroups(user, extraGroup)` +### `process.initgroups(user, extraGroup)` - + * `user` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The user name or numeric identifier. * `extraGroup` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) A group name or numeric identifier. @@ -2046,9 +2046,9 @@ This function is only available on POSIX platforms (i.e. not Windows or Android). This feature is not available in [`Worker`][] threads. -### `process.kill(pid[, signal])` +### `process.kill(pid[, signal])` - + * `pid` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) A process ID * `signal` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The signal to send, either as a string or number. @@ -2102,11 +2102,11 @@ process.kill(process.pid, 'SIGHUP'); When `SIGUSR1` is received by a Node.js process, Node.js will start the debugger. See [Signal Events][]. -### `process.mainModule` +### `process.mainModule` - + - + * [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) @@ -2119,9 +2119,9 @@ safe to assume that the two refer to the same module. As with [`require.main`][], `process.mainModule` will be `undefined` if there is no entry script. -### `process.memoryUsage()` +### `process.memoryUsage()` - + * Returns: [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) * `rss` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) @@ -2180,9 +2180,9 @@ The `process.memoryUsage()` method iterates over each page to gather information about memory usage which might be slow depending on the program memory allocations. -### `process.memoryUsage.rss()` +### `process.memoryUsage.rss()` - + * Returns: [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) @@ -2210,9 +2210,9 @@ console.log(memoryUsage.rss()); // 35655680 ``` -### `process.nextTick(callback[, ...args])` +### `process.nextTick(callback[, ...args])` - + * `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) * `...args` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) Additional arguments to pass when invoking the `callback` @@ -2424,9 +2424,9 @@ and handle the errors. When in doubt, unless the specific capabilities of `process.nextTick()` are needed, use `queueMicrotask()`. -### `process.noDeprecation` +### `process.noDeprecation` - + * [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) @@ -2436,9 +2436,9 @@ the [`'warning'` event][process_warning] and the [`emitWarning()` method][process_emit_warning] for more information about this flag's behavior. -### `process.pid` +### `process.pid` - + * [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) @@ -2447,18 +2447,18 @@ The `process.pid` property returns the PID of the process. ```mjs import { pid } from 'node:process'; -console.log(`This process is pid $pid`); +console.log(`This process is pid ${pid}`); ``` ```cjs const { pid } = require('node:process'); -console.log(`This process is pid $pid`); +console.log(`This process is pid ${pid}`); ``` -### `process.platform` +### `process.platform` - + * [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) @@ -2478,22 +2478,22 @@ Currently possible values are: ```mjs import { platform } from 'node:process'; -console.log(`This platform is $platform`); +console.log(`This platform is ${platform}`); ``` ```cjs const { platform } = require('node:process'); -console.log(`This platform is $platform`); +console.log(`This platform is ${platform}`); ``` The value `'android'` may also be returned if the Node.js is built on the Android operating system. However, Android support in Node.js [is experimental][Android building]. -### `process.ppid` +### `process.ppid` - + * [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) @@ -2503,18 +2503,18 @@ current process. ```mjs import { ppid } from 'node:process'; -console.log(`The parent process is pid $ppid`); +console.log(`The parent process is pid ${ppid}`); ``` ```cjs const { ppid } = require('node:process'); -console.log(`The parent process is pid $ppid`); +console.log(`The parent process is pid ${ppid}`); ``` -### `process.release` +### `process.release` - + * [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) @@ -2560,9 +2560,9 @@ In custom builds from non-release versions of the source tree, only the `name` property may be present. The additional properties should not be relied upon to exist. -### `process.report` +### `process.report` - + * [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) @@ -2570,9 +2570,9 @@ relied upon to exist. reports for the current process. Additional documentation is available in the [report documentation][]. -#### `process.report.compact` +#### `process.report.compact` - + * [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) @@ -2583,18 +2583,18 @@ human consumption. ```mjs import { report } from 'node:process'; -console.log(`Reports are compact? $report.compact`); +console.log(`Reports are compact? ${report.compact}`); ``` ```cjs const { report } = require('node:process'); -console.log(`Reports are compact? $report.compact`); +console.log(`Reports are compact? ${report.compact}`); ``` -#### `process.report.directory` +#### `process.report.directory` - + * [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) @@ -2605,18 +2605,18 @@ Node.js process. ```mjs import { report } from 'node:process'; -console.log(`Report directory is $report.directory`); +console.log(`Report directory is ${report.directory}`); ``` ```cjs const { report } = require('node:process'); -console.log(`Report directory is $report.directory`); +console.log(`Report directory is ${report.directory}`); ``` -#### `process.report.filename` +#### `process.report.filename` - + * [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) @@ -2630,18 +2630,18 @@ the report is written to the stdout or stderr of the process respectively. ```mjs import { report } from 'node:process'; -console.log(`Report filename is $report.filename`); +console.log(`Report filename is ${report.filename}`); ``` ```cjs const { report } = require('node:process'); -console.log(`Report filename is $report.filename`); +console.log(`Report filename is ${report.filename}`); ``` -#### `process.report.getReport([err])` +#### `process.report.getReport([err])` - + * `err` [`Error`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error) A custom error used for reporting the JavaScript stack. * Returns: [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) @@ -2674,9 +2674,9 @@ fs.writeFileSync('my-report.log', util.inspect(data), 'utf8'); Additional documentation is available in the [report documentation][]. -#### `process.report.reportOnFatalError` +#### `process.report.reportOnFatalError` - + * [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) @@ -2686,18 +2686,18 @@ memory errors or failed C++ assertions. ```mjs import { report } from 'node:process'; -console.log(`Report on fatal error: $report.reportOnFatalError`); +console.log(`Report on fatal error: ${report.reportOnFatalError}`); ``` ```cjs const { report } = require('node:process'); -console.log(`Report on fatal error: $report.reportOnFatalError`); +console.log(`Report on fatal error: ${report.reportOnFatalError}`); ``` -#### `process.report.reportOnSignal` +#### `process.report.reportOnSignal` - + * [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) @@ -2707,18 +2707,18 @@ signal specified by `process.report.signal`. ```mjs import { report } from 'node:process'; -console.log(`Report on signal: $report.reportOnSignal`); +console.log(`Report on signal: ${report.reportOnSignal}`); ``` ```cjs const { report } = require('node:process'); -console.log(`Report on signal: $report.reportOnSignal`); +console.log(`Report on signal: ${report.reportOnSignal}`); ``` -#### `process.report.reportOnUncaughtException` +#### `process.report.reportOnUncaughtException` - + * [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) @@ -2727,18 +2727,18 @@ If `true`, a diagnostic report is generated on uncaught exception. ```mjs import { report } from 'node:process'; -console.log(`Report on exception: $report.reportOnUncaughtException`); +console.log(`Report on exception: ${report.reportOnUncaughtException}`); ``` ```cjs const { report } = require('node:process'); -console.log(`Report on exception: $report.reportOnUncaughtException`); +console.log(`Report on exception: ${report.reportOnUncaughtException}`); ``` -#### `process.report.signal` +#### `process.report.signal` - + * [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) @@ -2748,18 +2748,18 @@ The signal used to trigger the creation of a diagnostic report. Defaults to ```mjs import { report } from 'node:process'; -console.log(`Report signal: $report.signal`); +console.log(`Report signal: ${report.signal}`); ``` ```cjs const { report } = require('node:process'); -console.log(`Report signal: $report.signal`); +console.log(`Report signal: ${report.signal}`); ``` -#### `process.report.writeReport([filename][, err])` +#### `process.report.writeReport([filename][, err])` - + * `filename` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) Name of the file where the report is written. This should be a relative path, that will be appended to the directory specified in @@ -2791,9 +2791,9 @@ report.writeReport(); Additional documentation is available in the [report documentation][]. -### `process.resourceUsage()` +### `process.resourceUsage()` - + * Returns: [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) the resource usage for the current process. All of these values come from the `uv_getrusage` call which returns @@ -2892,9 +2892,9 @@ console.log(resourceUsage()); */ ``` -### `process.send(message[, sendHandle[, options]][, callback])` +### `process.send(message[, sendHandle[, options]][, callback])` - + * `message` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) * `sendHandle` [`net.Server`](/api/net#netserver) | [`net.Socket`](/api/net#netsocket) @@ -2916,9 +2916,9 @@ If Node.js was not spawned with an IPC channel, `process.send` will be The message goes through serialization and parsing. The resulting message might not be the same as what is originally sent. -### `process.setegid(id)` +### `process.setegid(id)` - + * `id` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) A group name or ID @@ -2936,7 +2936,7 @@ if (process.getegid && process.setegid) { process.setegid(501); console.log(`New gid: ${process.getegid()}`); } catch (err) { - console.log(`Failed to set gid: $err`); + console.log(`Failed to set gid: ${err}`); } } ``` @@ -2950,7 +2950,7 @@ if (process.getegid && process.setegid) { process.setegid(501); console.log(`New gid: ${process.getegid()}`); } catch (err) { - console.log(`Failed to set gid: $err`); + console.log(`Failed to set gid: ${err}`); } } ``` @@ -2959,9 +2959,9 @@ This function is only available on POSIX platforms (i.e. not Windows or Android). This feature is not available in [`Worker`][] threads. -### `process.seteuid(id)` +### `process.seteuid(id)` - + * `id` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) A user name or ID @@ -2979,7 +2979,7 @@ if (process.geteuid && process.seteuid) { process.seteuid(501); console.log(`New uid: ${process.geteuid()}`); } catch (err) { - console.log(`Failed to set uid: $err`); + console.log(`Failed to set uid: ${err}`); } } ``` @@ -2993,7 +2993,7 @@ if (process.geteuid && process.seteuid) { process.seteuid(501); console.log(`New uid: ${process.geteuid()}`); } catch (err) { - console.log(`Failed to set uid: $err`); + console.log(`Failed to set uid: ${err}`); } } ``` @@ -3002,9 +3002,9 @@ This function is only available on POSIX platforms (i.e. not Windows or Android). This feature is not available in [`Worker`][] threads. -### `process.setgid(id)` +### `process.setgid(id)` - + * `id` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The group name or ID @@ -3022,7 +3022,7 @@ if (process.getgid && process.setgid) { process.setgid(501); console.log(`New gid: ${process.getgid()}`); } catch (err) { - console.log(`Failed to set gid: $err`); + console.log(`Failed to set gid: ${err}`); } } ``` @@ -3036,7 +3036,7 @@ if (process.getgid && process.setgid) { process.setgid(501); console.log(`New gid: ${process.getgid()}`); } catch (err) { - console.log(`Failed to set gid: $err`); + console.log(`Failed to set gid: ${err}`); } } ``` @@ -3045,9 +3045,9 @@ This function is only available on POSIX platforms (i.e. not Windows or Android). This feature is not available in [`Worker`][] threads. -### `process.setgroups(groups)` +### `process.setgroups(groups)` - + * `groups` integer\[] @@ -3065,7 +3065,7 @@ if (process.getgroups && process.setgroups) { process.setgroups([501]); console.log(process.getgroups()); // new groups } catch (err) { - console.log(`Failed to set groups: $err`); + console.log(`Failed to set groups: ${err}`); } } ``` @@ -3078,7 +3078,7 @@ if (process.getgroups && process.setgroups) { process.setgroups([501]); console.log(process.getgroups()); // new groups } catch (err) { - console.log(`Failed to set groups: $err`); + console.log(`Failed to set groups: ${err}`); } } ``` @@ -3087,11 +3087,11 @@ This function is only available on POSIX platforms (i.e. not Windows or Android). This feature is not available in [`Worker`][] threads. -### `process.setuid(id)` +### `process.setuid(id)` - + -* `id` {integer | string} +* `id` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The `process.setuid(id)` method sets the user identity of the process. (See setuid(2).) The `id` can be passed as either a numeric ID or a username string. @@ -3107,7 +3107,7 @@ if (process.getuid && process.setuid) { process.setuid(501); console.log(`New uid: ${process.getuid()}`); } catch (err) { - console.log(`Failed to set uid: $err`); + console.log(`Failed to set uid: ${err}`); } } ``` @@ -3121,7 +3121,7 @@ if (process.getuid && process.setuid) { process.setuid(501); console.log(`New uid: ${process.getuid()}`); } catch (err) { - console.log(`Failed to set uid: $err`); + console.log(`Failed to set uid: ${err}`); } } ``` @@ -3130,11 +3130,11 @@ This function is only available on POSIX platforms (i.e. not Windows or Android). This feature is not available in [`Worker`][] threads. -### `process.setSourceMapsEnabled(val)` +### `process.setSourceMapsEnabled(val)` - + - + * `val` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) @@ -3147,9 +3147,9 @@ It provides same features as launching Node.js process with commandline options Only source maps in JavaScript files that are loaded after source maps has been enabled will be parsed and loaded. -### `process.setUncaughtExceptionCaptureCallback(fn)` +### `process.setUncaughtExceptionCaptureCallback(fn)` - + * `fn` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) | [`null`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type) @@ -3171,7 +3171,7 @@ throw an error. Using this function is mutually exclusive with using the deprecated [`domain`][] built-in module. -### `process.stderr` +### `process.stderr` * [`Stream`](/api/stream#stream) @@ -3183,7 +3183,7 @@ a [Writable][] stream. `process.stderr` differs from other Node.js streams in important ways. See [note on process I/O][] for more information. -#### `process.stderr.fd` +#### `process.stderr.fd` * [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) @@ -3191,7 +3191,7 @@ This property refers to the value of underlying file descriptor of `process.stderr`. The value is fixed at `2`. In [`Worker`][] threads, this field does not exist. -### `process.stdin` +### `process.stdin` * [`Stream`](/api/stream#stream) @@ -3210,7 +3210,7 @@ In "old" streams mode the `stdin` stream is paused by default, so one must call `process.stdin.resume()` to read from it. Note also that calling `process.stdin.resume()` itself would switch stream to "old" mode. -#### `process.stdin.fd` +#### `process.stdin.fd` * [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) @@ -3218,7 +3218,7 @@ This property refers to the value of underlying file descriptor of `process.stdin`. The value is fixed at `0`. In [`Worker`][] threads, this field does not exist. -### `process.stdout` +### `process.stdout` * [`Stream`](/api/stream#stream) @@ -3244,7 +3244,7 @@ stdin.pipe(stdout); `process.stdout` differs from other Node.js streams in important ways. See [note on process I/O][] for more information. -#### `process.stdout.fd` +#### `process.stdout.fd` * [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) @@ -3300,9 +3300,9 @@ false See the [TTY][] documentation for more information. -### `process.throwDeprecation` +### `process.throwDeprecation` - + * [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) @@ -3329,9 +3329,9 @@ Thrown: [DeprecationWarning: test] { name: 'DeprecationWarning' } ``` -### `process.title` +### `process.title` - + * [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) @@ -3352,9 +3352,9 @@ Assigning a value to `process.title` might not result in an accurate label within process manager applications such as macOS Activity Monitor or Windows Services Manager. -### `process.traceDeprecation` +### `process.traceDeprecation` - + * [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) @@ -3364,7 +3364,7 @@ documentation for the [`'warning'` event][process_warning] and the [`emitWarning()` method][process_emit_warning] for more information about this flag's behavior. -### `process.umask()` +### `process.umask()` - the process-wide umask to be written twice. This introduces a race condition\n> between threads, and is a potential security vulnerability. There is no safe,\n> cross-platform alternative API."}}} /> + between threads, and is a potential security vulnerability. There is no safe,\n> cross-platform alternative API."}}} /> `process.umask()` returns the Node.js process's file mode creation mask. Child processes inherit the mask from the parent process. -### `process.umask(mask)` +### `process.umask(mask)` - + * `mask` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) @@ -3413,9 +3413,9 @@ console.log( In [`Worker`][] threads, `process.umask(mask)` will throw an exception. -### `process.uptime()` +### `process.uptime()` - + * Returns: [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) @@ -3425,9 +3425,9 @@ process has been running. The return value includes fractions of a second. Use `Math.floor()` to get whole seconds. -### `process.version` +### `process.version` - + * [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) @@ -3436,23 +3436,23 @@ The `process.version` property contains the Node.js version string. ```mjs import { version } from 'node:process'; -console.log(`Version: $version`); +console.log(`Version: ${version}`); // Version: v14.8.0 ``` ```cjs const { version } = require('node:process'); -console.log(`Version: $version`); +console.log(`Version: ${version}`); // Version: v14.8.0 ``` To get the version string without the prepended _v_, use `process.versions.node`. -### `process.versions` +### `process.versions` - + * [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) diff --git a/content/api/v18/punycode.en.md b/content/api/v18/punycode.en.md index ea64d9f503..8547089214 100644 --- a/content/api/v18/punycode.en.md +++ b/content/api/v18/punycode.en.md @@ -2,17 +2,17 @@ title: 'punycode' displayTitle: 'Punycode' category: 'api' -editPage: 'https://github.com/nodejs/node/blob/v18.8.0/doc/api/punycode.md' +editPage: 'https://github.com/nodejs/node/blob/v18.9.0/doc/api/punycode.md' version: 'v18' --- - + - + - + - + **The version of the punycode module bundled in Node.js is being deprecated.** In a future major version of Node.js this module will be removed. Users @@ -43,9 +43,9 @@ The `punycode` module is a third-party dependency used by Node.js and made available to developers as a convenience. Fixes or other modifications to the module must be directed to the [Punycode.js][] project. -### `punycode.decode(string)` +### `punycode.decode(string)` - + * `string` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) @@ -57,9 +57,9 @@ punycode.decode('maana-pta'); // 'mañana' punycode.decode('--dqo34k'); // '☃-⌘' ``` -### `punycode.encode(string)` +### `punycode.encode(string)` - + * `string` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) @@ -71,9 +71,9 @@ punycode.encode('mañana'); // 'maana-pta' punycode.encode('☃-⌘'); // '--dqo34k' ``` -### `punycode.toASCII(domain)` +### `punycode.toASCII(domain)` - + * `domain` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) @@ -89,9 +89,9 @@ punycode.toASCII('☃-⌘.com'); // 'xn----dqo34k.com' punycode.toASCII('example.com'); // 'example.com' ``` -### `punycode.toUnicode(domain)` +### `punycode.toUnicode(domain)` - + * `domain` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) @@ -106,13 +106,13 @@ punycode.toUnicode('xn----dqo34k.com'); // '☃-⌘.com' punycode.toUnicode('example.com'); // 'example.com' ``` -### `punycode.ucs2` +### `punycode.ucs2` - + -#### `punycode.ucs2.decode(string)` +#### `punycode.ucs2.decode(string)` - + * `string` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) @@ -125,9 +125,9 @@ punycode.ucs2.decode('abc'); // [0x61, 0x62, 0x63] punycode.ucs2.decode('\uD834\uDF06'); // [0x1D306] ``` -#### `punycode.ucs2.encode(codePoints)` +#### `punycode.ucs2.encode(codePoints)` - + * `codePoints` integer\[] @@ -139,9 +139,9 @@ punycode.ucs2.encode([0x61, 0x62, 0x63]); // 'abc' punycode.ucs2.encode([0x1D306]); // '\uD834\uDF06' ``` -### `punycode.version` +### `punycode.version` - + * [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) diff --git a/content/api/v18/querystring.en.md b/content/api/v18/querystring.en.md index 39bf0127f3..c61f5f3de4 100644 --- a/content/api/v18/querystring.en.md +++ b/content/api/v18/querystring.en.md @@ -2,17 +2,17 @@ title: 'querystring' displayTitle: 'Query string' category: 'api' -editPage: 'https://github.com/nodejs/node/blob/v18.8.0/doc/api/querystring.md' +editPage: 'https://github.com/nodejs/node/blob/v18.9.0/doc/api/querystring.md' version: 'v18' --- - + - + - + - + The `node:querystring` module provides utilities for parsing and formatting URL query strings. It can be accessed using: @@ -24,21 +24,21 @@ const querystring = require('node:querystring'); The `querystring` API is considered Legacy. While it is still maintained, new code should use the [`URLSearchParams`](/api/url#urlsearchparams) API instead. -### `querystring.decode()` +### `querystring.decode()` - + The `querystring.decode()` function is an alias for `querystring.parse()`. -### `querystring.encode()` +### `querystring.encode()` - + The `querystring.encode()` function is an alias for `querystring.stringify()`. -### `querystring.escape(str)` +### `querystring.escape(str)` - + * `str` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) @@ -51,9 +51,9 @@ generally not expected to be used directly. It is exported primarily to allow application code to provide a replacement percent-encoding implementation if necessary by assigning `querystring.escape` to an alternative function. -### `querystring.parse(str[, sep[, eq[, options]]])` +### `querystring.parse(str[, sep[, eq[, options]]])` - + * `str` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The URL query string to parse * `sep` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The substring used to delimit key and value pairs in the @@ -97,9 +97,9 @@ querystring.parse('w=%D6%D0%CE%C4&foo=bar', null, null, { decodeURIComponent: gbkDecodeURIComponent }); ``` -### `querystring.stringify(obj[, sep[, eq[, options]]])` +### `querystring.stringify(obj[, sep[, eq[, options]]])` - + * `obj` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) The object to serialize into a URL query string * `sep` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The substring used to delimit key and value pairs in the @@ -138,9 +138,9 @@ querystring.stringify({ w: '中文', foo: 'bar' }, null, null, { encodeURIComponent: gbkEncodeURIComponent }); ``` -### `querystring.unescape(str)` +### `querystring.unescape(str)` - + * `str` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) diff --git a/content/api/v18/readline.en.md b/content/api/v18/readline.en.md index a9590e9718..229eb7589b 100644 --- a/content/api/v18/readline.en.md +++ b/content/api/v18/readline.en.md @@ -2,15 +2,15 @@ title: 'readline' displayTitle: 'Readline' category: 'api' -editPage: 'https://github.com/nodejs/node/blob/v18.8.0/doc/api/readline.md' +editPage: 'https://github.com/nodejs/node/blob/v18.9.0/doc/api/readline.md' version: 'v18' --- - + - + - + The `node:readline` module provides an interface for reading data from a [Readable][] stream (such as [`process.stdin`][]) one line at a time. @@ -46,7 +46,7 @@ const rl = readline.createInterface({ input, output }); const answer = await rl.question('What do you think of Node.js? '); -console.log(`Thank you for your valuable feedback: $answer`); +console.log(`Thank you for your valuable feedback: ${answer}`); rl.close(); ``` @@ -59,7 +59,7 @@ const rl = readline.createInterface({ input, output }); rl.question('What do you think of Node.js? ', (answer) => { // TODO: Log the answer in a database - console.log(`Thank you for your valuable feedback: $answer`); + console.log(`Thank you for your valuable feedback: ${answer}`); rl.close(); }); @@ -71,9 +71,9 @@ received on the `input` stream. -### `InterfaceConstructor` +### `InterfaceConstructor` - + * Extends: [`EventEmitter`](/api/events#eventemitter) @@ -84,9 +84,9 @@ single `output` [Writable][] stream. The `output` stream is used to print prompts for user input that arrives on, and is read from, the `input` stream. -#### `'close'` +#### `'close'` - + The `'close'` event is emitted when one of the following occur: @@ -104,9 +104,9 @@ The listener function is called without passing any arguments. The `InterfaceConstructor` instance is finished once the `'close'` event is emitted. -#### `'line'` +#### `'line'` - + The `'line'` event is emitted whenever the `input` stream receives an end-of-line input (`\n`, `\r`, or `\r\n`). This usually occurs when the user @@ -120,13 +120,13 @@ received input. ```js rl.on('line', (input) => { - console.log(`Received: $input`); + console.log(`Received: ${input}`); }); ``` -#### `'history'` +#### `'history'` - + The `'history'` event is emitted whenever the history array has changed. @@ -141,13 +141,13 @@ a password. ```js rl.on('history', (history) => { - console.log(`Received: $history`); + console.log(`Received: ${history}`); }); ``` -#### `'pause'` +#### `'pause'` - + The `'pause'` event is emitted when one of the following occur: @@ -163,9 +163,9 @@ rl.on('pause', () => { }); ``` -#### `'resume'` +#### `'resume'` - + The `'resume'` event is emitted whenever the `input` stream is resumed. @@ -177,9 +177,9 @@ rl.on('resume', () => { }); ``` -#### `'SIGCONT'` +#### `'SIGCONT'` - + The `'SIGCONT'` event is emitted when a Node.js process previously moved into the background using Ctrl+Z (i.e. `SIGTSTP`) is then @@ -199,9 +199,9 @@ rl.on('SIGCONT', () => { The `'SIGCONT'` event is _not_ supported on Windows. -#### `'SIGINT'` +#### `'SIGINT'` - + The `'SIGINT'` event is emitted whenever the `input` stream receives a Ctrl+C input, known typically as `SIGINT`. If there are no @@ -218,9 +218,9 @@ rl.on('SIGINT', () => { }); ``` -#### `'SIGTSTP'` +#### `'SIGTSTP'` - + The `'SIGTSTP'` event is emitted when the `input` stream receives a Ctrl+Z input, typically known as `SIGTSTP`. If there are @@ -245,9 +245,9 @@ rl.on('SIGTSTP', () => { The `'SIGTSTP'` event is _not_ supported on Windows. -#### `rl.close()` +#### `rl.close()` - + The `rl.close()` method closes the `InterfaceConstructor` instance and relinquishes control over the `input` and `output` streams. When called, @@ -256,9 +256,9 @@ the `'close'` event will be emitted. Calling `rl.close()` does not immediately stop other events (including `'line'`) from being emitted by the `InterfaceConstructor` instance. -#### `rl.pause()` +#### `rl.pause()` - + The `rl.pause()` method pauses the `input` stream, allowing it to be resumed later if necessary. @@ -266,9 +266,9 @@ later if necessary. Calling `rl.pause()` does not immediately pause other events (including `'line'`) from being emitted by the `InterfaceConstructor` instance. -#### `rl.prompt([preserveCursor])` +#### `rl.prompt([preserveCursor])` - + * `preserveCursor` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) If `true`, prevents the cursor placement from being reset to `0`. @@ -283,9 +283,9 @@ paused. If the `InterfaceConstructor` was created with `output` set to `null` or `undefined` the prompt is not written. -#### `rl.question(query[, options], callback)` +#### `rl.question(query[, options], callback)` - + * `query` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) A statement or query to write to `output`, prepended to the prompt. @@ -315,7 +315,7 @@ Example usage: ```js rl.question('What is your favorite food? ', (answer) => { - console.log(`Oh, so your favorite food is $answer`); + console.log(`Oh, so your favorite food is ${answer}`); }); ``` @@ -326,7 +326,7 @@ const ac = new AbortController(); const signal = ac.signal; rl.question('What is your favorite food? ', { signal }, (answer) => { - console.log(`Oh, so your favorite food is $answer`); + console.log(`Oh, so your favorite food is ${answer}`); }); signal.addEventListener('abort', () => { @@ -336,32 +336,32 @@ signal.addEventListener('abort', () => { setTimeout(() => ac.abort(), 10000); ``` -#### `rl.resume()` +#### `rl.resume()` - + The `rl.resume()` method resumes the `input` stream if it has been paused. -#### `rl.setPrompt(prompt)` +#### `rl.setPrompt(prompt)` - + * `prompt` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The `rl.setPrompt()` method sets the prompt that will be written to `output` whenever `rl.prompt()` is called. -#### `rl.getPrompt()` +#### `rl.getPrompt()` - + * Returns: [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) the current prompt string The `rl.getPrompt()` method returns the current prompt used by `rl.prompt()`. -#### `rl.write(data[, key])` +#### `rl.write(data[, key])` - + * `data` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) * `key` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) @@ -392,9 +392,9 @@ rl.write(null, { ctrl: true, name: 'u' }); The `rl.write()` method will write the data to the `readline` `Interface`'s `input` _as if it were provided by the user_. -#### `rl[Symbol.asyncIterator]()` +#### `rl[Symbol.asyncIterator]()` - + * Returns: [`AsyncIterator`](https://tc39.github.io/ecma262/#sec-asynciterator-interface) @@ -428,9 +428,9 @@ async function processLineByLine() { invoked. Having asynchronous operations between interface creation and asynchronous iteration may result in missed lines. -#### `rl.line` +#### `rl.line` - + * [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) @@ -462,9 +462,9 @@ process.stdin.on('keypress', (c, k) => { }); ``` -#### `rl.cursor` +#### `rl.cursor` - + * [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) | [`undefined`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type) @@ -475,9 +475,9 @@ reading input from a TTY stream. The position of cursor determines the portion of the input string that will be modified as input is processed, as well as the column where the terminal caret will be rendered. -#### `rl.getCursorPos()` +#### `rl.getCursorPos()` - + * Returns: [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) * `rows` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) the row of the prompt the cursor currently lands on @@ -489,13 +489,13 @@ line prompts are included in the calculations. ### Promises API - + - + -#### `readlinePromises.Interface` +#### `readlinePromises.Interface` - + * Extends: [`readline.InterfaceConstructor`](/api/readline#interfaceconstructor) @@ -505,9 +505,9 @@ single `input` [Readable][] stream and a single `output` [Writable][] stream. The `output` stream is used to print prompts for user input that arrives on, and is read from, the `input` stream. -##### `rl.question(query[, options])` +##### `rl.question(query[, options])` - + * `query` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) A statement or query to write to `output`, prepended to the prompt. @@ -533,7 +533,7 @@ Example usage: ```mjs const answer = await rl.question('What is your favorite food? '); -console.log(`Oh, so your favorite food is $answer`); +console.log(`Oh, so your favorite food is ${answer}`); ``` Using an `AbortSignal` to cancel a question. @@ -546,24 +546,24 @@ signal.addEventListener('abort', () => { }, { once: true }); const answer = await rl.question('What is your favorite food? ', { signal }); -console.log(`Oh, so your favorite food is $answer`); +console.log(`Oh, so your favorite food is ${answer}`); ``` -#### `readlinePromises.Readline` +#### `readlinePromises.Readline` - + -##### `new readlinePromises.Readline(stream[, options])` +##### `new readlinePromises.Readline(stream[, options])` - + * `stream` [`stream.Writable`](/api/stream#streamwritable) A [TTY][] stream. * `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) * `autoCommit` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) If `true`, no need to call `rl.commit()`. -##### `rl.clearLine(dir)` +##### `rl.clearLine(dir)` - + * `dir` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) * `-1`: to the left from cursor @@ -577,9 +577,9 @@ direction identified by `dir`. Call `rl.commit()` to see the effect of this method, unless `autoCommit: true` was passed to the constructor. -##### `rl.clearScreenDown()` +##### `rl.clearScreenDown()` - + * Returns: this @@ -589,18 +589,18 @@ cursor down. Call `rl.commit()` to see the effect of this method, unless `autoCommit: true` was passed to the constructor. -##### `rl.commit()` +##### `rl.commit()` - + * Returns: [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) The `rl.commit()` method sends all the pending actions to the associated `stream` and clears the internal list of pending actions. -##### `rl.cursorTo(x[, y])` +##### `rl.cursorTo(x[, y])` - + * `x` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) * `y` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) @@ -611,9 +611,9 @@ that moves cursor to the specified position in the associated `stream`. Call `rl.commit()` to see the effect of this method, unless `autoCommit: true` was passed to the constructor. -##### `rl.moveCursor(dx, dy)` +##### `rl.moveCursor(dx, dy)` - + * `dx` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) * `dy` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) @@ -625,18 +625,18 @@ associated `stream`. Call `rl.commit()` to see the effect of this method, unless `autoCommit: true` was passed to the constructor. -##### `rl.rollback()` +##### `rl.rollback()` - + * Returns: this The `rl.rollback` methods clears the internal list of pending actions without sending it to the associated `stream`. -#### `readlinePromises.createInterface(options)` +#### `readlinePromises.createInterface(options)` - + * `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) * `input` [`stream.Readable`](/api/stream#streamreadable) The [Readable][] stream to listen to. This option @@ -691,7 +691,7 @@ is to listen for the `'line'` event: ```js rl.on('line', (line) => { - console.log(`Received: $line`); + console.log(`Received: ${line}`); }); ``` @@ -730,11 +730,11 @@ async function completer(linePartial) { ### Callback API - + -#### `readline.Interface` +#### `readline.Interface` - + * Extends: [`readline.InterfaceConstructor`](/api/readline#interfaceconstructor) @@ -744,9 +744,9 @@ single `input` [Readable][] stream and a single `output` [Writable][] stream. The `output` stream is used to print prompts for user input that arrives on, and is read from, the `input` stream. -##### `rl.question(query[, options], callback)` +##### `rl.question(query[, options], callback)` - + * `query` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) A statement or query to write to `output`, prepended to the prompt. @@ -776,7 +776,7 @@ Example usage: ```js rl.question('What is your favorite food? ', (answer) => { - console.log(`Oh, so your favorite food is $answer`); + console.log(`Oh, so your favorite food is ${answer}`); }); ``` @@ -787,7 +787,7 @@ const ac = new AbortController(); const signal = ac.signal; rl.question('What is your favorite food? ', { signal }, (answer) => { - console.log(`Oh, so your favorite food is $answer`); + console.log(`Oh, so your favorite food is ${answer}`); }); signal.addEventListener('abort', () => { @@ -797,9 +797,9 @@ signal.addEventListener('abort', () => { setTimeout(() => ac.abort(), 10000); ``` -#### `readline.clearLine(stream, dir[, callback])` +#### `readline.clearLine(stream, dir[, callback])` - + * `stream` [`stream.Writable`](/api/stream#streamwritable) * `dir` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) @@ -814,9 +814,9 @@ setTimeout(() => ac.abort(), 10000); The `readline.clearLine()` method clears current line of given [TTY][] stream in a specified direction identified by `dir`. -#### `readline.clearScreenDown(stream[, callback])` +#### `readline.clearScreenDown(stream[, callback])` - + * `stream` [`stream.Writable`](/api/stream#streamwritable) * `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) Invoked once the operation completes. @@ -827,9 +827,9 @@ in a specified direction identified by `dir`. The `readline.clearScreenDown()` method clears the given [TTY][] stream from the current position of the cursor down. -#### `readline.createInterface(options)` +#### `readline.createInterface(options)` - + * `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) * `input` [`stream.Readable`](/api/stream#streamreadable) The [Readable][] stream to listen to. This option @@ -886,7 +886,7 @@ listen for the `'line'` event: ```js rl.on('line', (line) => { - console.log(`Received: $line`); + console.log(`Received: ${line}`); }); ``` @@ -927,9 +927,9 @@ function completer(linePartial, callback) { } ``` -#### `readline.cursorTo(stream, x[, y][, callback])` +#### `readline.cursorTo(stream, x[, y][, callback])` - + * `stream` [`stream.Writable`](/api/stream#streamwritable) * `x` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) @@ -942,9 +942,9 @@ function completer(linePartial, callback) { The `readline.cursorTo()` method moves cursor to the specified position in a given [TTY][] `stream`. -#### `readline.moveCursor(stream, dx, dy[, callback])` +#### `readline.moveCursor(stream, dx, dy[, callback])` - + * `stream` [`stream.Writable`](/api/stream#streamwritable) * `dx` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) @@ -957,9 +957,9 @@ given [TTY][] `stream`. The `readline.moveCursor()` method moves the cursor _relative_ to its current position in a given [TTY][] `stream`. -### `readline.emitKeypressEvents(stream[, interface])` +### `readline.emitKeypressEvents(stream[, interface])` - + * `stream` [`stream.Readable`](/api/stream#streamreadable) * `interface` [`readline.InterfaceConstructor`](/api/readline#interfaceconstructor) @@ -1035,7 +1035,7 @@ async function processLineByLine() { for await (const line of rl) { // Each line in input.txt will be successively available here as `line`. - console.log(`Line from file: $line`); + console.log(`Line from file: ${line}`); } } @@ -1054,7 +1054,7 @@ const rl = readline.createInterface({ }); rl.on('line', (line) => { - console.log(`Line from file: $line`); + console.log(`Line from file: ${line}`); }); ``` diff --git a/content/api/v18/repl.en.md b/content/api/v18/repl.en.md index 574c4721b8..3f011cbaef 100644 --- a/content/api/v18/repl.en.md +++ b/content/api/v18/repl.en.md @@ -2,15 +2,15 @@ title: 'repl' displayTitle: 'REPL' category: 'api' -editPage: 'https://github.com/nodejs/node/blob/v18.8.0/doc/api/repl.md' +editPage: 'https://github.com/nodejs/node/blob/v18.9.0/doc/api/repl.md' version: 'v18' --- - + - + - + The `node:repl` module provides a Read-Eval-Print-Loop (REPL) implementation that is available both as a standalone program or includible in other @@ -58,7 +58,7 @@ The following special commands are supported by all REPL instances: > .editor // Entering editor mode (^D to finish, ^C to cancel) function welcome(name) { - return `Hello $name!`; + return `Hello ${name}!`; } welcome('Node.js User'); @@ -155,7 +155,7 @@ global or scoped variable, the input `fs` will be evaluated on-demand as ##### Global uncaught exceptions - + The REPL uses the [`domain`][] module to catch all uncaught exceptions for that REPL session. @@ -182,7 +182,7 @@ This use of the [`domain`][] module in the REPL has these side effects: ##### Assignment of the `_` (underscore) variable - + The default evaluator will, by default, assign the result of the most recently evaluated expression to the special variable `_` (underscore). @@ -212,7 +212,7 @@ Error: foo 'foo' ``` -##### `await` keyword +##### `await` keyword Support for the `await` keyword is enabled at the top level. @@ -250,7 +250,7 @@ undefined #### Reverse-i-search - + The REPL supports bi-directional reverse-i-search similar to [ZSH][]. It is triggered with Ctrl+R to search backward @@ -359,9 +359,9 @@ function myWriter(output) { } ``` -### `REPLServer` +### `REPLServer` - + * `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) See [`repl.start()`][] * Extends: [`readline.Interface`](/api/readline#readlineinterface) @@ -378,9 +378,9 @@ const firstInstance = repl.start(options); const secondInstance = new repl.REPLServer(options); ``` -#### `'exit'` +#### `'exit'` - + The `'exit'` event is emitted when the REPL is exited either by receiving the `.exit` command as input, the user pressing Ctrl+C twice @@ -396,9 +396,9 @@ replServer.on('exit', () => { }); ``` -#### `'reset'` +#### `'reset'` - + The `'reset'` event is emitted when the REPL's context is reset. This occurs whenever the `.clear` command is received as input _unless_ the REPL is using @@ -440,9 +440,9 @@ Clearing context... > ``` -#### `replServer.defineCommand(keyword, cmd)` +#### `replServer.defineCommand(keyword, cmd)` - + * `keyword` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The command keyword (_without_ a leading `.` character). * `cmd` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) | [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) The function to invoke when the command is processed. @@ -466,7 +466,7 @@ replServer.defineCommand('sayhello', { help: 'Say hello', action(name) { this.clearBufferedCommand(); - console.log(`Hello, $name!`); + console.log(`Hello, ${name}!`); this.displayPrompt(); } }); @@ -485,9 +485,9 @@ Hello, Node.js User! Goodbye! ``` -#### `replServer.displayPrompt([preserveCursor])` +#### `replServer.displayPrompt([preserveCursor])` - + * `preserveCursor` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) @@ -504,20 +504,20 @@ The `replServer.displayPrompt` method is primarily intended to be called from within the action function for commands registered using the `replServer.defineCommand()` method. -#### `replServer.clearBufferedCommand()` +#### `replServer.clearBufferedCommand()` - + The `replServer.clearBufferedCommand()` method clears any command that has been buffered but not yet executed. This method is primarily intended to be called from within the action function for commands registered using the `replServer.defineCommand()` method. -#### `replServer.parseREPLKeyword(keyword[, rest])` +#### `replServer.parseREPLKeyword(keyword[, rest])` - + - + * `keyword` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) the potential keyword to parse and execute * `rest` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) any parameters to the keyword command @@ -526,9 +526,9 @@ called from within the action function for commands registered using the An internal method used to parse and execute `REPLServer` keywords. Returns `true` if `keyword` is a valid keyword, otherwise `false`. -#### `replServer.setupHistory(historyPath, callback)` +#### `replServer.setupHistory(historyPath, callback)` - + * `historyPath` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) the path to the history file * `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) called when history writes are ready or upon error @@ -541,17 +541,17 @@ by default. However, this is not the case when creating a REPL programmatically. Use this method to initialize a history log file when working with REPL instances programmatically. -### `repl.builtinModules` +### `repl.builtinModules` - + * string\[] A list of the names of all Node.js modules, e.g., `'http'`. -### `repl.start([options])` +### `repl.start([options])` - + * `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) * `prompt` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The input prompt to display. **Default:** `'> '` @@ -720,10 +720,10 @@ possible to connect to a long-running Node.js process without restarting it. For an example of running a "full-featured" (`terminal`) REPL over a `net.Server` and `net.Socket` instance, see: -. +(https://gist.github.com/TooTallNate/2209310)[https://gist.github.com/TooTallNate/2209310]. For an example of running a REPL instance over [`curl(1)`][], see: -. +(https://gist.github.com/TooTallNate/2053342)[https://gist.github.com/TooTallNate/2053342]. [TTY keybindings]: (/api/readline#tty-keybindings) [ZSH]: https://en.wikipedia.org/wiki/Z_shell diff --git a/content/api/v18/report.en.md b/content/api/v18/report.en.md index e77a4480b4..50a41bf729 100644 --- a/content/api/v18/report.en.md +++ b/content/api/v18/report.en.md @@ -2,17 +2,17 @@ title: 'report' displayTitle: 'Diagnostic report' category: 'api' -editPage: 'https://github.com/nodejs/node/blob/v18.8.0/doc/api/report.md' +editPage: 'https://github.com/nodejs/node/blob/v18.9.0/doc/api/report.md' version: 'v18' --- - + - + - + - + Delivers a JSON-formatted diagnostic summary, written to a file. @@ -596,7 +596,7 @@ Specific API documentation can be found under ### Interaction with workers - + [`Worker`][] threads can create reports in the same way that the main thread does. diff --git a/content/api/v18/stream.en.md b/content/api/v18/stream.en.md index 8ae8df9cd3..bb495b630e 100644 --- a/content/api/v18/stream.en.md +++ b/content/api/v18/stream.en.md @@ -2,15 +2,15 @@ title: 'stream' displayTitle: 'Stream' category: 'api' -editPage: 'https://github.com/nodejs/node/blob/v18.8.0/doc/api/stream.md' +editPage: 'https://github.com/nodejs/node/blob/v18.9.0/doc/api/stream.md' version: 'v18' --- - + - + - + A stream is an abstract interface for working with streaming data in Node.js. The `node:stream` module provides an API for implementing the stream interface. @@ -56,7 +56,7 @@ and [`stream.addAbortSignal()`][]. #### Streams Promises API - + The `stream/promises` API provides an alternative set of asynchronous utility functions for streams that return `Promise` objects rather than using @@ -77,7 +77,7 @@ object mode is not safe. #### Buffering - + Both [`Writable`][] and [`Readable`][] streams will store data in an internal buffer. @@ -131,7 +131,7 @@ the internal buffers can be retrieved using `writable.writableBuffer` or ### API for stream consumers - + Almost all Node.js applications, no matter how simple, use streams in some manner. The following is an example of using streams in a Node.js application @@ -164,7 +164,7 @@ const server = http.createServer((req, res) => { } catch (er) { // uh oh! bad json! res.statusCode = 400; - return res.end(`error: $er.message`); + return res.end(`error: ${er.message}`); } }); }); @@ -232,15 +232,15 @@ myStream.write('some more data'); myStream.end('done writing data'); ``` -##### `stream.Writable` +##### `stream.Writable` - + - + ###### Event: `'close'` - + The `'close'` event is emitted when the stream and any of its underlying resources (a file descriptor, for example) have been closed. The event indicates @@ -251,7 +251,7 @@ created with the `emitClose` option. ###### Event: `'drain'` - + If a call to [`stream.write(chunk)`][stream-write] returns `false`, the `'drain'` event will be emitted when it is appropriate to resume writing data @@ -287,7 +287,7 @@ function writeOneMillionTimes(writer, data, encoding, callback) { ###### Event: `'error'` - + * [`Error`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error) @@ -303,7 +303,7 @@ After `'error'`, no further events other than `'close'` _should_ be emitted ###### Event: `'finish'` - + The `'finish'` event is emitted after the [`stream.end()`][stream-end] method has been called, and all data has been flushed to the underlying system. @@ -311,7 +311,7 @@ has been called, and all data has been flushed to the underlying system. ```js const writer = getWritableStreamSomehow(); for (let i = 0; i < 100; i++) { - writer.write(`hello, #$i!\n`); + writer.write(`hello, #${i}!\n`); } writer.on('finish', () => { console.log('All writes are now complete.'); @@ -321,7 +321,7 @@ writer.end('This is the end\n'); ###### Event: `'pipe'` - + * `src` [`stream.Readable`](/api/stream#streamreadable) source stream that is piping to this writable @@ -340,7 +340,7 @@ reader.pipe(writer); ###### Event: `'unpipe'` - + * `src` [`stream.Readable`](/api/stream#streamreadable) The source stream that [unpiped][`stream.unpipe()`] this writable @@ -365,7 +365,7 @@ reader.unpipe(writer); ###### `writable.cork()` - + The `writable.cork()` method forces all written data to be buffered in memory. The buffered data will be flushed when either the [`stream.uncork()`][] or @@ -384,7 +384,7 @@ See also: [`writable.uncork()`][], [`writable._writev()`][stream-_writev]. ###### `writable.destroy([error])` - + * `error` [`Error`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error) Optional, an error to emit with `'error'` event. * Returns: [`this`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this) @@ -435,7 +435,7 @@ but instead implement [`writable._destroy()`][writable-_destroy]. ###### `writable.closed` - + * [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) @@ -443,7 +443,7 @@ Is `true` after `'close'` has been emitted. ###### `writable.destroyed` - + * [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) @@ -461,9 +461,9 @@ console.log(myStream.destroyed); // true ###### `writable.end([chunk[, encoding]][, callback])` - + -* `chunk` {string|Buffer|Uint8Array|any} Optional data to write. For streams +* `chunk` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`Uint8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array) | [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) Optional data to write. For streams not operating in object mode, `chunk` must be a string, `Buffer` or `Uint8Array`. For object mode streams, `chunk` may be any JavaScript value other than `null`. @@ -490,7 +490,7 @@ file.end('world!'); ###### `writable.setDefaultEncoding(encoding)` - + * `encoding` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The new default encoding * Returns: [`this`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this) @@ -500,7 +500,7 @@ The `writable.setDefaultEncoding()` method sets the default `encoding` for a ###### `writable.uncork()` - + The `writable.uncork()` method flushes all data buffered since [`stream.cork()`][] was called. @@ -537,7 +537,7 @@ See also: [`writable.cork()`][]. ###### `writable.writable` - + * [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) @@ -546,9 +546,9 @@ the stream has not been destroyed, errored or ended. ###### `writable.writableAborted` - + - + * [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) @@ -556,7 +556,7 @@ Returns whether the stream was destroyed or errored before emitting `'finish'`. ###### `writable.writableEnded` - + * [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) @@ -566,7 +566,7 @@ does not indicate whether the data has been flushed, for this use ###### `writable.writableCorked` - + * [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) @@ -575,7 +575,7 @@ called in order to fully uncork the stream. ###### `writable.errored` - + * [`Error`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error) @@ -583,7 +583,7 @@ Returns error if the stream has been destroyed with an error. ###### `writable.writableFinished` - + * [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) @@ -591,7 +591,7 @@ Is set to `true` immediately before the [`'finish'`][] event is emitted. ###### `writable.writableHighWaterMark` - + * [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) @@ -599,7 +599,7 @@ Return the value of `highWaterMark` passed when creating this `Writable`. ###### `writable.writableLength` - + * [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) @@ -609,7 +609,7 @@ the status of the `highWaterMark`. ###### `writable.writableNeedDrain` - + * [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) @@ -617,7 +617,7 @@ Is `true` if the stream's buffer has been full and stream will emit `'drain'`. ###### `writable.writableObjectMode` - + * [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) @@ -625,9 +625,9 @@ Getter for the property `objectMode` of a given `Writable` stream. ###### `writable.write(chunk[, encoding][, callback])` - + -* `chunk` {string|Buffer|Uint8Array|any} Optional data to write. For streams +* `chunk` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`Uint8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array) | [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) Optional data to write. For streams not operating in object mode, `chunk` must be a string, `Buffer` or `Uint8Array`. For object mode streams, `chunk` may be any JavaScript value other than `null`. @@ -811,15 +811,15 @@ to consume data from a single stream. Specifically, using a combination of `on('data')`, `on('readable')`, `pipe()`, or async iterators could lead to unintuitive behavior. -##### `stream.Readable` +##### `stream.Readable` - + - + ###### Event: `'close'` - + The `'close'` event is emitted when the stream and any of its underlying resources (a file descriptor, for example) have been closed. The event indicates @@ -830,7 +830,7 @@ created with the `emitClose` option. ###### Event: `'data'` - + * `chunk` [`Buffer`](/api/buffer#buffer) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) The chunk of data. For streams that are not operating in object mode, the chunk will be either a string or `Buffer`. @@ -856,13 +856,13 @@ encoding has been specified for the stream using the ```js const readable = getReadableStreamSomehow(); readable.on('data', (chunk) => { - console.log(`Received $chunk.length bytes of data.`); + console.log(`Received ${chunk.length} bytes of data.`); }); ``` ###### Event: `'end'` - + The `'end'` event is emitted when there is no more data to be consumed from the stream. @@ -875,7 +875,7 @@ consumed. ```js const readable = getReadableStreamSomehow(); readable.on('data', (chunk) => { - console.log(`Received $chunk.length bytes of data.`); + console.log(`Received ${chunk.length} bytes of data.`); }); readable.on('end', () => { console.log('There will be no more data.'); @@ -884,7 +884,7 @@ readable.on('end', () => { ###### Event: `'error'` - + * [`Error`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error) @@ -897,14 +897,14 @@ The listener callback will be passed a single `Error` object. ###### Event: `'pause'` - + The `'pause'` event is emitted when [`stream.pause()`][stream-pause] is called and `readableFlowing` is not `false`. ###### Event: `'readable'` - + The `'readable'` event is emitted when there is data available to be read from the stream or when the end of the stream has been reached. Effectively, the @@ -964,14 +964,14 @@ will start flowing, i.e. `'data'` events will be emitted without calling ###### Event: `'resume'` - + The `'resume'` event is emitted when [`stream.resume()`][stream-resume] is called and `readableFlowing` is not `true`. ###### `readable.destroy([error])` - + * `error` [`Error`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error) Error which will be passed as payload in `'error'` event * Returns: [`this`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this) @@ -989,7 +989,7 @@ Implementors should not override this method, but instead implement ###### `readable.closed` - + * [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) @@ -997,7 +997,7 @@ Is `true` after `'close'` has been emitted. ###### `readable.destroyed` - + * [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) @@ -1005,7 +1005,7 @@ Is `true` after [`readable.destroy()`][readable-destroy] has been called. ###### `readable.isPaused()` - + * Returns: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) @@ -1026,7 +1026,7 @@ readable.isPaused(); // === false ###### `readable.pause()` - + * Returns: [`this`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this) @@ -1037,7 +1037,7 @@ becomes available will remain in the internal buffer. ```js const readable = getReadableStreamSomehow(); readable.on('data', (chunk) => { - console.log(`Received $chunk.length bytes of data.`); + console.log(`Received ${chunk.length} bytes of data.`); readable.pause(); console.log('There will be no additional data for 1 second.'); setTimeout(() => { @@ -1052,7 +1052,7 @@ event listener. ###### `readable.pipe(destination[, options])` - + * `destination` [`stream.Writable`](/api/stream#streamwritable) The destination for writing data * `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) Pipe options @@ -1114,7 +1114,7 @@ closed until the Node.js process exits, regardless of the specified options. ###### `readable.read([size])` - + * `size` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Optional argument to specify how much data to read. * Returns: [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`null`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type) | [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) @@ -1148,7 +1148,7 @@ readable.on('readable', () => { console.log('Stream is readable (new data received in buffer)'); // Use a loop to make sure we read all currently available data while (null !== (chunk = readable.read())) { - console.log(`Read $chunk.length bytes of data...`); + console.log(`Read ${chunk.length} bytes of data...`); } }); @@ -1196,7 +1196,7 @@ been emitted will return `null`. No runtime error will be raised. ###### `readable.readable` - + * [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) @@ -1205,9 +1205,9 @@ the stream has not been destroyed or emitted `'error'` or `'end'`. ###### `readable.readableAborted` - + - + * [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) @@ -1215,9 +1215,9 @@ Returns whether the stream was destroyed or errored before emitting `'end'`. ###### `readable.readableDidRead` - + - + * [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) @@ -1225,7 +1225,7 @@ Returns whether `'data'` has been emitted. ###### `readable.readableEncoding` - + * [`null`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) @@ -1234,7 +1234,7 @@ property can be set using the [`readable.setEncoding()`][] method. ###### `readable.readableEnded` - + * [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) @@ -1242,7 +1242,7 @@ Becomes `true` when [`'end'`][] event is emitted. ###### `readable.errored` - + * [`Error`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error) @@ -1250,7 +1250,7 @@ Returns error if the stream has been destroyed with an error. ###### `readable.readableFlowing` - + * [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) @@ -1259,7 +1259,7 @@ in the [Three states][] section. ###### `readable.readableHighWaterMark` - + * [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) @@ -1267,7 +1267,7 @@ Returns the value of `highWaterMark` passed when creating this `Readable`. ###### `readable.readableLength` - + * [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) @@ -1277,7 +1277,7 @@ the status of the `highWaterMark`. ###### `readable.readableObjectMode` - + * [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) @@ -1285,7 +1285,7 @@ Getter for the property `objectMode` of a given `Readable` stream. ###### `readable.resume()` - + * Returns: [`this`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this) @@ -1308,7 +1308,7 @@ event listener. ###### `readable.setEncoding(encoding)` - + * `encoding` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The encoding to use. * Returns: [`this`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this) @@ -1339,7 +1339,7 @@ readable.on('data', (chunk) => { ###### `readable.unpipe([destination])` - + * `destination` [`stream.Writable`](/api/stream#streamwritable) Optional specific stream to unpipe * Returns: [`this`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this) @@ -1369,9 +1369,9 @@ setTimeout(() => { ###### `readable.unshift(chunk[, encoding])` - + -* `chunk` {Buffer|Uint8Array|string|null|any} Chunk of data to unshift onto the +* `chunk` [`Buffer`](/api/buffer#buffer) | [`Uint8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`null`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type) | [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) Chunk of data to unshift onto the read queue. For streams not operating in object mode, `chunk` must be a string, `Buffer`, `Uint8Array` or `null`. For object mode streams, `chunk` may be any JavaScript value. @@ -1442,7 +1442,7 @@ process of performing a read. ###### `readable.wrap(stream)` - + * `stream` [`Stream`](/api/stream#stream) An "old style" readable stream * Returns: [`this`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this) @@ -1473,7 +1473,7 @@ myReader.on('readable', () => { ###### `readable[Symbol.asyncIterator]()` - + * Returns: [`AsyncIterator`](https://tc39.github.io/ecma262/#sec-asynciterator-interface) to fully consume the stream. @@ -1501,9 +1501,9 @@ has less then 64 KiB of data because no `highWaterMark` option is provided to ###### `readable.iterator([options])` - + - + * `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) * `destroyOnReturn` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) When set to `false`, calling `return` on the @@ -1553,9 +1553,9 @@ showBoth(); ###### `readable.map(fn[, options])` - + - + * `fn` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) | [`AsyncFunction`](https://tc39.es/ecma262/#sec-async-function-constructor) a function to map over every chunk in the stream. @@ -1596,9 +1596,9 @@ for await (const result of dnsResults) { ###### `readable.filter(fn[, options])` - + - + * `fn` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) | [`AsyncFunction`](https://tc39.es/ecma262/#sec-async-function-constructor) a function to filter chunks from the stream. * `data` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) a chunk of data from the stream. @@ -1643,9 +1643,9 @@ for await (const result of dnsResults) { ###### `readable.forEach(fn[, options])` - + - + * `fn` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) | [`AsyncFunction`](https://tc39.es/ecma262/#sec-async-function-constructor) a function to call on each chunk of the stream. * `data` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) a chunk of data from the stream. @@ -1700,9 +1700,9 @@ console.log('done'); // Stream has finished ###### `readable.toArray([options])` - + - + * `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) * `signal` [`AbortSignal`](/api/globals#abortsignal) allows cancelling the toArray operation if the @@ -1736,9 +1736,9 @@ const dnsResults = await Readable.from([ ###### `readable.some(fn[, options])` - + - + * `fn` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) | [`AsyncFunction`](https://tc39.es/ecma262/#sec-async-function-constructor) a function to call on each chunk of the stream. * `data` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) a chunk of data from the stream. @@ -1783,9 +1783,9 @@ console.log('done'); // Stream has finished ###### `readable.find(fn[, options])` - + - + * `fn` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) | [`AsyncFunction`](https://tc39.es/ecma262/#sec-async-function-constructor) a function to call on each chunk of the stream. * `data` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) a chunk of data from the stream. @@ -1831,9 +1831,9 @@ console.log('done'); // Stream has finished ###### `readable.every(fn[, options])` - + - + * `fn` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) | [`AsyncFunction`](https://tc39.es/ecma262/#sec-async-function-constructor) a function to call on each chunk of the stream. * `data` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) a chunk of data from the stream. @@ -1878,9 +1878,9 @@ console.log('done'); // Stream has finished ###### `readable.flatMap(fn[, options])` - + - + * `fn` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) | [`AsyncGeneratorFunction`](https://tc39.es/proposal-async-iteration/#sec-asyncgeneratorfunction-constructor) | [`AsyncFunction`](https://tc39.es/ecma262/#sec-async-function-constructor) a function to map over every chunk in the stream. @@ -1925,9 +1925,9 @@ for await (const result of concatResult) { ###### `readable.drop(limit[, options])` - + - + * `limit` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) the number of chunks to drop from the readable. * `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) @@ -1945,9 +1945,9 @@ await Readable.from([1, 2, 3, 4]).drop(2).toArray(); // [3, 4] ###### `readable.take(limit[, options])` - + - + * `limit` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) the number of chunks to take from the readable. * `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) @@ -1965,9 +1965,9 @@ await Readable.from([1, 2, 3, 4]).take(2).toArray(); // [1, 2] ###### `readable.asIndexedPairs([options])` - + - + * `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) * `signal` [`AbortSignal`](/api/globals#abortsignal) allows destroying the stream if the signal is @@ -1987,9 +1987,9 @@ console.log(pairs); // [[0, 'a'], [1, 'b'], [2, 'c']] ###### `readable.reduce(fn[, initial[, options]])` - + - + * `fn` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) | [`AsyncFunction`](https://tc39.es/ecma262/#sec-async-function-constructor) a reducer function to call over every chunk in the stream. @@ -2028,11 +2028,11 @@ console.log(ten); // 10 #### Duplex and transform streams -##### `stream.Duplex` +##### `stream.Duplex` - + - + Duplex streams are streams that implement both the [`Readable`][] and [`Writable`][] interfaces. @@ -2045,7 +2045,7 @@ Examples of `Duplex` streams include: ###### `duplex.allowHalfOpen` - + * [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) @@ -2057,11 +2057,11 @@ This can be changed manually to change the half-open behavior of an existing `Duplex` stream instance, but must be changed before the `'end'` event is emitted. -##### `stream.Transform` +##### `stream.Transform` - + - + Transform streams are [`Duplex`][] streams where the output is in some way related to the input. Like all [`Duplex`][] streams, `Transform` streams @@ -2074,7 +2074,7 @@ Examples of `Transform` streams include: ###### `transform.destroy([error])` - + * `error` [`Error`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error) * Returns: [`this`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this) @@ -2089,9 +2089,9 @@ unless `emitClose` is set in false. Once `destroy()` has been called, any further calls will be a no-op and no further errors except from `_destroy()` may be emitted as `'error'`. -#### `stream.finished(stream[, options], callback)` +#### `stream.finished(stream[, options], callback)` - + * `stream` [`Stream`](/api/stream#stream) A readable and/or writable stream. * `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) @@ -2167,11 +2167,11 @@ const cleanup = finished(rs, (err) => { }); ``` -#### `stream.pipeline(source[, ...transforms], destination, callback)` +#### `stream.pipeline(source[, ...transforms], destination, callback)` -#### `stream.pipeline(streams, callback)` +#### `stream.pipeline(streams, callback)` - + * `streams` Stream\[]|Iterable\[]|AsyncIterable\[]|Function\[] * `source` [`Stream`](/api/stream#stream) | [`Iterable`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#The_iterable_protocol) | [`AsyncIterable`](https://tc39.github.io/ecma262/#sec-asynciterable-interface) | [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) @@ -2339,11 +2339,11 @@ const server = http.createServer((req, res) => { }); ``` -#### `stream.compose(...streams)` +#### `stream.compose(...streams)` - + - + * `streams` Stream\[]|Iterable\[]|AsyncIterable\[]|Function\[] * Returns: [`stream.Duplex`](/api/stream#streamduplex) @@ -2427,9 +2427,9 @@ await finished(compose(s1, s2, s3)); console.log(res); // prints 'HELLOWORLD' ``` -#### `stream.Readable.from(iterable[, options])` +#### `stream.Readable.from(iterable[, options])` - + * `iterable` [`Iterable`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#The_iterable_protocol) Object implementing the `Symbol.asyncIterator` or `Symbol.iterator` iterable protocol. Emits an 'error' event if a null @@ -2460,11 +2460,11 @@ Calling `Readable.from(string)` or `Readable.from(buffer)` will not have the strings or buffers be iterated to match the other streams semantics for performance reasons. -#### `stream.Readable.fromWeb(readableStream[, options])` +#### `stream.Readable.fromWeb(readableStream[, options])` - + - + * `readableStream` [`ReadableStream`](/api/webstreams#readablestream) * `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) @@ -2474,44 +2474,44 @@ for performance reasons. * `signal` [`AbortSignal`](/api/globals#abortsignal) * Returns: [`stream.Readable`](/api/stream#streamreadable) -#### `stream.Readable.isDisturbed(stream)` +#### `stream.Readable.isDisturbed(stream)` - + - + * `stream` [`stream.Readable`](/api/stream#streamreadable) | [`ReadableStream`](/api/webstreams#readablestream) * Returns: `boolean` Returns whether the stream has been read from or cancelled. -#### `stream.isErrored(stream)` +#### `stream.isErrored(stream)` - + - + * `stream` [`Readable`](/api/stream#streamreadable) | [`Writable`](/api/stream#streamwritable) | [`Duplex`](/api/stream#streamduplex) | [`WritableStream`](/api/webstreams#writablestream) | [`ReadableStream`](/api/webstreams#readablestream) * Returns: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) Returns whether the stream has encountered an error. -#### `stream.isReadable(stream)` +#### `stream.isReadable(stream)` - + - + * `stream` [`Readable`](/api/stream#streamreadable) | [`Duplex`](/api/stream#streamduplex) | [`ReadableStream`](/api/webstreams#readablestream) * Returns: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) Returns whether the stream is readable. -#### `stream.Readable.toWeb(streamReadable[, options])` +#### `stream.Readable.toWeb(streamReadable[, options])` - + - + * `streamReadable` [`stream.Readable`](/api/stream#streamreadable) * `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) @@ -2520,11 +2520,11 @@ Returns whether the stream is readable. * `size` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) * Returns: [`ReadableStream`](/api/webstreams#readablestream) -#### `stream.Writable.fromWeb(writableStream[, options])` +#### `stream.Writable.fromWeb(writableStream[, options])` - + - + * `writableStream` [`WritableStream`](/api/webstreams#writablestream) * `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) @@ -2534,21 +2534,20 @@ Returns whether the stream is readable. * `signal` [`AbortSignal`](/api/globals#abortsignal) * Returns: [`stream.Writable`](/api/stream#streamwritable) -#### `stream.Writable.toWeb(streamWritable)` +#### `stream.Writable.toWeb(streamWritable)` - + - + * `streamWritable` [`stream.Writable`](/api/stream#streamwritable) * Returns: [`WritableStream`](/api/webstreams#writablestream) -#### `stream.Duplex.from(src)` +#### `stream.Duplex.from(src)` - + -* `src` {Stream|Blob|ArrayBuffer|string|Iterable|AsyncIterable| - AsyncGeneratorFunction|AsyncFunction|Promise|Object} +* `src` [`Stream`](/api/stream#stream) | [`Blob`](/api/buffer#blob) | [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Iterable`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#The_iterable_protocol) | [`AsyncIterable`](https://tc39.github.io/ecma262/#sec-asynciterable-interface) | [`AsyncGeneratorFunction`](https://tc39.es/proposal-async-iteration/#sec-asyncgeneratorfunction-constructor) | [`AsyncFunction`](https://tc39.es/ecma262/#sec-async-function-constructor) | [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) | [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) A utility method for creating duplex streams. @@ -2564,17 +2563,17 @@ A utility method for creating duplex streams. `null`. * `AsyncFunction` converts into a writable `Duplex`. Must return either `null` or `undefined` -* `Object ({ writable, readable })` converts `readable` and +* `Object (```{ writable, readable }```)` converts `readable` and `writable` into `Stream` and then combines them into `Duplex` where the `Duplex` will write to the `writable` and read from the `readable`. * `Promise` converts into readable `Duplex`. Value `null` is ignored. * Returns: [`stream.Duplex`](/api/stream#streamduplex) -#### `stream.Duplex.fromWeb(pair[, options])` +#### `stream.Duplex.fromWeb(pair[, options])` - + - + * `pair` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) * `readable` [`ReadableStream`](/api/webstreams#readablestream) @@ -2649,11 +2648,11 @@ duplex.write('hello'); duplex.once('readable', () => console.log('readable', duplex.read())); ``` -#### `stream.Duplex.toWeb(streamDuplex)` +#### `stream.Duplex.toWeb(streamDuplex)` - + - + * `streamDuplex` [`stream.Duplex`](/api/stream#streamduplex) * Returns: [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) @@ -2705,9 +2704,9 @@ readable.getReader().read().then((result) => { }); ``` -#### `stream.addAbortSignal(signal, stream)` +#### `stream.addAbortSignal(signal, stream)` - + * `signal` [`AbortSignal`](/api/globals#abortsignal) A signal representing possible cancellation * `stream` [`Stream`](/api/stream#stream) a stream to attach a signal to @@ -2757,7 +2756,7 @@ const stream = addAbortSignal( ### API for stream implementers - + The `node:stream` module API has been designed to make it possible to easily implement streams using JavaScript's prototypal inheritance model. @@ -2811,7 +2810,7 @@ expectations. #### Simplified construction - + For many simple cases, it is possible to create a stream without relying on inheritance. This can be accomplished by directly creating instances of the @@ -2842,9 +2841,9 @@ Custom `Writable` streams _must_ call the `new stream.Writable([options])` constructor and implement the `writable._write()` and/or `writable._writev()` method. -##### `new stream.Writable([options])` +##### `new stream.Writable([options])` - + * `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) * `highWaterMark` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Buffer level when @@ -2944,9 +2943,9 @@ const myWritable = new Writable({ controller.abort(); ``` -##### `writable._construct(callback)` +##### `writable._construct(callback)` - + * `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) Call this function (optionally with an error argument) when the stream has finished initializing. @@ -2993,9 +2992,9 @@ class WriteStream extends Writable { } ``` -##### `writable._write(chunk, encoding, callback)` +##### `writable._write(chunk, encoding, callback)` - + * `chunk` [`Buffer`](/api/buffer#buffer) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) The `Buffer` to be written, converted from the `string` passed to [`stream.write()`][stream-write]. If the stream's @@ -3043,7 +3042,7 @@ The `writable._write()` method is prefixed with an underscore because it is internal to the class that defines it, and should never be called directly by user programs. -##### `writable._writev(chunks, callback)` +##### `writable._writev(chunks, callback)` * `chunks` Object\[] The data to be written. The value is an array of [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) that each represent a discrete chunk of data to write. The properties of @@ -3069,9 +3068,9 @@ The `writable._writev()` method is prefixed with an underscore because it is internal to the class that defines it, and should never be called directly by user programs. -##### `writable._destroy(err, callback)` +##### `writable._destroy(err, callback)` - + * `err` [`Error`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error) A possible error. * `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) A callback function that takes an optional error @@ -3082,9 +3081,9 @@ It can be overridden by child classes but it **must not** be called directly. Furthermore, the `callback` should not be mixed with async/await once it is executed when a promise is resolved. -##### `writable._final(callback)` +##### `writable._final(callback)` - + * `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) Call this function (optionally with an error argument) when finished writing any remaining data. @@ -3190,9 +3189,9 @@ The `stream.Readable` class is extended to implement a [`Readable`][] stream. Custom `Readable` streams _must_ call the `new stream.Readable([options])` constructor and implement the [`readable._read()`][] method. -##### `new stream.Readable([options])` +##### `new stream.Readable([options])` - + * `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) * `highWaterMark` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The maximum [number of bytes][hwm-gotcha] to store @@ -3272,9 +3271,9 @@ const read = new Readable({ controller.abort(); ``` -##### `readable._construct(callback)` +##### `readable._construct(callback)` - + * `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) Call this function (optionally with an error argument) when the stream has finished initializing. @@ -3328,9 +3327,9 @@ class ReadStream extends Readable { } ``` -##### `readable._read(size)` +##### `readable._read(size)` - + * `size` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number of bytes to read asynchronously @@ -3365,9 +3364,9 @@ The [`readable._read()`][] method is prefixed with an underscore because it is internal to the class that defines it, and should never be called directly by user programs. -##### `readable._destroy(err, callback)` +##### `readable._destroy(err, callback)` - + * `err` [`Error`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error) A possible error. * `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) A callback function that takes an optional error @@ -3376,11 +3375,11 @@ user programs. The `_destroy()` method is called by [`readable.destroy()`][readable-destroy]. It can be overridden by child classes but it **must not** be called directly. -##### `readable.push(chunk[, encoding])` +##### `readable.push(chunk[, encoding])` - + -* `chunk` {Buffer|Uint8Array|string|null|any} Chunk of data to push into the +* `chunk` [`Buffer`](/api/buffer#buffer) | [`Uint8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`null`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type) | [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) Chunk of data to push into the read queue. For streams not operating in object mode, `chunk` must be a string, `Buffer` or `Uint8Array`. For object mode streams, `chunk` may be any JavaScript value. @@ -3469,7 +3468,7 @@ const myReadable = new Readable({ ##### An example counting stream - + The following is a basic example of a `Readable` stream that emits the numerals from 1 to 1,000,000 in ascending order, and then ends. @@ -3515,9 +3514,9 @@ Custom `Duplex` streams _must_ call the `new stream.Duplex([options])` constructor and implement _both_ the [`readable._read()`][] and `writable._write()` methods. -##### `new stream.Duplex(options)` +##### `new stream.Duplex(options)` - + * `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) Passed to both `Writable` and `Readable` constructors. Also has the following fields: @@ -3725,7 +3724,7 @@ Care must be taken when using `Transform` streams in that data written to the stream can cause the `Writable` side of the stream to become paused if the output on the `Readable` side is not consumed. -##### `new stream.Transform([options])` +##### `new stream.Transform([options])` * `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) Passed to both `Writable` and `Readable` constructors. Also has the following fields: @@ -3773,21 +3772,21 @@ const myTransform = new Transform({ }); ``` -##### `'end'` +##### `'end'` The [`'end'`][] event is from the `stream.Readable` class. The `'end'` event is emitted after all data has been output, which occurs after the callback in [`transform._flush()`][stream-_flush] has been called. In the case of an error, `'end'` should not be emitted. -##### `'finish'` +##### `'finish'` The [`'finish'`][] event is from the `stream.Writable` class. The `'finish'` event is emitted after [`stream.end()`][stream-end] is called and all chunks have been processed by [`stream._transform()`][stream-_transform]. In the case of an error, `'finish'` should not be emitted. -##### `transform._flush(callback)` +##### `transform._flush(callback)` * `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) A callback function (optionally with an error argument and data) to be called when remaining data has been flushed. @@ -3815,7 +3814,7 @@ The `transform._flush()` method is prefixed with an underscore because it is internal to the class that defines it, and should never be called directly by user programs. -##### `transform._transform(chunk, encoding, callback)` +##### `transform._transform(chunk, encoding, callback)` * `chunk` [`Buffer`](/api/buffer#buffer) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) The `Buffer` to be transformed, converted from the `string` passed to [`stream.write()`][stream-write]. If the stream's @@ -3869,7 +3868,7 @@ user programs. queue mechanism, and to receive the next chunk, `callback` must be called, either synchronously or asynchronously. -##### `stream.PassThrough` +##### `stream.PassThrough` The `stream.PassThrough` class is a trivial implementation of a [`Transform`][] stream that simply passes the input bytes across to the output. Its purpose is @@ -3878,7 +3877,7 @@ primarily for examples and testing, but there are some use cases where ### Additional notes - + #### Streams compatibility with async generators and async iterators @@ -3970,11 +3969,11 @@ pipelinePromise(iterator, writable) }); ``` - + #### Compatibility with older Node.js versions - + Prior to Node.js 0.10, the `Readable` stream interface was simpler, but also less powerful and less useful. @@ -4039,7 +4038,7 @@ In addition to new `Readable` streams switching into flowing mode, pre-0.10 style streams can be wrapped in a `Readable` class using the [`readable.wrap()`][`stream.wrap()`] method. -#### `readable.read(0)` +#### `readable.read(0)` There are some cases where it is necessary to trigger a refresh of the underlying readable stream mechanisms, without actually consuming any @@ -4054,7 +4053,7 @@ While most applications will almost never need to do this, there are situations within Node.js where this is done, particularly in the `Readable` stream class internals. -#### `readable.push('')` +#### `readable.push('')` Use of `readable.push('')` is not recommended. @@ -4064,7 +4063,7 @@ object mode has an interesting side effect. Because it _is_ a call to However, because the argument is an empty string, no data is added to the readable buffer so there is nothing for a user to consume. -#### `highWaterMark` discrepancy after calling `readable.setEncoding()` +#### `highWaterMark` discrepancy after calling `readable.setEncoding()` The use of `readable.setEncoding()` will change the behavior of how the `highWaterMark` operates in non-object mode. diff --git a/content/api/v18/string_decoder.en.md b/content/api/v18/string_decoder.en.md index 520ba9cf09..0b31085d1a 100644 --- a/content/api/v18/string_decoder.en.md +++ b/content/api/v18/string_decoder.en.md @@ -2,15 +2,15 @@ title: 'string_decoder' displayTitle: 'String decoder' category: 'api' -editPage: 'https://github.com/nodejs/node/blob/v18.8.0/doc/api/string_decoder.md' +editPage: 'https://github.com/nodejs/node/blob/v18.9.0/doc/api/string_decoder.md' version: 'v18' --- - + - + - + The `node:string_decoder` module provides an API for decoding `Buffer` objects into strings in a manner that preserves encoded multi-byte UTF-8 and UTF-16 @@ -50,20 +50,20 @@ decoder.write(Buffer.from([0x82])); console.log(decoder.end(Buffer.from([0xAC]))); ``` -### `StringDecoder` +### `StringDecoder` -#### `new StringDecoder([encoding])` +#### `new StringDecoder([encoding])` - + * `encoding` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The character [encoding][] the `StringDecoder` will use. **Default:** `'utf8'`. Creates a new `StringDecoder` instance. -#### `stringDecoder.end([buffer])` +#### `stringDecoder.end([buffer])` - + * `buffer` [`Buffer`](/api/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) A `Buffer`, or `TypedArray`, or `DataView` containing the bytes to decode. @@ -77,9 +77,9 @@ If the `buffer` argument is provided, one final call to `stringDecoder.write()` is performed before returning the remaining input. After `end()` is called, the `stringDecoder` object can be reused for new input. -#### `stringDecoder.write(buffer)` +#### `stringDecoder.write(buffer)` - + * `buffer` [`Buffer`](/api/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) A `Buffer`, or `TypedArray`, or `DataView` containing the bytes to decode. diff --git a/content/api/v18/synopsis.en.md b/content/api/v18/synopsis.en.md index 2cf8b46af0..2ab6d6507f 100644 --- a/content/api/v18/synopsis.en.md +++ b/content/api/v18/synopsis.en.md @@ -2,15 +2,15 @@ title: 'synopsis' displayTitle: 'Usage and example' category: 'api' -editPage: 'https://github.com/nodejs/node/blob/v18.8.0/doc/api/synopsis.md' +editPage: 'https://github.com/nodejs/node/blob/v18.9.0/doc/api/synopsis.md' version: 'v18' --- ### Usage - + - + `node [options] [V8 options] [script.js | -e "script" | - ] [arguments]` @@ -73,7 +73,7 @@ const server = http.createServer((req, res) => { }); server.listen(port, hostname, () => { - console.log(`Server running at http://$hostname:$port/`); + console.log(`Server running at http://${hostname}:${port}/`); }); ``` diff --git a/content/api/v18/test.en.md b/content/api/v18/test.en.md index 6d4801a15c..92ccfdeab3 100644 --- a/content/api/v18/test.en.md +++ b/content/api/v18/test.en.md @@ -2,15 +2,15 @@ title: 'test' displayTitle: 'Test runner' category: 'api' -editPage: 'https://github.com/nodejs/node/blob/v18.8.0/doc/api/test.md' +editPage: 'https://github.com/nodejs/node/blob/v18.9.0/doc/api/test.md' version: 'v18' --- - + - + - + The `node:test` module facilitates the creation of JavaScript tests that report results in [TAP][] format. To access it: @@ -154,7 +154,7 @@ test('skip() method with message', (t) => { }); ``` -### `describe`/`it` syntax +### `describe`/`it` syntax Running tests can also be done using `describe` to declare a suite and `it` to declare a test. @@ -190,7 +190,7 @@ import { describe, it } from 'node:test'; const { describe, it } = require('node:test'); ``` -#### `only` tests +#### `only` tests If Node.js is started with the [`--test-only`][] command-line option, it is possible to skip all top level tests except for a selected subset by passing @@ -322,9 +322,36 @@ Otherwise, the test is considered to be a failure. Test files must be executable by Node.js, but are not required to use the `node:test` module internally. -### `test([name][, options][, fn])` +### `run([options])` - + + +* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) Configuration options for running tests. The following + properties are supported: + * `concurrency` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) | [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) If a number is provided, + then that many files would run in parallel. + If truthy, it would run (number of cpu cores - 1) + files in parallel. + If falsy, it would only run one file at a time. + If unspecified, subtests inherit this value from their parent. + **Default:** `true`. + * `files`: [`Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array) An array containing the list of files to run. + **Default** matching files from [test runner execution model][]. + * `signal` [`AbortSignal`](/api/globals#abortsignal) Allows aborting an in-progress test execution. + * `timeout` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) A number of milliseconds the test execution will + fail after. + If unspecified, subtests inherit this value from their parent. + **Default:** `Infinity`. +* Returns: [`TapStream`](/api/test#tapstream) + +```js +run({ files: [path.resolve('./tests/test.js')] }) + .pipe(process.stdout); +``` + +### `test([name][, options][, fn])` + + * `name` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The name of the test, which is displayed when reporting test results. **Default:** The `name` property of `fn`, or `''` if `fn` @@ -389,7 +416,7 @@ The `timeout` option can be used to fail the test if it takes longer than canceling tests because a running test might block the application thread and thus prevent the scheduled cancellation. -### `describe([name][, options][, fn])` +### `describe([name][, options][, fn])` * `name` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The name of the suite, which is displayed when reporting test results. **Default:** The `name` property of `fn`, or `''` if `fn` @@ -408,16 +435,16 @@ and a test point in the TAP output. After invocation of top level `describe` functions, all top level tests and suites will execute. -### `describe.skip([name][, options][, fn])` +### `describe.skip([name][, options][, fn])` -Shorthand for skipping a suite, same as [`describe([name], { skip: true }[, fn])`][describe options]. +Shorthand for skipping a suite, same as [`describe([name], ```{ skip: true }```[, fn])`][describe options]. -### `describe.todo([name][, options][, fn])` +### `describe.todo([name][, options][, fn])` Shorthand for marking a suite as `TODO`, same as -[`describe([name], { todo: true }[, fn])`][describe options]. +[`describe([name], ```{ todo: true }```[, fn])`][describe options]. -### `it([name][, options][, fn])` +### `it([name][, options][, fn])` * `name` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The name of the test, which is displayed when reporting test results. **Default:** The `name` property of `fn`, or `''` if `fn` @@ -433,19 +460,19 @@ The `it()` function is the value imported from the `node:test` module. Each invocation of this function results in the creation of a test point in the TAP output. -### `it.skip([name][, options][, fn])` +### `it.skip([name][, options][, fn])` Shorthand for skipping a test, -same as [`it([name], { skip: true }[, fn])`][it options]. +same as [`it([name], ```{ skip: true }```[, fn])`][it options]. -### `it.todo([name][, options][, fn])` +### `it.todo([name][, options][, fn])` Shorthand for marking a test as `TODO`, -same as [`it([name], { todo: true }[, fn])`][it options]. +same as [`it([name], ```{ todo: true }```[, fn])`][it options]. -#### `before([, fn][, options])` +#### `before([, fn][, options])` - + * `fn` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) | [`AsyncFunction`](https://tc39.es/ecma262/#sec-async-function-constructor) The hook function. If the hook uses callbacks, @@ -469,9 +496,9 @@ describe('tests', async () => { }); ``` -#### `after([, fn][, options])` +#### `after([, fn][, options])` - + * `fn` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) | [`AsyncFunction`](https://tc39.es/ecma262/#sec-async-function-constructor) The hook function. If the hook uses callbacks, @@ -495,9 +522,9 @@ describe('tests', async () => { }); ``` -#### `beforeEach([, fn][, options])` +#### `beforeEach([, fn][, options])` - + * `fn` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) | [`AsyncFunction`](https://tc39.es/ecma262/#sec-async-function-constructor) The hook function. If the hook uses callbacks, @@ -515,16 +542,16 @@ before each subtest of the current suite. ```js describe('tests', async () => { - beforeEach(() => t.diagnostics('about to run a test')); + beforeEach(() => t.diagnostic('about to run a test')); it('is a subtest', () => { assert.ok('some relevant assertion here'); }); }); ``` -#### `afterEach([, fn][, options])` +#### `afterEach([, fn][, options])` - + * `fn` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) | [`AsyncFunction`](https://tc39.es/ecma262/#sec-async-function-constructor) The hook function. If the hook uses callbacks, @@ -542,24 +569,63 @@ after each subtest of the current test. ```js describe('tests', async () => { - afterEach(() => t.diagnostics('about to run a test')); + afterEach(() => t.diagnostic('about to run a test')); it('is a subtest', () => { assert.ok('some relevant assertion here'); }); }); ``` -### `TestContext` +### `TapStream` + + + +* Extends [`ReadableStream`](/api/webstreams#readablestream) + +A successful call to [`run()`][] method will return a new [`TapStream`](/api/test#tapstream) +object, streaming a [TAP][] output +`TapStream` will emit events, in the order of the tests definition + +#### `'test:diagnostic'` + +* `message` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The diagnostic message. + +Emitted when [`context.diagnostic`][] is called. + +#### `'test:fail'` + +* `data` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) + * `duration` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The test duration. + * `error` [`Error`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error) The failure casing test to fail. + * `name` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The test name. + * `testNumber` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The ordinal number of the test. + * `todo` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`undefined`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type) Present if [`context.todo`][] is called + * `skip` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`undefined`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type) Present if [`context.skip`][] is called + +Emitted when a test fails. + +#### `'test:pass'` + +* `data` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) + * `duration` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The test duration. + * `name` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The test name. + * `testNumber` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The ordinal number of the test. + * `todo` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`undefined`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type) Present if [`context.todo`][] is called + * `skip` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`undefined`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type) Present if [`context.skip`][] is called + +Emitted when a test passes. + +### `TestContext` - + An instance of `TestContext` is passed to each test function in order to interact with the test runner. However, the `TestContext` constructor is not exposed as part of the API. -#### `context.beforeEach([, fn][, options])` +#### `context.beforeEach([, fn][, options])` - + * `fn` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) | [`AsyncFunction`](https://tc39.es/ecma262/#sec-async-function-constructor) The hook function. The first argument to this function is a [`TestContext`][] object. If the hook uses callbacks, @@ -577,7 +643,7 @@ before each subtest of the current test. ```js test('top level test', async (t) => { - t.beforeEach((t) => t.diagnostics(`about to run $t.name`)); + t.beforeEach((t) => t.diagnostic(`about to run ${t.name}`)); await t.test( 'This is a subtest', (t) => { @@ -587,9 +653,9 @@ test('top level test', async (t) => { }); ``` -#### `context.afterEach([, fn][, options])` +#### `context.afterEach([, fn][, options])` - + * `fn` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) | [`AsyncFunction`](https://tc39.es/ecma262/#sec-async-function-constructor) The hook function. The first argument to this function is a [`TestContext`][] object. If the hook uses callbacks, @@ -607,7 +673,7 @@ after each subtest of the current test. ```js test('top level test', async (t) => { - t.afterEach((t) => t.diagnostics(`finished running $t.name`)); + t.afterEach((t) => t.diagnostic(`finished running ${t.name}`)); await t.test( 'This is a subtest', (t) => { @@ -617,9 +683,9 @@ test('top level test', async (t) => { }); ``` -#### `context.diagnostic(message)` +#### `context.diagnostic(message)` - + * `message` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) Message to be displayed as a TAP diagnostic. @@ -633,15 +699,15 @@ test('top level test', (t) => { }); ``` -#### `context.name` +#### `context.name` - + The name of the test. -#### `context.runOnly(shouldRunOnlyTests)` +#### `context.runOnly(shouldRunOnlyTests)` - + * `shouldRunOnlyTests` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) Whether or not to run `only` tests. @@ -661,9 +727,9 @@ test('top level test', (t) => { }); ``` -#### `context.signal` +#### `context.signal` - + * [`AbortSignal`](/api/globals#abortsignal) Can be used to abort test subtasks when the test has been aborted. @@ -674,9 +740,9 @@ test('top level test', async (t) => { }); ``` -#### `context.skip([message])` +#### `context.skip([message])` - + * `message` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) Optional skip message to be displayed in TAP output. @@ -692,9 +758,9 @@ test('top level test', (t) => { }); ``` -#### `context.todo([message])` +#### `context.todo([message])` - + * `message` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) Optional `TODO` message to be displayed in TAP output. @@ -709,9 +775,9 @@ test('top level test', (t) => { }); ``` -#### `context.test([name][, options][, fn])` +#### `context.test([name][, options][, fn])` - + * `name` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The name of the subtest, which is displayed when reporting test results. **Default:** The `name` property of `fn`, or `''` if @@ -755,23 +821,23 @@ test('top level test', async (t) => { }); ``` -### `SuiteContext` +### `SuiteContext` - + An instance of `SuiteContext` is passed to each suite function in order to interact with the test runner. However, the `SuiteContext` constructor is not exposed as part of the API. -#### `context.name` +#### `context.name` - + The name of the suite. -#### `context.signal` +#### `context.signal` - + * [`AbortSignal`](/api/globals#abortsignal) Can be used to abort test subtasks when the test has been aborted. @@ -781,6 +847,10 @@ The name of the suite. [`--test`]: (/api/cli#--test) [`SuiteContext`]: #class-suitecontext [`TestContext`]: #class-testcontext +[`context.diagnostic`]: #contextdiagnosticmessage +[`context.skip`]: #contextskipmessage +[`context.todo`]: #contexttodomessage +[`run()`]: #runoptions [`test()`]: #testname-options-fn [describe options]: #describename-options-fn [it options]: #testname-options-fn diff --git a/content/api/v18/timers.en.md b/content/api/v18/timers.en.md index 316470b216..7f05537a3b 100644 --- a/content/api/v18/timers.en.md +++ b/content/api/v18/timers.en.md @@ -2,15 +2,15 @@ title: 'timers' displayTitle: 'Timers' category: 'api' -editPage: 'https://github.com/nodejs/node/blob/v18.8.0/doc/api/timers.md' +editPage: 'https://github.com/nodejs/node/blob/v18.9.0/doc/api/timers.md' version: 'v18' --- - + - + - + The `timer` module exposes a global API for scheduling functions to be called at some future period of time. Because the timer functions are @@ -20,7 +20,7 @@ The timer functions within Node.js implement a similar API as the timers API provided by Web Browsers but use a different internal implementation that is built around the Node.js [Event Loop][]. -### `Immediate` +### `Immediate` This object is created internally and is returned from [`setImmediate()`][]. It can be passed to [`clearImmediate()`][] in order to cancel the scheduled @@ -31,17 +31,17 @@ running as long as the immediate is active. The `Immediate` object returned by [`setImmediate()`][] exports both `immediate.ref()` and `immediate.unref()` functions that can be used to control this default behavior. -#### `immediate.hasRef()` +#### `immediate.hasRef()` - + * Returns: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) If true, the `Immediate` object will keep the Node.js event loop active. -#### `immediate.ref()` +#### `immediate.ref()` - + * Returns: [`Immediate`](/api/timers#immediate) a reference to `immediate` @@ -52,9 +52,9 @@ effect. By default, all `Immediate` objects are "ref'ed", making it normally unnecessary to call `immediate.ref()` unless `immediate.unref()` had been called previously. -#### `immediate.unref()` +#### `immediate.unref()` - + * Returns: [`Immediate`](/api/timers#immediate) a reference to `immediate` @@ -63,7 +63,7 @@ loop to remain active. If there is no other activity keeping the event loop running, the process may exit before the `Immediate` object's callback is invoked. Calling `immediate.unref()` multiple times will have no effect. -### `Timeout` +### `Timeout` This object is created internally and is returned from [`setTimeout()`][] and [`setInterval()`][]. It can be passed to either [`clearTimeout()`][] or @@ -75,27 +75,27 @@ timer is active. Each of the `Timeout` objects returned by these functions export both `timeout.ref()` and `timeout.unref()` functions that can be used to control this default behavior. -#### `timeout.close()` +#### `timeout.close()` - + - + * Returns: [`Timeout`](/api/timers#timeout) a reference to `timeout` Cancels the timeout. -#### `timeout.hasRef()` +#### `timeout.hasRef()` - + * Returns: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) If true, the `Timeout` object will keep the Node.js event loop active. -#### `timeout.ref()` +#### `timeout.ref()` - + * Returns: [`Timeout`](/api/timers#timeout) a reference to `timeout` @@ -105,9 +105,9 @@ When called, requests that the Node.js event loop _not_ exit so long as the By default, all `Timeout` objects are "ref'ed", making it normally unnecessary to call `timeout.ref()` unless `timeout.unref()` had been called previously. -#### `timeout.refresh()` +#### `timeout.refresh()` - + * Returns: [`Timeout`](/api/timers#timeout) a reference to `timeout` @@ -119,9 +119,9 @@ JavaScript object. Using this on a timer that has already called its callback will reactivate the timer. -#### `timeout.unref()` +#### `timeout.unref()` - + * Returns: [`Timeout`](/api/timers#timeout) a reference to `timeout` @@ -130,9 +130,9 @@ to remain active. If there is no other activity keeping the event loop running, the process may exit before the `Timeout` object's callback is invoked. Calling `timeout.unref()` multiple times will have no effect. -#### `timeout[Symbol.toPrimitive]()` +#### `timeout[Symbol.toPrimitive]()` - + * Returns: [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) a number that can be used to reference this `timeout` @@ -150,9 +150,9 @@ a certain period of time. When a timer's function is called varies depending on which method was used to create the timer and what other work the Node.js event loop is doing. -#### `setImmediate(callback[, ...args])` +#### `setImmediate(callback[, ...args])` - + * `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) The function to call at the end of this turn of the Node.js [Event Loop][] @@ -173,9 +173,9 @@ If `callback` is not a function, a [`TypeError`][] will be thrown. This method has a custom variant for promises that is available using [`timersPromises.setImmediate()`][]. -#### `setInterval(callback[, delay[, ...args]])` +#### `setInterval(callback[, delay[, ...args]])` - + * `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) The function to call when the timer elapses. * `delay` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The number of milliseconds to wait before calling the @@ -193,9 +193,9 @@ If `callback` is not a function, a [`TypeError`][] will be thrown. This method has a custom variant for promises that is available using [`timersPromises.setInterval()`][]. -#### `setTimeout(callback[, delay[, ...args]])` +#### `setTimeout(callback[, delay[, ...args]])` - + * `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) The function to call when the timer elapses. * `delay` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The number of milliseconds to wait before calling the @@ -264,27 +264,27 @@ setTimeoutPromise(1000, 'foobar', { signal }) ac.abort(); ``` -#### `clearImmediate(immediate)` +#### `clearImmediate(immediate)` - + * `immediate` [`Immediate`](/api/timers#immediate) An `Immediate` object as returned by [`setImmediate()`][]. Cancels an `Immediate` object created by [`setImmediate()`][]. -#### `clearInterval(timeout)` +#### `clearInterval(timeout)` - + * `timeout` [`Timeout`](/api/timers#timeout) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) A `Timeout` object as returned by [`setInterval()`][] or the [primitive][] of the `Timeout` object as a string or a number. Cancels a `Timeout` object created by [`setInterval()`][]. -#### `clearTimeout(timeout)` +#### `clearTimeout(timeout)` - + * `timeout` [`Timeout`](/api/timers#timeout) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) A `Timeout` object as returned by [`setTimeout()`][] or the [primitive][] of the `Timeout` object as a string or a number. @@ -293,7 +293,7 @@ Cancels a `Timeout` object created by [`setTimeout()`][]. ### Timers Promises API - + The `timers/promises` API provides an alternative set of timer functions that return `Promise` objects. The API is accessible via @@ -315,9 +315,9 @@ const { } = require('node:timers/promises'); ``` -#### `timersPromises.setTimeout([delay[, value[, options]]])` +#### `timersPromises.setTimeout([delay[, value[, options]]])` - + * `delay` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The number of milliseconds to wait before fulfilling the promise. **Default:** `1`. @@ -349,9 +349,9 @@ setTimeout(100, 'result').then((res) => { }); ``` -#### `timersPromises.setImmediate([value[, options]])` +#### `timersPromises.setImmediate([value[, options]])` - + * `value` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) A value with which the promise is fulfilled. * `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) @@ -381,9 +381,9 @@ setImmediate('result').then((res) => { }); ``` -#### `timersPromises.setInterval([delay[, value[, options]]])` +#### `timersPromises.setInterval([delay[, value[, options]]])` - + Returns an async iterator that generates values in an interval of `delay` ms. @@ -430,11 +430,11 @@ const interval = 100; })(); ``` -#### `timersPromises.scheduler.wait(delay[, options])` +#### `timersPromises.scheduler.wait(delay[, options])` - + - + * `delay` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The number of milliseconds to wait before resolving the promise. @@ -456,11 +456,11 @@ import { scheduler } from 'node:timers/promises'; await scheduler.wait(1000); // Wait one second before continuing ``` -#### `timersPromises.scheduler.yield()` +#### `timersPromises.scheduler.yield()` - + - + * Returns: [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) diff --git a/content/api/v18/tls.en.md b/content/api/v18/tls.en.md index 881e16fc9e..c77aa1f527 100644 --- a/content/api/v18/tls.en.md +++ b/content/api/v18/tls.en.md @@ -2,15 +2,15 @@ title: 'tls' displayTitle: 'TLS (SSL)' category: 'api' -editPage: 'https://github.com/nodejs/node/blob/v18.8.0/doc/api/tls.md' +editPage: 'https://github.com/nodejs/node/blob/v18.9.0/doc/api/tls.md' version: 'v18' --- - + - + - + The `node:tls` module provides an implementation of the Transport Layer Security (TLS) and Secure Socket Layer (SSL) protocols that is built on top of OpenSSL. @@ -112,7 +112,7 @@ Where: #### Perfect forward secrecy - + The term _[forward secrecy][]_ or _perfect forward secrecy_ describes a feature of key-agreement (i.e., key-exchange) methods. That is, the server and client @@ -152,7 +152,7 @@ TLSv1.3, because all TLSv1.3 cipher suites use ECDHE. #### ALPN and SNI - + ALPN (Application-Layer Protocol Negotiation Extension) and SNI (Server Name Indication) are TLS handshake extensions: @@ -163,7 +163,7 @@ SNI (Server Name Indication) are TLS handshake extensions: #### Pre-shared keys - + TLS-PSK support is available as an alternative to normal certificate-based authentication. It uses a pre-shared key instead of certificates to @@ -197,7 +197,7 @@ limitations of the underlying OpenSSL API. #### Client-initiated renegotiation attack mitigation - + The TLS protocol allows clients to renegotiate certain aspects of the TLS session. Unfortunately, session renegotiation requires a disproportionate amount @@ -449,34 +449,34 @@ has the property `code` which can take one of the following values: * `'CERT_REJECTED'`: Certificate rejected. * `'HOSTNAME_MISMATCH'`: Hostname mismatch. -### `tls.CryptoStream` +### `tls.CryptoStream` - + - + The `tls.CryptoStream` class represents a stream of encrypted data. This class is deprecated and should no longer be used. -#### `cryptoStream.bytesWritten` +#### `cryptoStream.bytesWritten` - + The `cryptoStream.bytesWritten` property returns the total number of bytes written to the underlying socket _including_ the bytes required for the implementation of the TLS protocol. -### `tls.SecurePair` +### `tls.SecurePair` - + - + Returned by [`tls.createSecurePair()`][]. -#### `'secure'` +#### `'secure'` - + The `'secure'` event is emitted by the `SecurePair` object once a secure connection has been established. @@ -486,17 +486,17 @@ As with checking for the server event, `pair.cleartext.authorized` should be inspected to confirm whether the certificate used is properly authorized. -### `tls.Server` +### `tls.Server` - + * Extends: [`net.Server`](/api/net#netserver) Accepts encrypted connections using TLS or SSL. -#### `'connection'` +#### `'connection'` - + * `socket` [`stream.Duplex`](/api/stream#streamduplex) @@ -508,9 +508,9 @@ will not receive events unlike the socket created from the [`net.Server`][] This event can also be explicitly emitted by users to inject connections into the TLS server. In that case, any [`Duplex`][] stream can be passed. -#### `'keylog'` +#### `'keylog'` - + * `line` [`Buffer`](/api/buffer#buffer) Line of ASCII text, in NSS `SSLKEYLOGFILE` format. * `tlsSocket` [`tls.TLSSocket`](/api/tls#tlstlssocket) The `tls.TLSSocket` instance on which it was @@ -535,9 +535,9 @@ server.on('keylog', (line, tlsSocket) => { }); ``` -#### `'newSession'` +#### `'newSession'` - + The `'newSession'` event is emitted upon creation of a new TLS session. This may be used to store sessions in external storage. The data should be provided to @@ -553,9 +553,9 @@ The listener callback is passed three arguments when called: Listening for this event will have an effect only on connections established after the addition of the event listener. -#### `'OCSPRequest'` +#### `'OCSPRequest'` - + The `'OCSPRequest'` event is emitted when the client sends a certificate status request. The listener callback is passed three arguments when called: @@ -599,9 +599,9 @@ after the addition of the event listener. An npm module like [asn1.js][] may be used to parse the certificates. -#### `'resumeSession'` +#### `'resumeSession'` - + The `'resumeSession'` event is emitted when the client requests to resume a previous TLS session. The listener callback is passed two arguments when @@ -637,9 +637,9 @@ server.on('resumeSession', (id, cb) => { }); ``` -#### `'secureConnection'` +#### `'secureConnection'` - + The `'secureConnection'` event is emitted after the handshaking process for a new connection has successfully completed. The listener callback is passed a @@ -660,9 +660,9 @@ equals `false`. The `tlsSocket.servername` property is a string containing the server name requested via SNI. -#### `'tlsClientError'` +#### `'tlsClientError'` - + The `'tlsClientError'` event is emitted when an error occurs before a secure connection is established. The listener callback is passed two arguments when @@ -672,9 +672,9 @@ called: * `tlsSocket` [`tls.TLSSocket`](/api/tls#tlstlssocket) The `tls.TLSSocket` instance from which the error originated. -#### `server.addContext(hostname, context)` +#### `server.addContext(hostname, context)` - + * `hostname` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) A SNI host name or wildcard (e.g. `'*'`) * `context` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) An object containing any of the possible properties @@ -687,9 +687,9 @@ the client request's SNI name matches the supplied `hostname` (or wildcard). When there are multiple matching contexts, the most recently added one is used. -#### `server.address()` +#### `server.address()` - + * Returns: [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) @@ -697,9 +697,9 @@ Returns the bound address, the address family name, and port of the server as reported by the operating system. See [`net.Server.address()`][] for more information. -#### `server.close([callback])` +#### `server.close([callback])` - + * `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) A listener callback that will be registered to listen for the server instance's `'close'` event. @@ -710,9 +710,9 @@ The `server.close()` method stops the server from accepting new connections. This function operates asynchronously. The `'close'` event will be emitted when the server has no more open connections. -#### `server.getTicketKeys()` +#### `server.getTicketKeys()` - + * Returns: [`Buffer`](/api/buffer#buffer) A 48-byte buffer containing the session ticket keys. @@ -720,14 +720,14 @@ Returns the session ticket keys. See [Session Resumption][] for more information. -#### `server.listen()` +#### `server.listen()` Starts the server listening for encrypted connections. This method is identical to [`server.listen()`][] from [`net.Server`][]. -#### `server.setSecureContext(options)` +#### `server.setSecureContext(options)` - + * `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) An object containing any of the possible properties from the [`tls.createSecureContext()`][] `options` arguments (e.g. `key`, `cert`, @@ -736,9 +736,9 @@ This method is identical to [`server.listen()`][] from [`net.Server`][]. The `server.setSecureContext()` method replaces the secure context of an existing server. Existing connections to the server are not interrupted. -#### `server.setTicketKeys(keys)` +#### `server.setTicketKeys(keys)` - + * `keys` [`Buffer`](/api/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) A 48-byte buffer containing the session ticket keys. @@ -750,9 +750,9 @@ Existing or currently pending server connections will use the previous keys. See [Session Resumption][] for more information. -### `tls.TLSSocket` +### `tls.TLSSocket` - + * Extends: [`net.Socket`](/api/net#netsocket) @@ -762,12 +762,12 @@ negotiation. Instances of `tls.TLSSocket` implement the duplex [Stream][] interface. Methods that return TLS connection metadata (e.g. -[`tls.TLSSocket.getPeerCertificate()`][] will only return data while the +[`tls.TLSSocket.getPeerCertificate()`][]) will only return data while the connection is open. -#### `new tls.TLSSocket(socket[, options])` +#### `new tls.TLSSocket(socket[, options])` - + * `socket` [`net.Socket`](/api/net#netsocket) | [`stream.Duplex`](/api/stream#streamduplex) On the server side, any `Duplex` stream. On the client side, any @@ -799,9 +799,9 @@ connection is open. Construct a new `tls.TLSSocket` object from an existing TCP socket. -#### `'keylog'` +#### `'keylog'` - + * `line` [`Buffer`](/api/buffer#buffer) Line of ASCII text, in NSS `SSLKEYLOGFILE` format. @@ -819,9 +819,9 @@ const logFile = fs.createWriteStream('/tmp/ssl-keys.log', { flags: 'a' }); tlsSocket.on('keylog', (line) => logFile.write(line)); ``` -#### `'OCSPResponse'` +#### `'OCSPResponse'` - + The `'OCSPResponse'` event is emitted if the `requestOCSP` option was set when the `tls.TLSSocket` was created and an OCSP response has been received. @@ -832,9 +832,9 @@ The listener callback is passed a single argument when called: Typically, the `response` is a digitally signed object from the server's CA that contains information about server's certificate revocation status. -#### `'secureConnect'` +#### `'secureConnect'` - + The `'secureConnect'` event is emitted after the handshaking process for a new connection has successfully completed. The listener callback will be called @@ -849,9 +849,9 @@ protocol. The `'secureConnect'` event is not emitted when a [`tls.TLSSocket`](/api/tls#tlstlssocket) is created using the `new tls.TLSSocket()` constructor. -#### `'session'` +#### `'session'` - + * `session` [`Buffer`](/api/buffer#buffer) @@ -887,42 +887,42 @@ tlsSocket.once('session', (session) => { }); ``` -#### `tlsSocket.address()` +#### `tlsSocket.address()` - + * Returns: [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) Returns the bound `address`, the address `family` name, and `port` of the underlying socket as reported by the operating system: -`{ port: 12346, family: 'IPv4', address: '127.0.0.1' }`. +````{ port: 12346, family: 'IPv4', address: '127.0.0.1' }````. -#### `tlsSocket.authorizationError` +#### `tlsSocket.authorizationError` - + Returns the reason why the peer's certificate was not been verified. This property is set only when `tlsSocket.authorized === false`. -#### `tlsSocket.authorized` +#### `tlsSocket.authorized` - + * [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) This property is `true` if the peer certificate was signed by one of the CAs specified when creating the `tls.TLSSocket` instance, otherwise `false`. -#### `tlsSocket.disableRenegotiation()` +#### `tlsSocket.disableRenegotiation()` - + Disables TLS renegotiation for this `TLSSocket` instance. Once called, attempts to renegotiate will trigger an `'error'` event on the `TLSSocket`. -#### `tlsSocket.enableTrace()` +#### `tlsSocket.enableTrace()` - + When enabled, TLS packet trace information is written to `stderr`. This can be used to debug TLS connection problems. @@ -932,16 +932,16 @@ The format of the output is identical to the output of OpenSSL's `SSL_trace()` function, the format is undocumented, can change without notice, and should not be relied on. -#### `tlsSocket.encrypted` +#### `tlsSocket.encrypted` - + Always returns `true`. This may be used to distinguish TLS sockets from regular `net.Socket` instances. -#### `tlsSocket.exportKeyingMaterial(length, label[, context])` +#### `tlsSocket.exportKeyingMaterial(length, label[, context])` - + * `length` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) number of bytes to retrieve from keying material @@ -974,9 +974,9 @@ const keyingMaterial = tlsSocket.exportKeyingMaterial( See the OpenSSL [`SSL_export_keying_material`][] documentation for more information. -#### `tlsSocket.getCertificate()` +#### `tlsSocket.getCertificate()` - + * Returns: [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) @@ -989,9 +989,9 @@ structure. If there is no local certificate, an empty object will be returned. If the socket has been destroyed, `null` will be returned. -#### `tlsSocket.getCipher()` +#### `tlsSocket.getCipher()` - + * Returns: [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) * `name` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) OpenSSL name for the cipher suite. @@ -1015,9 +1015,9 @@ See [SSL\_CIPHER\_get\_name](https://www.openssl.org/docs/man1.1.1/man3/SSL_CIPHER_get_name.html) for more information. -#### `tlsSocket.getEphemeralKeyInfo()` +#### `tlsSocket.getEphemeralKeyInfo()` - + * Returns: [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) @@ -1028,11 +1028,11 @@ ephemeral. As this is only supported on a client socket; `null` is returned if called on a server socket. The supported types are `'DH'` and `'ECDH'`. The `name` property is available only when type is `'ECDH'`. -For example: `{ type: 'ECDH', name: 'prime256v1', size: 256 }`. +For example: ````{ type: 'ECDH', name: 'prime256v1', size: 256 }````. -#### `tlsSocket.getFinished()` +#### `tlsSocket.getFinished()` - + * Returns: [`Buffer`](/api/buffer#buffer) | [`undefined`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type) The latest `Finished` message that has been sent to the socket as part of a SSL/TLS handshake, or `undefined` if @@ -1046,9 +1046,9 @@ provided by SSL/TLS is not desired or is not enough. Corresponds to the `SSL_get_finished` routine in OpenSSL and may be used to implement the `tls-unique` channel binding from [RFC 5929][]. -#### `tlsSocket.getPeerCertificate([detailed])` +#### `tlsSocket.getPeerCertificate([detailed])` - + * `detailed` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) Include the full certificate chain if `true`, otherwise include just the peer's certificate. @@ -1064,7 +1064,7 @@ certificate. ##### Certificate object - + A certificate object has properties corresponding to the fields of the certificate. @@ -1074,7 +1074,7 @@ certificate. Country (`C`), StateOrProvince (`ST`), Locality (`L`), Organization (`O`), OrganizationalUnit (`OU`), and CommonName (`CN`). The CommonName is typically a DNS name with TLS certificates. Example: - `{C: 'UK', ST: 'BC', L: 'Metro', O: 'Node Fans', OU: 'Docs', CN: 'example.com'}`. + ````{C: 'UK', ST: 'BC', L: 'Metro', O: 'Node Fans', OU: 'Docs', CN: 'example.com'}````. * `issuer` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) The certificate issuer, described in the same terms as the `subject`. * `valid_from` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The date-time the certificate is valid from. @@ -1153,9 +1153,9 @@ Example certificate: raw: } ``` -#### `tlsSocket.getPeerFinished()` +#### `tlsSocket.getPeerFinished()` - + * Returns: [`Buffer`](/api/buffer#buffer) | [`undefined`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type) The latest `Finished` message that is expected or has actually been received from the socket as part of a SSL/TLS handshake, @@ -1169,20 +1169,20 @@ provided by SSL/TLS is not desired or is not enough. Corresponds to the `SSL_get_peer_finished` routine in OpenSSL and may be used to implement the `tls-unique` channel binding from [RFC 5929][]. -#### `tlsSocket.getPeerX509Certificate()` +#### `tlsSocket.getPeerX509Certificate()` - + -* Returns: {X509Certificate} +* Returns: [`X509Certificate`](/api/crypto#x509certificate) -Returns the peer certificate as an {X509Certificate} object. +Returns the peer certificate as an [`X509Certificate`](/api/crypto#x509certificate) object. If there is no peer certificate, or the socket has been destroyed, `undefined` will be returned. -#### `tlsSocket.getProtocol()` +#### `tlsSocket.getProtocol()` - + * Returns: [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`null`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type) @@ -1201,9 +1201,9 @@ Protocol versions are: See the OpenSSL [`SSL_get_version`][] documentation for more information. -#### `tlsSocket.getSession()` +#### `tlsSocket.getSession()` - + * [`Buffer`](/api/buffer#buffer) @@ -1217,9 +1217,9 @@ See [Session Resumption][] for more information. Note: `getSession()` works only for TLSv1.2 and below. For TLSv1.3, applications must use the [`'session'`][] event (it also works for TLSv1.2 and below). -#### `tlsSocket.getSharedSigalgs()` +#### `tlsSocket.getSharedSigalgs()` - + * Returns: [`Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array) List of signature algorithms shared between the server and the client in the order of decreasing preference. @@ -1228,9 +1228,9 @@ See [SSL\_get\_shared\_sigalgs](https://www.openssl.org/docs/man1.1.1/man3/SSL_get_shared_sigalgs.html) for more information. -#### `tlsSocket.getTLSTicket()` +#### `tlsSocket.getTLSTicket()` - + * [`Buffer`](/api/buffer#buffer) @@ -1241,69 +1241,69 @@ It may be useful for debugging. See [Session Resumption][] for more information. -#### `tlsSocket.getX509Certificate()` +#### `tlsSocket.getX509Certificate()` - + -* Returns: {X509Certificate} +* Returns: [`X509Certificate`](/api/crypto#x509certificate) -Returns the local certificate as an {X509Certificate} object. +Returns the local certificate as an [`X509Certificate`](/api/crypto#x509certificate) object. If there is no local certificate, or the socket has been destroyed, `undefined` will be returned. -#### `tlsSocket.isSessionReused()` +#### `tlsSocket.isSessionReused()` - + * Returns: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) `true` if the session was reused, `false` otherwise. See [Session Resumption][] for more information. -#### `tlsSocket.localAddress` +#### `tlsSocket.localAddress` - + * [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) Returns the string representation of the local IP address. -#### `tlsSocket.localPort` +#### `tlsSocket.localPort` - + * [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Returns the numeric representation of the local port. -#### `tlsSocket.remoteAddress` +#### `tlsSocket.remoteAddress` - + * [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) Returns the string representation of the remote IP address. For example, `'74.125.127.100'` or `'2001:4860:a005::68'`. -#### `tlsSocket.remoteFamily` +#### `tlsSocket.remoteFamily` - + * [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) Returns the string representation of the remote IP family. `'IPv4'` or `'IPv6'`. -#### `tlsSocket.remotePort` +#### `tlsSocket.remotePort` - + * [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Returns the numeric representation of the remote port. For example, `443`. -#### `tlsSocket.renegotiate(options, callback)` +#### `tlsSocket.renegotiate(options, callback)` - + * `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) * `rejectUnauthorized` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) If not `false`, the server certificate is @@ -1333,9 +1333,9 @@ When running as the server, the socket will be destroyed with an error after For TLSv1.3, renegotiation cannot be initiated, it is not supported by the protocol. -#### `tlsSocket.setMaxSendFragment(size)` +#### `tlsSocket.setMaxSendFragment(size)` - + * `size` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The maximum TLS fragment size. The maximum value is `16384`. **Default:** `16384`. @@ -1351,9 +1351,9 @@ and their processing can be delayed due to packet loss or reordering. However, smaller fragments add extra TLS framing bytes and CPU overhead, which may decrease overall server throughput. -### `tls.checkServerIdentity(hostname, cert)` +### `tls.checkServerIdentity(hostname, cert)` - + * `hostname` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The host name or IP address to verify the certificate against. @@ -1384,9 +1384,9 @@ was present (see [CVE-2021-44531][]). Applications that wish to accept `uniformResourceIdentifier` subject alternative names can use a custom `options.checkServerIdentity` function that implements the desired behavior. -### `tls.connect(options[, callback])` +### `tls.connect(options[, callback])` - + * `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) * `enableTrace`: See [`tls.createServer()`][] @@ -1418,7 +1418,7 @@ was present (see [CVE-2021-44531][]). Applications that wish to accept decide which identity to use during negotiation. Always `null` if TLS 1.3 is used. * Returns: [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) in the form - `{ psk: [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray), identity: }` + ````{ psk: [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray), identity: }```` or `null` to stop the negotiation process. `psk` must be compatible with the selected cipher's digest. `identity` must use UTF-8 encoding. @@ -1431,8 +1431,7 @@ was present (see [CVE-2021-44531][]). Applications that wish to accept of the server against the certificate but that's not applicable for PSK because there won't be a certificate present. More information can be found in the [RFC 4279][]. - * `ALPNProtocols`: {string\[]|Buffer\[]|TypedArray\[]|DataView\[]|Buffer| - TypedArray|DataView} + * `ALPNProtocols`: [`Buffer`](/api/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) An array of strings, `Buffer`s, `TypedArray`s, or `DataView`s, or a single `Buffer`, `TypedArray`, or `DataView` containing the supported ALPN protocols. `Buffer`s should have the format `[len][name][len][name]...` @@ -1518,9 +1517,9 @@ socket.on('end', () => { }); ``` -### `tls.connect(path[, options][, callback])` +### `tls.connect(path[, options][, callback])` - + * `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) Default value for `options.path`. * `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) See [`tls.connect()`][]. @@ -1532,9 +1531,9 @@ as an argument instead of an option. A path option, if specified, will take precedence over the path argument. -### `tls.connect(port[, host][, options][, callback])` +### `tls.connect(port[, host][, options][, callback])` - + * `port` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Default value for `options.port`. * `host` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) Default value for `options.host`. @@ -1548,9 +1547,9 @@ as arguments instead of options. A port or host option, if specified, will take precedence over any port or host argument. -### `tls.createSecureContext([options])` +### `tls.createSecureContext([options])` - + * `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) * `ca` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) Optionally override the trusted CA @@ -1616,7 +1615,7 @@ argument. keys will be decrypted with `options.passphrase`. Multiple keys using different algorithms can be provided either as an array of unencrypted key strings or buffers, or an array of objects in the form - `{pem: [, passphrase: ]}`. The object form can only + ````{pem: [, passphrase: ]}````. The object form can only occur in an array. `object.passphrase` is optional. Encrypted keys will be decrypted with `object.passphrase` if provided, or `options.passphrase` if it is not. @@ -1643,7 +1642,7 @@ argument. `key` and `cert` individually. PFX is usually encrypted, if it is, `passphrase` will be used to decrypt it. Multiple PFX can be provided either as an array of unencrypted PFX buffers, or an array of objects in the form - `{buf: [, passphrase: ]}`. The object form can only + ````{buf: [, passphrase: ]}````. The object form can only occur in an array. `object.passphrase` is optional. Encrypted PFX will be decrypted with `object.passphrase` if provided, or `options.passphrase` if it is not. @@ -1685,11 +1684,11 @@ A key is _required_ for ciphers that use certificates. Either `key` or If the `ca` option is not given, then Node.js will default to using [Mozilla's publicly trusted list of CAs][]. -### `tls.createSecurePair([context][, isServer][, requestCert][, rejectUnauthorized][, options])` +### `tls.createSecurePair([context][, isServer][, requestCert][, rejectUnauthorized][, options])` - + - + * `context` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) A secure context object as returned by `tls.createSecureContext()` @@ -1742,13 +1741,12 @@ secureSocket = tls.TLSSocket(socket, options); where `secureSocket` has the same API as `pair.cleartext`. -### `tls.createServer([options][, secureConnectionListener])` +### `tls.createServer([options][, secureConnectionListener])` - + * `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) - * `ALPNProtocols`: {string\[]|Buffer\[]|TypedArray\[]|DataView\[]|Buffer| - TypedArray|DataView} + * `ALPNProtocols`: [`Buffer`](/api/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) An array of strings, `Buffer`s, `TypedArray`s, or `DataView`s, or a single `Buffer`, `TypedArray`, or `DataView` containing the supported ALPN protocols. `Buffer`s should have the format `[len][name][len][name]...` @@ -1853,9 +1851,9 @@ server.listen(8000, () => { The server can be tested by connecting to it using the example client from [`tls.connect()`][]. -### `tls.getCiphers()` +### `tls.getCiphers()` - + * Returns: string\[] @@ -1873,9 +1871,9 @@ TLSv1.2 and below. console.log(tls.getCiphers()); // ['aes128-gcm-sha256', 'aes128-sha', ...] ``` -### `tls.rootCertificates` +### `tls.rootCertificates` - + * string\[] @@ -1885,17 +1883,17 @@ from the bundled Mozilla CA store as supplied by the current Node.js version. The bundled CA store, as supplied by Node.js, is a snapshot of Mozilla CA store that is fixed at release time. It is identical on all supported platforms. -### `tls.DEFAULT_ECDH_CURVE` +### `tls.DEFAULT_ECDH_CURVE` - + The default curve name to use for ECDH key agreement in a tls server. The default value is `'auto'`. See [`tls.createSecureContext()`][] for further information. -### `tls.DEFAULT_MAX_VERSION` +### `tls.DEFAULT_MAX_VERSION` - + * [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The default value of the `maxVersion` option of [`tls.createSecureContext()`][]. It can be assigned any of the supported TLS @@ -1905,9 +1903,9 @@ information. the default to `'TLSv1.3'`. If multiple of the options are provided, the highest maximum is used. -### `tls.DEFAULT_MIN_VERSION` +### `tls.DEFAULT_MIN_VERSION` - + * [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The default value of the `minVersion` option of [`tls.createSecureContext()`][]. It can be assigned any of the supported TLS diff --git a/content/api/v18/tracing.en.md b/content/api/v18/tracing.en.md index cfdafc7f81..61a0ecdb0e 100644 --- a/content/api/v18/tracing.en.md +++ b/content/api/v18/tracing.en.md @@ -2,15 +2,15 @@ title: 'tracing' displayTitle: 'Trace events' category: 'api' -editPage: 'https://github.com/nodejs/node/blob/v18.8.0/doc/api/tracing.md' +editPage: 'https://github.com/nodejs/node/blob/v18.9.0/doc/api/tracing.md' version: 'v18' --- - + - + - + The `node:trace_events` module provides a mechanism to centralize tracing information generated by V8, Node.js core, and userspace code. @@ -32,6 +32,11 @@ The available categories are: * `node.net.native`: Enables capture of trace data for network. * `node.environment`: Enables capture of Node.js Environment milestones. * `node.fs.sync`: Enables capture of trace data for file system sync methods. +* `node.fs_dir.sync`: Enables capture of trace data for file system sync + directory methods. +* `node.fs.async`: Enables capture of trace data for file system async methods. +* `node.fs_dir.async`: Enables capture of trace data for file system async + directory methods. * `node.perf`: Enables capture of [Performance API][] measurements. * `node.perf.usertiming`: Enables capture of only Performance API User Timing measures and marks. @@ -58,7 +63,7 @@ flag to enable trace events. This requirement has been removed. However, the ```bash node --trace-events-enabled -## is equivalent to +# is equivalent to node --trace-event-categories v8,node,node.async_hooks ``` @@ -85,7 +90,7 @@ be specified with `--trace-event-file-pattern` that accepts a template string that supports `$rotation` and `$pid`: ```bash -node --trace-event-categories v8 --trace-event-file-pattern '$pid-$rotation.log' server.js +node --trace-event-categories v8 --trace-event-file-pattern '${pid}-${rotation}.log' server.js ``` To guarantee that the log file is properly generated after signal events like @@ -108,11 +113,11 @@ The features from this module are not available in [`Worker`][] threads. ### The `node:trace_events` module - + -#### `Tracing` object +#### `Tracing` object - + The `Tracing` object is used to enable or disable tracing for sets of categories. Instances are created using the `trace_events.createTracing()` @@ -123,18 +128,18 @@ When created, the `Tracing` object is disabled. Calling the categories. Calling `tracing.disable()` will remove the categories from the set of enabled trace event categories. -##### `tracing.categories` +##### `tracing.categories` - + * [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) A comma-separated list of the trace event categories covered by this `Tracing` object. -##### `tracing.disable()` +##### `tracing.disable()` - + Disables this `Tracing` object. @@ -157,22 +162,22 @@ t2.disable(); // Will only disable emission of the 'node.perf' category console.log(trace_events.getEnabledCategories()); ``` -##### `tracing.enable()` +##### `tracing.enable()` - + Enables this `Tracing` object for the set of categories covered by the `Tracing` object. -##### `tracing.enabled` +##### `tracing.enabled` - + * [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) `true` only if the `Tracing` object has been enabled. -#### `trace_events.createTracing(options)` +#### `trace_events.createTracing(options)` - + * `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) * `categories` string\[] An array of trace category names. Values included @@ -191,9 +196,9 @@ tracing.enable(); tracing.disable(); ``` -#### `trace_events.getEnabledCategories()` +#### `trace_events.getEnabledCategories()` - + * Returns: [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) diff --git a/content/api/v18/tty.en.md b/content/api/v18/tty.en.md index 55b62b8449..4ceff1a392 100644 --- a/content/api/v18/tty.en.md +++ b/content/api/v18/tty.en.md @@ -2,15 +2,15 @@ title: 'tty' displayTitle: 'TTY' category: 'api' -editPage: 'https://github.com/nodejs/node/blob/v18.8.0/doc/api/tty.md' +editPage: 'https://github.com/nodejs/node/blob/v18.9.0/doc/api/tty.md' version: 'v18' --- - + - + - + The `node:tty` module provides the `tty.ReadStream` and `tty.WriteStream` classes. In most cases, it will not be necessary or possible to use this module @@ -38,9 +38,9 @@ In most cases, there should be little to no reason for an application to manually create instances of the `tty.ReadStream` and `tty.WriteStream` classes. -### `tty.ReadStream` +### `tty.ReadStream` - + * Extends: [`net.Socket`](/api/net#netsocket) @@ -48,22 +48,22 @@ Represents the readable side of a TTY. In normal circumstances [`process.stdin`][] will be the only `tty.ReadStream` instance in a Node.js process and there should be no reason to create additional instances. -#### `readStream.isRaw` +#### `readStream.isRaw` - + A `boolean` that is `true` if the TTY is currently configured to operate as a raw device. Defaults to `false`. -#### `readStream.isTTY` +#### `readStream.isTTY` - + A `boolean` that is always `true` for `tty.ReadStream` instances. -#### `readStream.setRawMode(mode)` +#### `readStream.setRawMode(mode)` - + * `mode` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) If `true`, configures the `tty.ReadStream` to operate as a raw device. If `false`, configures the `tty.ReadStream` to operate in its @@ -79,9 +79,9 @@ terminal is disabled, including echoing input characters. Ctrl+C will no longer cause a `SIGINT` when in this mode. -### `tty.WriteStream` +### `tty.WriteStream` - + * Extends: [`net.Socket`](/api/net#netsocket) @@ -90,9 +90,9 @@ Represents the writable side of a TTY. In normal circumstances, `tty.WriteStream` instances created for a Node.js process and there should be no reason to create additional instances. -#### `'resize'` +#### `'resize'` - + The `'resize'` event is emitted whenever either of the `writeStream.columns` or `writeStream.rows` properties have changed. No arguments are passed to the @@ -101,13 +101,13 @@ listener callback when called. ```js process.stdout.on('resize', () => { console.log('screen size has changed!'); - console.log(`$process.stdout.columnsx$process.stdout.rows`); + console.log(`${process.stdout.columns}x${process.stdout.rows}`); }); ``` -#### `writeStream.clearLine(dir[, callback])` +#### `writeStream.clearLine(dir[, callback])` - + * `dir` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) * `-1`: to the left from cursor @@ -121,9 +121,9 @@ process.stdout.on('resize', () => { `writeStream.clearLine()` clears the current line of this `WriteStream` in a direction identified by `dir`. -#### `writeStream.clearScreenDown([callback])` +#### `writeStream.clearScreenDown([callback])` - + * `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) Invoked once the operation completes. * Returns: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) `false` if the stream wishes for the calling code to wait @@ -133,16 +133,16 @@ direction identified by `dir`. `writeStream.clearScreenDown()` clears this `WriteStream` from the current cursor down. -#### `writeStream.columns` +#### `writeStream.columns` - + A `number` specifying the number of columns the TTY currently has. This property is updated whenever the `'resize'` event is emitted. -#### `writeStream.cursorTo(x[, y][, callback])` +#### `writeStream.cursorTo(x[, y][, callback])` - + * `x` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) * `y` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) @@ -154,9 +154,9 @@ is updated whenever the `'resize'` event is emitted. `writeStream.cursorTo()` moves this `WriteStream`'s cursor to the specified position. -#### `writeStream.getColorDepth([env])` +#### `writeStream.getColorDepth([env])` - + * `env` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) An object containing the environment variables to check. This enables simulating the usage of a specific terminal. **Default:** @@ -187,9 +187,9 @@ To enforce a specific color support, use one of the below environment settings. Disabling color support is also possible by using the `NO_COLOR` and `NODE_DISABLE_COLORS` environment variables. -#### `writeStream.getWindowSize()` +#### `writeStream.getWindowSize()` - + * Returns: number\[] @@ -198,9 +198,9 @@ corresponding to this `WriteStream`. The array is of the type `[numColumns, numRows]` where `numColumns` and `numRows` represent the number of columns and rows in the corresponding TTY. -#### `writeStream.hasColors([count][, env])` +#### `writeStream.hasColors([count][, env])` - + * `count` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The number of colors that are requested (minimum 2). **Default:** 16. @@ -226,15 +226,15 @@ process.stdout.hasColors(2 ** 24, { TMUX: '1' }); // Returns false (the environment setting pretends to support 2 ** 8 colors). ``` -#### `writeStream.isTTY` +#### `writeStream.isTTY` - + A `boolean` that is always `true`. -#### `writeStream.moveCursor(dx, dy[, callback])` +#### `writeStream.moveCursor(dx, dy[, callback])` - + * `dx` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) * `dy` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) @@ -246,16 +246,16 @@ A `boolean` that is always `true`. `writeStream.moveCursor()` moves this `WriteStream`'s cursor _relative_ to its current position. -#### `writeStream.rows` +#### `writeStream.rows` - + A `number` specifying the number of rows the TTY currently has. This property is updated whenever the `'resize'` event is emitted. -### `tty.isatty(fd)` +### `tty.isatty(fd)` - + * `fd` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) A numeric file descriptor * Returns: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) diff --git a/content/api/v18/url.en.md b/content/api/v18/url.en.md index 118bec7a86..16dc9327de 100644 --- a/content/api/v18/url.en.md +++ b/content/api/v18/url.en.md @@ -2,15 +2,15 @@ title: 'url' displayTitle: 'URL' category: 'api' -editPage: 'https://github.com/nodejs/node/blob/v18.8.0/doc/api/url.md' +editPage: 'https://github.com/nodejs/node/blob/v18.9.0/doc/api/url.md' version: 'v18' --- - + - + - + The `node:url` module provides utilities for URL resolution and parsing. It can be accessed using: @@ -99,7 +99,7 @@ myURL.hash = '#fgh'; const pathname = '/a/b/c'; const search = '?d=e'; const hash = '#fgh'; -const myURL = new URL(`https://example.org$pathname$search$hash`); +const myURL = new URL(`https://example.org${pathname}${search}${hash}`); ``` To get the constructed URL string, use the `href` property accessor: @@ -110,9 +110,9 @@ console.log(myURL.href); ### The WHATWG URL API -#### `URL` +#### `URL` - + Browser-compatible `URL` class, implemented by following the WHATWG URL Standard. [Examples of parsed URLs][] may be found in the Standard itself. @@ -125,7 +125,7 @@ using the `delete` keyword on any properties of `URL` objects (e.g. `delete myURL.protocol`, `delete myURL.pathname`, etc) has no effect but will still return `true`. -##### `new URL(input[, base])` +##### `new URL(input[, base])` * `input` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The absolute or relative input URL to parse. If `input` is relative, then `base` is required. If `input` is absolute, the `base` @@ -197,7 +197,7 @@ myURL = new URL('foo:Example.com/', 'https://example.org/'); // foo:Example.com/ ``` -##### `url.hash` +##### `url.hash` * [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) @@ -218,7 +218,7 @@ are [percent-encoded][]. The selection of which characters to percent-encode may vary somewhat from what the [`url.parse()`][] and [`url.format()`][] methods would produce. -##### `url.host` +##### `url.host` * [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) @@ -236,7 +236,7 @@ console.log(myURL.href); Invalid host values assigned to the `host` property are ignored. -##### `url.hostname` +##### `url.hostname` * [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) @@ -262,7 +262,7 @@ console.log(myURL.href); Invalid host name values assigned to the `hostname` property are ignored. -##### `url.href` +##### `url.href` * [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) @@ -288,9 +288,9 @@ object's properties will be modified. If the value assigned to the `href` property is not a valid URL, a `TypeError` will be thrown. -##### `url.origin` +##### `url.origin` - + * [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) @@ -311,7 +311,7 @@ console.log(idnURL.hostname); // Prints xn--g6w251d ``` -##### `url.password` +##### `url.password` * [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) @@ -332,7 +332,7 @@ are [percent-encoded][]. The selection of which characters to percent-encode may vary somewhat from what the [`url.parse()`][] and [`url.format()`][] methods would produce. -##### `url.pathname` +##### `url.pathname` * [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) @@ -353,9 +353,9 @@ property are [percent-encoded][]. The selection of which characters to percent-encode may vary somewhat from what the [`url.parse()`][] and [`url.format()`][] methods would produce. -##### `url.port` +##### `url.port` - + * [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) @@ -438,7 +438,7 @@ console.log(myURL.port); // Prints 4 (because it is the leading number in the string '4.567e21') ``` -##### `url.protocol` +##### `url.protocol` * [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) @@ -458,7 +458,7 @@ Invalid URL protocol values assigned to the `protocol` property are ignored. ###### Special schemes - + The [WHATWG URL Standard][] considers a handful of URL protocol schemes to be _special_ in terms of how they are parsed and serialized. When a URL is @@ -498,7 +498,7 @@ console.log(u.href); According to the WHATWG URL Standard, special protocol schemes are `ftp`, `file`, `http`, `https`, `ws`, and `wss`. -##### `url.search` +##### `url.search` * [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) @@ -519,7 +519,7 @@ property will be [percent-encoded][]. The selection of which characters to percent-encode may vary somewhat from what the [`url.parse()`][] and [`url.format()`][] methods would produce. -##### `url.searchParams` +##### `url.searchParams` * [`URLSearchParams`](/api/url#urlsearchparams) @@ -546,7 +546,7 @@ myUrl.searchParams.sort(); console.log(myUrl.search); // prints ?foo=%7Ebar ``` -##### `url.username` +##### `url.username` * [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) @@ -567,14 +567,14 @@ property will be [percent-encoded][]. The selection of which characters to percent-encode may vary somewhat from what the [`url.parse()`][] and [`url.format()`][] methods would produce. -##### `url.toString()` +##### `url.toString()` * Returns: [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The `toString()` method on the `URL` object returns the serialized URL. The value returned is equivalent to that of [`url.href`][] and [`url.toJSON()`][]. -##### `url.toJSON()` +##### `url.toJSON()` * Returns: [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) @@ -594,11 +594,11 @@ console.log(JSON.stringify(myURLs)); // Prints ["https://www.example.com/","https://test.example.org/"] ``` -##### `URL.createObjectURL(blob)` +##### `URL.createObjectURL(blob)` - + - + * `blob` [`Blob`](/api/buffer#blob) * Returns: [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) @@ -628,11 +628,11 @@ The data stored by the registered [`Blob`](/api/buffer#blob) will be retained in Threads, `Blob` objects registered within one Worker will not be available to other workers or the main thread. -##### `URL.revokeObjectURL(id)` +##### `URL.revokeObjectURL(id)` - + - + * `id` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) A `'blob:nodedata:...` URL string returned by a prior call to `URL.createObjectURL()`. @@ -640,9 +640,9 @@ to other workers or the main thread. Removes the stored [`Blob`](/api/buffer#blob) identified by the given ID. Attempting to revoke a ID that isn't registered will silently fail. -#### `URLSearchParams` +#### `URLSearchParams` - + The `URLSearchParams` API provides read and write access to the query of a `URL`. The `URLSearchParams` class can also be used standalone with one of the @@ -687,11 +687,11 @@ console.log(myURL.href); // Prints https://example.org/?a=b&a=c ``` -##### `new URLSearchParams()` +##### `new URLSearchParams()` Instantiate a new empty `URLSearchParams` object. -##### `new URLSearchParams(string)` +##### `new URLSearchParams(string)` * `string` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) A query string @@ -712,9 +712,9 @@ console.log(params.toString()); // Prints 'user=abc&query=xyz' ``` -##### `new URLSearchParams(obj)` +##### `new URLSearchParams(obj)` - + * `obj` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) An object representing a collection of key-value pairs @@ -736,9 +736,9 @@ console.log(params.toString()); // Prints 'user=abc&query=first%2Csecond' ``` -##### `new URLSearchParams(iterable)` +##### `new URLSearchParams(iterable)` - + * `iterable` [`Iterable`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#The_iterable_protocol) An iterable object whose elements are key-value pairs @@ -789,20 +789,20 @@ new URLSearchParams([ // Each query pair must be an iterable [name, value] tuple ``` -##### `urlSearchParams.append(name, value)` +##### `urlSearchParams.append(name, value)` * `name` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) * `value` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) Append a new name-value pair to the query string. -##### `urlSearchParams.delete(name)` +##### `urlSearchParams.delete(name)` * `name` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) Remove all name-value pairs whose name is `name`. -##### `urlSearchParams.entries()` +##### `urlSearchParams.entries()` * Returns: [`Iterator`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#The_iterator_protocol) @@ -812,9 +812,9 @@ is the `name`, the second item of the `Array` is the `value`. Alias for [`urlSearchParams[@@iterator]()`][`urlSearchParams@@iterator()`]. -##### `urlSearchParams.forEach(fn[, thisArg])` +##### `urlSearchParams.forEach(fn[, thisArg])` - + * `fn` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) Invoked for each name-value pair in the query * `thisArg` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) To be used as `this` value for when `fn` is called @@ -831,7 +831,7 @@ myURL.searchParams.forEach((value, name, searchParams) => { // c d true ``` -##### `urlSearchParams.get(name)` +##### `urlSearchParams.get(name)` * `name` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) * Returns: [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) or `null` if there is no name-value pair with the given @@ -840,7 +840,7 @@ myURL.searchParams.forEach((value, name, searchParams) => { Returns the value of the first name-value pair whose name is `name`. If there are no such pairs, `null` is returned. -##### `urlSearchParams.getAll(name)` +##### `urlSearchParams.getAll(name)` * `name` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) * Returns: string\[] @@ -848,14 +848,14 @@ are no such pairs, `null` is returned. Returns the values of all name-value pairs whose name is `name`. If there are no such pairs, an empty array is returned. -##### `urlSearchParams.has(name)` +##### `urlSearchParams.has(name)` * `name` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) * Returns: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) Returns `true` if there is at least one name-value pair whose name is `name`. -##### `urlSearchParams.keys()` +##### `urlSearchParams.keys()` * Returns: [`Iterator`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#The_iterator_protocol) @@ -871,7 +871,7 @@ for (const name of params.keys()) { // foo ``` -##### `urlSearchParams.set(name, value)` +##### `urlSearchParams.set(name, value)` * `name` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) * `value` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) @@ -895,9 +895,9 @@ console.log(params.toString()); // Prints foo=def&abc=def&xyz=opq ``` -##### `urlSearchParams.sort()` +##### `urlSearchParams.sort()` - + Sort all existing name-value pairs in-place by their names. Sorting is done with a [stable sorting algorithm][], so relative order between name-value pairs @@ -912,20 +912,20 @@ console.log(params.toString()); // Prints query%5B%5D=abc&query%5B%5D=123&type=search ``` -##### `urlSearchParams.toString()` +##### `urlSearchParams.toString()` * Returns: [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) Returns the search parameters serialized as a string, with characters percent-encoded where necessary. -##### `urlSearchParams.values()` +##### `urlSearchParams.values()` * Returns: [`Iterator`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#The_iterator_protocol) Returns an ES6 `Iterator` over the values of each name-value pair. -##### `urlSearchParams[Symbol.iterator]()` +##### `urlSearchParams[Symbol.iterator]()` * Returns: [`Iterator`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#The_iterator_protocol) @@ -945,9 +945,9 @@ for (const [name, value] of params) { // xyz baz ``` -#### `url.domainToASCII(domain)` +#### `url.domainToASCII(domain)` - + * `domain` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) * Returns: [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) @@ -982,9 +982,9 @@ console.log(url.domainToASCII('xn--iñvalid.com')); // Prints an empty string ``` -#### `url.domainToUnicode(domain)` +#### `url.domainToUnicode(domain)` - + * `domain` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) * Returns: [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) @@ -1019,11 +1019,11 @@ console.log(url.domainToUnicode('xn--iñvalid.com')); // Prints an empty string ``` -#### `url.fileURLToPath(url)` +#### `url.fileURLToPath(url)` - + -* `url` {URL | string} The file URL string or URL object to convert to a path. +* `url` [`URL`](/api/url#the-whatwg-url-api) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The file URL string or URL object to convert to a path. * Returns: [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The fully-resolved platform-specific Node.js file path. This function ensures the correct decodings of percent-encoded characters as @@ -1062,9 +1062,9 @@ new URL('file:///hello world').pathname; // Incorrect: /hello%20world fileURLToPath('file:///hello world'); // Correct: /hello world (POSIX) ``` -#### `url.format(URL[, options])` +#### `url.format(URL[, options])` - + * `URL` [`URL`](/api/url#the-whatwg-url-api) A [WHATWG URL][] object * `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) @@ -1115,9 +1115,9 @@ console.log(url.format(myURL, { fragment: false, unicode: true, auth: false })); // Prints 'https://測試/?abc' ``` -#### `url.pathToFileURL(path)` +#### `url.pathToFileURL(path)` - + * `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The path to convert to a File URL. * Returns: [`URL`](/api/url#the-whatwg-url-api) The file URL object. @@ -1149,9 +1149,9 @@ new URL('/some/path%.c', 'file:'); // Incorrect: file:///some/path%.c pathToFileURL('/some/path%.c'); // Correct: file:///some/path%25.c (POSIX) ``` -#### `url.urlToHttpOptions(url)` +#### `url.urlToHttpOptions(url)` - + * `url` [`URL`](/api/url#the-whatwg-url-api) The [WHATWG URL][] object to convert to an options object. * Returns: [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) Options object @@ -1213,21 +1213,21 @@ console.log(urlToHttpOptions(myUrl)); ### Legacy URL API - + - + #### Legacy `urlObject` - + - + The legacy `urlObject` (`require('node:url').Url` or -`import { Url } from 'node:url'`) is +`import Url from 'node:url'`) is created and returned by the `url.parse()` function. -##### `urlObject.auth` +##### `urlObject.auth` The `auth` property is the username and password portion of the URL, also referred to as _userinfo_. This string subset follows the `protocol` and @@ -1237,35 +1237,35 @@ by `:`. For example: `'user:pass'`. -##### `urlObject.hash` +##### `urlObject.hash` The `hash` property is the fragment identifier portion of the URL including the leading `#` character. For example: `'#hash'`. -##### `urlObject.host` +##### `urlObject.host` The `host` property is the full lower-cased host portion of the URL, including the `port` if specified. For example: `'sub.example.com:8080'`. -##### `urlObject.hostname` +##### `urlObject.hostname` The `hostname` property is the lower-cased host name portion of the `host` component _without_ the `port` included. For example: `'sub.example.com'`. -##### `urlObject.href` +##### `urlObject.href` The `href` property is the full URL string that was parsed with both the `protocol` and `host` components converted to lower-case. For example: `'http://user:pass@sub.example.com:8080/p/a/t/h?query=string#hash'`. -##### `urlObject.path` +##### `urlObject.path` The `path` property is a concatenation of the `pathname` and `search` components. @@ -1274,7 +1274,7 @@ For example: `'/p/a/t/h?query=string'`. No decoding of the `path` is performed. -##### `urlObject.pathname` +##### `urlObject.pathname` The `pathname` property consists of the entire path section of the URL. This is everything following the `host` (including the `port`) and before the start @@ -1285,31 +1285,31 @@ For example: `'/p/a/t/h'`. No decoding of the path string is performed. -##### `urlObject.port` +##### `urlObject.port` The `port` property is the numeric port portion of the `host` component. For example: `'8080'`. -##### `urlObject.protocol` +##### `urlObject.protocol` The `protocol` property identifies the URL's lower-cased protocol scheme. For example: `'http:'`. -##### `urlObject.query` +##### `urlObject.query` The `query` property is either the query string without the leading ASCII question mark (`?`), or an object returned by the [`querystring`][] module's `parse()` method. Whether the `query` property is a string or object is determined by the `parseQueryString` argument passed to `url.parse()`. -For example: `'query=string'` or `{'query': 'string'}`. +For example: `'query=string'` or ````{'query': 'string'}````. If returned as a string, no decoding of the query string is performed. If returned as an object, both keys and values are decoded. -##### `urlObject.search` +##### `urlObject.search` The `search` property consists of the entire "query string" portion of the URL, including the leading ASCII question mark (`?`) character. @@ -1318,17 +1318,17 @@ For example: `'?query=string'`. No decoding of the query string is performed. -##### `urlObject.slashes` +##### `urlObject.slashes` The `slashes` property is a `boolean` with a value of `true` if two ASCII forward-slash characters (`/`) are required following the colon in the `protocol`. -#### `url.format(urlObject)` +#### `url.format(urlObject)` - + - + * `urlObject` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) A URL object (as returned by `url.parse()` or constructed otherwise). If a string, it is converted to an object by passing @@ -1407,11 +1407,11 @@ The formatting process operates as follows: string, an [`Error`][] is thrown. * `result` is returned. -#### `url.parse(urlString[, parseQueryString[, slashesDenoteHost]])` +#### `url.parse(urlString[, parseQueryString[, slashesDenoteHost]])` - + - + * `urlString` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The URL string to parse. * `parseQueryString` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) If `true`, the `query` property will always @@ -1421,7 +1421,7 @@ The formatting process operates as follows: * `slashesDenoteHost` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) If `true`, the first token after the literal string `//` and preceding the next `/` will be interpreted as the `host`. For instance, given `//foo/bar`, the result would be - `{host: 'foo', pathname: '/bar'}` rather than `{pathname: '//foo/bar'}`. + ````{host: 'foo', pathname: '/bar'}` rather than `{pathname: '//foo/bar'}````. **Default:** `false`. The `url.parse()` method takes a URL string, parses it, and returns a URL @@ -1444,11 +1444,11 @@ concerns, it is legacy and not deprecated because it is: Use with caution. -#### `url.resolve(from, to)` +#### `url.resolve(from, to)` - + - + * `from` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The base URL to use if `to` is a relative URL. * `to` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The target URL to resolve. diff --git a/content/api/v18/util.en.md b/content/api/v18/util.en.md index 1f98e8eefd..c182168437 100644 --- a/content/api/v18/util.en.md +++ b/content/api/v18/util.en.md @@ -2,15 +2,15 @@ title: 'util' displayTitle: 'Util' category: 'api' -editPage: 'https://github.com/nodejs/node/blob/v18.8.0/doc/api/util.md' +editPage: 'https://github.com/nodejs/node/blob/v18.9.0/doc/api/util.md' version: 'v18' --- - + - + - + The `node:util` module supports the needs of Node.js internal APIs. Many of the utilities are useful for application and module developers as well. To access @@ -20,9 +20,9 @@ it: const util = require('node:util'); ``` -### `util.callbackify(original)` +### `util.callbackify(original)` - + * `original` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) An `async` function * Returns: [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) a callback style function @@ -75,9 +75,9 @@ callbackFunction((err, ret) => { }); ``` -### `util.debuglog(section[, callback])` +### `util.debuglog(section[, callback])` - + * `section` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) A string identifying the portion of the application for which the `debuglog` function is being created. @@ -140,9 +140,9 @@ let debuglog = util.debuglog('internals', (debug) => { }); ``` -#### `debuglog().enabled` +#### `debuglog().enabled` - + * [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) @@ -167,16 +167,16 @@ output something like: hello from foo [123] ``` -### `util.debug(section)` +### `util.debug(section)` - + Alias for `util.debuglog`. Usage allows for readability of that doesn't imply logging when only using `util.debuglog().enabled`. -### `util.deprecate(fn, msg[, code])` +### `util.deprecate(fn, msg[, code])` - + * `fn` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) The function that is being deprecated. * `msg` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) A warning message to display when the deprecated function is @@ -231,9 +231,9 @@ The `--throw-deprecation` command-line flag and `process.throwDeprecation` property take precedence over `--trace-deprecation` and `process.traceDeprecation`. -### `util.format(format[, ...args])` +### `util.format(format[, ...args])` - + * `format` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) A `printf`-like format string. @@ -245,7 +245,7 @@ corresponding argument. Supported specifiers are: * `%s`: `String` will be used to convert all values except `BigInt`, `Object` and `-0`. `BigInt` values will be represented with an `n` and Objects that have no user defined `toString` function are inspected using `util.inspect()` - with options `{ depth: 0, colors: false, compact: 3 }`. + with options ````{ depth: 0, colors: false, compact: 3 }````. * `%d`: `Number` will be used to convert all values except `BigInt` and `Symbol`. * `%i`: `parseInt(value, 10)` is used for all values except `BigInt` and @@ -255,7 +255,7 @@ corresponding argument. Supported specifiers are: circular references. * `%o`: `Object`. A string representation of an object with generic JavaScript object formatting. Similar to `util.inspect()` with options - `{ showHidden: true, showProxy: true }`. This will show the full object + ````{ showHidden: true, showProxy: true }````. This will show the full object including non-enumerable properties and proxies. * `%O`: `Object`. A string representation of an object with generic JavaScript object formatting. Similar to `util.inspect()` without options. This will show @@ -303,9 +303,9 @@ util.format('%% %s'); Some input values can have a significant performance overhead that can block the event loop. Use this function with care and never in a hot code path. -### `util.formatWithOptions(inspectOptions, format[, ...args])` +### `util.formatWithOptions(inspectOptions, format[, ...args])` - + * `inspectOptions` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) * `format` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) @@ -320,9 +320,9 @@ util.formatWithOptions({ colors: true }, 'See object %O', { foo: 42 }); // when printed to a terminal. ``` -### `util.getSystemErrorName(err)` +### `util.getSystemErrorName(err)` - + * `err` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) * Returns: [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) @@ -338,9 +338,9 @@ fs.access('file/that/does/not/exist', (err) => { }); ``` -### `util.getSystemErrorMap()` +### `util.getSystemErrorMap()` - + * Returns: [`Map`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map) @@ -356,11 +356,11 @@ fs.access('file/that/does/not/exist', (err) => { }); ``` -### `util.inherits(constructor, superConstructor)` +### `util.inherits(constructor, superConstructor)` - + - + * `constructor` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) * `superConstructor` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) @@ -398,7 +398,7 @@ console.log(stream instanceof EventEmitter); // true console.log(MyStream.super_ === EventEmitter); // true stream.on('data', (data) => { - console.log(`Received data: "$data"`); + console.log(`Received data: "${data}"`); }); stream.write('It works!'); // Received data: "It works!" ``` @@ -417,16 +417,16 @@ class MyStream extends EventEmitter { const stream = new MyStream(); stream.on('data', (data) => { - console.log(`Received data: "$data"`); + console.log(`Received data: "${data}"`); }); stream.write('With ES6'); ``` -### `util.inspect(object[, options])` +### `util.inspect(object[, options])` -### `util.inspect(object[, showHidden[, depth[, colors]]])` +### `util.inspect(object[, showHidden[, depth[, colors]]])` - + * `object` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) Any JavaScript primitive or `Object`. * `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) @@ -644,7 +644,7 @@ be truncated. #### Customizing `util.inspect` colors - + Color output (if enabled) of `util.inspect` is customizable globally via the `util.inspect.styles` and `util.inspect.colors` properties. @@ -735,9 +735,9 @@ ignored, if not supported. #### Custom inspection functions on objects - + - + Objects may also define their own [`[util.inspect.custom](depth, opts, inspect)`][util.inspect.custom] function, @@ -764,8 +764,8 @@ class Box { // Five space padding because that's the size of "Box< ". const padding = ' '.repeat(5); const inner = inspect(this.value, newOptions) - .replace(/\n/g, `\n$padding`); - return `${options.stylize('Box', 'special')}< $inner >`; + .replace(/\n/g, `\n${padding}`); + return `${options.stylize('Box', 'special')}< ${inner} >`; } } @@ -791,9 +791,9 @@ util.inspect(obj); // Returns: "{ bar: 'baz' }" ``` -#### `util.inspect.custom` +#### `util.inspect.custom` - + * [`symbol`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Symbol_type) that can be used to declare custom inspect functions. @@ -830,9 +830,9 @@ console.log(password); See [Custom inspection functions on Objects][] for more details. -#### `util.inspect.defaultOptions` +#### `util.inspect.defaultOptions` - + The `defaultOptions` value allows customization of the default options used by `util.inspect`. This is useful for functions like `console.log` or @@ -849,9 +849,9 @@ util.inspect.defaultOptions.maxArrayLength = null; console.log(arr); // logs the full array ``` -### `util.isDeepStrictEqual(val1, val2)` +### `util.isDeepStrictEqual(val1, val2)` - + * `val1` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) * `val2` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) @@ -863,11 +863,11 @@ Otherwise, returns `false`. See [`assert.deepStrictEqual()`][] for more information about deep strict equality. -### `util.parseArgs([config])` +### `util.parseArgs([config])` - + - + * `config` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) Used to provide arguments for parsing and to configure the parser. `config` supports the following properties: @@ -897,7 +897,7 @@ equality. * `values` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) A mapping of parsed option names with their [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) or [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) values. * `positionals` string\[] Positional arguments. - * `tokens` {Object\[] | undefined} See [parseArgs tokens](#parseargs-tokens) + * `tokens` [`undefined`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type) See [parseArgs tokens](#parseargs-tokens) section. Only returned if `config` includes `tokens: true`. Provides a higher level API for command-line argument parsing than interacting @@ -947,7 +947,7 @@ console.log(values, positionals); `util.parseArgs` is experimental and behavior may change. Join the conversation in [pkgjs/parseargs][] to contribute to the design. -#### `parseArgs` `tokens` +#### `parseArgs` `tokens` Detailed parse information is available for adding custom behaviours by specifying `tokens: true` in the configuration. @@ -960,9 +960,9 @@ The returned tokens have properties describing: * option tokens * `name` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) Long name of option. * `rawName` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) How option used in args, like `-f` of `--foo`. - * `value` {string | undefined} Option value specified in args. + * `value` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`undefined`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type) Option value specified in args. Undefined for boolean options. - * `inlineValue` {boolean | undefined} Whether option value specified inline, + * `inlineValue` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) | [`undefined`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type) Whether option value specified inline, like `--foo=bar`. * positional tokens * `value` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The value of the positional argument in args (i.e. `args[index]`). @@ -1055,9 +1055,9 @@ $ node negate.js --no-logfile --logfile=test.log --color --no-color { logfile: 'test.log', color: false } ``` -### `util.promisify(original)` +### `util.promisify(original)` - + * `original` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) * Returns: [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) @@ -1088,7 +1088,7 @@ const stat = util.promisify(fs.stat); async function callStat() { const stats = await stat('.'); - console.log(`This directory is owned by $stats.uid`); + console.log(`This directory is owned by ${stats.uid}`); } ``` @@ -1167,9 +1167,9 @@ doSomething[util.promisify.custom] = (foo) => { If `promisify.custom` is defined but is not a function, `promisify()` will throw an error. -#### `util.promisify.custom` +#### `util.promisify.custom` - + * [`symbol`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Symbol_type) that can be used to declare custom promisified variants of functions, see [Custom promisified functions][]. @@ -1191,9 +1191,9 @@ doSomething[kCustomPromisifiedSymbol] = (foo) => { }; ``` -### `util.stripVTControlCharacters(str)` +### `util.stripVTControlCharacters(str)` - + * `str` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) * Returns: [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) @@ -1205,9 +1205,9 @@ console.log(util.stripVTControlCharacters('\u001B[4mvalue\u001B[0m')); // Prints "value" ``` -### `util.TextDecoder` +### `util.TextDecoder` - + An implementation of the [WHATWG Encoding Standard][] `TextDecoder` API. @@ -1283,9 +1283,9 @@ Different Node.js build configurations support different sets of encodings. The `'iso-8859-16'` encoding listed in the [WHATWG Encoding Standard][] is not supported. -#### `new TextDecoder([encoding[, options]])` +#### `new TextDecoder([encoding[, options]])` - + * `encoding` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) Identifies the `encoding` that this `TextDecoder` instance supports. **Default:** `'utf-8'`. @@ -1303,7 +1303,7 @@ supported encodings or an alias. The `TextDecoder` class is also available on the global object. -#### `textDecoder.decode([input[, options]])` +#### `textDecoder.decode([input[, options]])` * `input` [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) An `ArrayBuffer`, `DataView`, or `TypedArray` instance containing the encoded data. @@ -1319,29 +1319,29 @@ internally and emitted after the next call to `textDecoder.decode()`. If `textDecoder.fatal` is `true`, decoding errors that occur will result in a `TypeError` being thrown. -#### `textDecoder.encoding` +#### `textDecoder.encoding` * [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The encoding supported by the `TextDecoder` instance. -#### `textDecoder.fatal` +#### `textDecoder.fatal` * [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) The value will be `true` if decoding errors result in a `TypeError` being thrown. -#### `textDecoder.ignoreBOM` +#### `textDecoder.ignoreBOM` * [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) The value will be `true` if the decoding result will include the byte order mark. -### `util.TextEncoder` +### `util.TextEncoder` - + An implementation of the [WHATWG Encoding Standard][] `TextEncoder` API. All instances of `TextEncoder` only support UTF-8 encoding. @@ -1353,18 +1353,18 @@ const uint8array = encoder.encode('this is some data'); The `TextEncoder` class is also available on the global object. -#### `textEncoder.encode([input])` +#### `textEncoder.encode([input])` * `input` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The text to encode. **Default:** an empty string. -* Returns: {Uint8Array} +* Returns: [`Uint8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array) UTF-8 encodes the `input` string and returns a `Uint8Array` containing the encoded bytes. -#### `textEncoder.encodeInto(src, dest)` +#### `textEncoder.encodeInto(src, dest)` * `src` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The text to encode. -* `dest` {Uint8Array} The array to hold the encode result. +* `dest` [`Uint8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array) The array to hold the encode result. * Returns: [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) * `read` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The read Unicode code units of src. * `written` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The written UTF-8 bytes of dest. @@ -1379,15 +1379,15 @@ const dest = new Uint8Array(10); const { read, written } = encoder.encodeInto(src, dest); ``` -#### `textEncoder.encoding` +#### `textEncoder.encoding` * [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The encoding supported by the `TextEncoder` instance. Always set to `'utf-8'`. -### `util.toUSVString(string)` +### `util.toUSVString(string)` - + * `string` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) @@ -1395,9 +1395,9 @@ Returns the `string` after replacing any surrogate code points (or equivalently, any unpaired surrogate code units) with the Unicode "replacement character" U+FFFD. -### `util.types` +### `util.types` - + `util.types` provides type checks for different kinds of built-in objects. Unlike `instanceof` or `Object.prototype.toString.call(value)`, these checks do @@ -1410,9 +1410,9 @@ useful for addon developers who prefer to do type checking in JavaScript. The API is accessible via `require('node:util').types` or `require('node:util/types')`. -#### `util.types.isAnyArrayBuffer(value)` +#### `util.types.isAnyArrayBuffer(value)` - + * `value` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) * Returns: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) @@ -1428,9 +1428,9 @@ util.types.isAnyArrayBuffer(new ArrayBuffer()); // Returns true util.types.isAnyArrayBuffer(new SharedArrayBuffer()); // Returns true ``` -#### `util.types.isArrayBufferView(value)` +#### `util.types.isArrayBufferView(value)` - + * `value` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) * Returns: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) @@ -1446,9 +1446,9 @@ util.types.isArrayBufferView(new DataView(new ArrayBuffer(16))); // true util.types.isArrayBufferView(new ArrayBuffer()); // false ``` -#### `util.types.isArgumentsObject(value)` +#### `util.types.isArgumentsObject(value)` - + * `value` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) * Returns: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) @@ -1463,9 +1463,9 @@ function foo() { } ``` -#### `util.types.isArrayBuffer(value)` +#### `util.types.isArrayBuffer(value)` - + * `value` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) * Returns: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) @@ -1479,9 +1479,9 @@ util.types.isArrayBuffer(new ArrayBuffer()); // Returns true util.types.isArrayBuffer(new SharedArrayBuffer()); // Returns false ``` -#### `util.types.isAsyncFunction(value)` +#### `util.types.isAsyncFunction(value)` - + * `value` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) * Returns: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) @@ -1496,9 +1496,9 @@ util.types.isAsyncFunction(function foo() {}); // Returns false util.types.isAsyncFunction(async function foo() {}); // Returns true ``` -#### `util.types.isBigInt64Array(value)` +#### `util.types.isBigInt64Array(value)` - + * `value` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) * Returns: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) @@ -1510,9 +1510,9 @@ util.types.isBigInt64Array(new BigInt64Array()); // Returns true util.types.isBigInt64Array(new BigUint64Array()); // Returns false ``` -#### `util.types.isBigUint64Array(value)` +#### `util.types.isBigUint64Array(value)` - + * `value` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) * Returns: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) @@ -1524,9 +1524,9 @@ util.types.isBigUint64Array(new BigInt64Array()); // Returns false util.types.isBigUint64Array(new BigUint64Array()); // Returns true ``` -#### `util.types.isBooleanObject(value)` +#### `util.types.isBooleanObject(value)` - + * `value` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) * Returns: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) @@ -1543,9 +1543,9 @@ util.types.isBooleanObject(Boolean(false)); // Returns false util.types.isBooleanObject(Boolean(true)); // Returns false ``` -#### `util.types.isBoxedPrimitive(value)` +#### `util.types.isBoxedPrimitive(value)` - + * `value` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) * Returns: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) @@ -1563,18 +1563,18 @@ util.types.isBoxedPrimitive(Object(Symbol('foo'))); // Returns true util.types.isBoxedPrimitive(Object(BigInt(5))); // Returns true ``` -#### `util.types.isCryptoKey(value)` +#### `util.types.isCryptoKey(value)` - + * `value` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) * Returns: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) Returns `true` if `value` is a [`CryptoKey`](/api/webcrypto#cryptokey), `false` otherwise. -#### `util.types.isDataView(value)` +#### `util.types.isDataView(value)` - + * `value` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) * Returns: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) @@ -1589,9 +1589,9 @@ util.types.isDataView(new Float64Array()); // Returns false See also [`ArrayBuffer.isView()`][]. -#### `util.types.isDate(value)` +#### `util.types.isDate(value)` - + * `value` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) * Returns: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) @@ -1602,9 +1602,9 @@ Returns `true` if the value is a built-in [`Date`][] instance. util.types.isDate(new Date()); // Returns true ``` -#### `util.types.isExternal(value)` +#### `util.types.isExternal(value)` - + * `value` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) * Returns: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) @@ -1646,9 +1646,9 @@ util.types.isExternal(new String('foo')); // returns false For further information on `napi_create_external`, refer to [`napi_create_external()`][]. -#### `util.types.isFloat32Array(value)` +#### `util.types.isFloat32Array(value)` - + * `value` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) * Returns: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) @@ -1661,9 +1661,9 @@ util.types.isFloat32Array(new Float32Array()); // Returns true util.types.isFloat32Array(new Float64Array()); // Returns false ``` -#### `util.types.isFloat64Array(value)` +#### `util.types.isFloat64Array(value)` - + * `value` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) * Returns: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) @@ -1676,9 +1676,9 @@ util.types.isFloat64Array(new Uint8Array()); // Returns false util.types.isFloat64Array(new Float64Array()); // Returns true ``` -#### `util.types.isGeneratorFunction(value)` +#### `util.types.isGeneratorFunction(value)` - + * `value` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) * Returns: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) @@ -1693,9 +1693,9 @@ util.types.isGeneratorFunction(function foo() {}); // Returns false util.types.isGeneratorFunction(function* foo() {}); // Returns true ``` -#### `util.types.isGeneratorObject(value)` +#### `util.types.isGeneratorObject(value)` - + * `value` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) * Returns: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) @@ -1712,9 +1712,9 @@ const generator = foo(); util.types.isGeneratorObject(generator); // Returns true ``` -#### `util.types.isInt8Array(value)` +#### `util.types.isInt8Array(value)` - + * `value` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) * Returns: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) @@ -1727,9 +1727,9 @@ util.types.isInt8Array(new Int8Array()); // Returns true util.types.isInt8Array(new Float64Array()); // Returns false ``` -#### `util.types.isInt16Array(value)` +#### `util.types.isInt16Array(value)` - + * `value` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) * Returns: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) @@ -1742,9 +1742,9 @@ util.types.isInt16Array(new Int16Array()); // Returns true util.types.isInt16Array(new Float64Array()); // Returns false ``` -#### `util.types.isInt32Array(value)` +#### `util.types.isInt32Array(value)` - + * `value` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) * Returns: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) @@ -1757,18 +1757,18 @@ util.types.isInt32Array(new Int32Array()); // Returns true util.types.isInt32Array(new Float64Array()); // Returns false ``` -#### `util.types.isKeyObject(value)` +#### `util.types.isKeyObject(value)` - + * `value` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) * Returns: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) Returns `true` if `value` is a [`KeyObject`](/api/crypto#keyobject), `false` otherwise. -#### `util.types.isMap(value)` +#### `util.types.isMap(value)` - + * `value` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) * Returns: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) @@ -1779,9 +1779,9 @@ Returns `true` if the value is a built-in [`Map`][] instance. util.types.isMap(new Map()); // Returns true ``` -#### `util.types.isMapIterator(value)` +#### `util.types.isMapIterator(value)` - + * `value` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) * Returns: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) @@ -1797,9 +1797,9 @@ util.types.isMapIterator(map.entries()); // Returns true util.types.isMapIterator(map[Symbol.iterator]()); // Returns true ``` -#### `util.types.isModuleNamespaceObject(value)` +#### `util.types.isModuleNamespaceObject(value)` - + * `value` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) * Returns: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) @@ -1814,9 +1814,9 @@ import * as ns from './a.js'; util.types.isModuleNamespaceObject(ns); // Returns true ``` -#### `util.types.isNativeError(value)` +#### `util.types.isNativeError(value)` - + * `value` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) * Returns: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) @@ -1829,9 +1829,9 @@ util.types.isNativeError(new TypeError()); // Returns true util.types.isNativeError(new RangeError()); // Returns true ``` -#### `util.types.isNumberObject(value)` +#### `util.types.isNumberObject(value)` - + * `value` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) * Returns: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) @@ -1844,9 +1844,9 @@ util.types.isNumberObject(0); // Returns false util.types.isNumberObject(new Number(0)); // Returns true ``` -#### `util.types.isPromise(value)` +#### `util.types.isPromise(value)` - + * `value` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) * Returns: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) @@ -1857,9 +1857,9 @@ Returns `true` if the value is a built-in [`Promise`][]. util.types.isPromise(Promise.resolve(42)); // Returns true ``` -#### `util.types.isProxy(value)` +#### `util.types.isProxy(value)` - + * `value` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) * Returns: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) @@ -1873,9 +1873,9 @@ util.types.isProxy(target); // Returns false util.types.isProxy(proxy); // Returns true ``` -#### `util.types.isRegExp(value)` +#### `util.types.isRegExp(value)` - + * `value` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) * Returns: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) @@ -1887,9 +1887,9 @@ util.types.isRegExp(/abc/); // Returns true util.types.isRegExp(new RegExp('abc')); // Returns true ``` -#### `util.types.isSet(value)` +#### `util.types.isSet(value)` - + * `value` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) * Returns: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) @@ -1900,9 +1900,9 @@ Returns `true` if the value is a built-in [`Set`][] instance. util.types.isSet(new Set()); // Returns true ``` -#### `util.types.isSetIterator(value)` +#### `util.types.isSetIterator(value)` - + * `value` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) * Returns: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) @@ -1918,9 +1918,9 @@ util.types.isSetIterator(set.entries()); // Returns true util.types.isSetIterator(set[Symbol.iterator]()); // Returns true ``` -#### `util.types.isSharedArrayBuffer(value)` +#### `util.types.isSharedArrayBuffer(value)` - + * `value` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) * Returns: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) @@ -1934,9 +1934,9 @@ util.types.isSharedArrayBuffer(new ArrayBuffer()); // Returns false util.types.isSharedArrayBuffer(new SharedArrayBuffer()); // Returns true ``` -#### `util.types.isStringObject(value)` +#### `util.types.isStringObject(value)` - + * `value` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) * Returns: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) @@ -1949,9 +1949,9 @@ util.types.isStringObject('foo'); // Returns false util.types.isStringObject(new String('foo')); // Returns true ``` -#### `util.types.isSymbolObject(value)` +#### `util.types.isSymbolObject(value)` - + * `value` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) * Returns: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) @@ -1965,9 +1965,9 @@ util.types.isSymbolObject(symbol); // Returns false util.types.isSymbolObject(Object(symbol)); // Returns true ``` -#### `util.types.isTypedArray(value)` +#### `util.types.isTypedArray(value)` - + * `value` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) * Returns: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) @@ -1982,9 +1982,9 @@ util.types.isTypedArray(new Float64Array()); // Returns true See also [`ArrayBuffer.isView()`][]. -#### `util.types.isUint8Array(value)` +#### `util.types.isUint8Array(value)` - + * `value` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) * Returns: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) @@ -1997,9 +1997,9 @@ util.types.isUint8Array(new Uint8Array()); // Returns true util.types.isUint8Array(new Float64Array()); // Returns false ``` -#### `util.types.isUint8ClampedArray(value)` +#### `util.types.isUint8ClampedArray(value)` - + * `value` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) * Returns: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) @@ -2012,9 +2012,9 @@ util.types.isUint8ClampedArray(new Uint8ClampedArray()); // Returns true util.types.isUint8ClampedArray(new Float64Array()); // Returns false ``` -#### `util.types.isUint16Array(value)` +#### `util.types.isUint16Array(value)` - + * `value` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) * Returns: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) @@ -2027,9 +2027,9 @@ util.types.isUint16Array(new Uint16Array()); // Returns true util.types.isUint16Array(new Float64Array()); // Returns false ``` -#### `util.types.isUint32Array(value)` +#### `util.types.isUint32Array(value)` - + * `value` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) * Returns: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) @@ -2042,9 +2042,9 @@ util.types.isUint32Array(new Uint32Array()); // Returns true util.types.isUint32Array(new Float64Array()); // Returns false ``` -#### `util.types.isWeakMap(value)` +#### `util.types.isWeakMap(value)` - + * `value` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) * Returns: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) @@ -2055,9 +2055,9 @@ Returns `true` if the value is a built-in [`WeakMap`][] instance. util.types.isWeakMap(new WeakMap()); // Returns true ``` -#### `util.types.isWeakSet(value)` +#### `util.types.isWeakSet(value)` - + * `value` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) * Returns: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) @@ -2068,11 +2068,11 @@ Returns `true` if the value is a built-in [`WeakSet`][] instance. util.types.isWeakSet(new WeakSet()); // Returns true ``` -#### `util.types.isWebAssemblyCompiledModule(value)` +#### `util.types.isWebAssemblyCompiledModule(value)` - + - + * `value` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) * Returns: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) @@ -2089,11 +2089,11 @@ util.types.isWebAssemblyCompiledModule(module); // Returns true The following APIs are deprecated and should no longer be used. Existing applications and modules should be updated to find alternative approaches. -#### `util._extend(target, source)` +#### `util._extend(target, source)` - + - + * `target` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) * `source` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) @@ -2104,11 +2104,11 @@ Node.js modules. The community found and used it anyway. It is deprecated and should not be used in new code. JavaScript comes with very similar built-in functionality through [`Object.assign()`][]. -#### `util.isArray(object)` +#### `util.isArray(object)` - + - + * `object` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) * Returns: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) @@ -2128,11 +2128,11 @@ util.isArray({}); // Returns: false ``` -#### `util.isBoolean(object)` +#### `util.isBoolean(object)` - + - + * `object` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) * Returns: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) @@ -2150,11 +2150,11 @@ util.isBoolean(false); // Returns: true ``` -#### `util.isBuffer(object)` +#### `util.isBuffer(object)` - + - + * `object` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) * Returns: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) @@ -2172,11 +2172,11 @@ util.isBuffer(Buffer.from('hello world')); // Returns: true ``` -#### `util.isDate(object)` +#### `util.isDate(object)` - + - + * `object` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) * Returns: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) @@ -2194,11 +2194,11 @@ util.isDate({}); // Returns: false ``` -#### `util.isError(object)` +#### `util.isError(object)` - + - + * `object` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) * Returns: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) @@ -2232,11 +2232,11 @@ util.isError(obj); // Returns: true ``` -#### `util.isFunction(object)` +#### `util.isFunction(object)` - + - + * `object` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) * Returns: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) @@ -2258,11 +2258,11 @@ util.isFunction(Bar); // Returns: true ``` -#### `util.isNull(object)` +#### `util.isNull(object)` - + - + * `object` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) * Returns: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) @@ -2281,11 +2281,11 @@ util.isNull(null); // Returns: true ``` -#### `util.isNullOrUndefined(object)` +#### `util.isNullOrUndefined(object)` - + - `value === undefined || value === null` instead."}}} /> + * `object` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) * Returns: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) @@ -2304,11 +2304,11 @@ util.isNullOrUndefined(null); // Returns: true ``` -#### `util.isNumber(object)` +#### `util.isNumber(object)` - + - + * `object` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) * Returns: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) @@ -2328,11 +2328,11 @@ util.isNumber(NaN); // Returns: true ``` -#### `util.isObject(object)` +#### `util.isObject(object)` - + - Use `value !== null && typeof value === 'object'` instead."}}} /> + * `object` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) * Returns: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) @@ -2354,11 +2354,11 @@ util.isObject(() => {}); // Returns: false ``` -#### `util.isPrimitive(object)` +#### `util.isPrimitive(object)` - + - `(typeof value !== 'object' && typeof value !== 'function') || value === null`\n> instead."}}} /> + instead."}}} /> * `object` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) * Returns: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) @@ -2389,11 +2389,11 @@ util.isPrimitive(new Date()); // Returns: false ``` -#### `util.isRegExp(object)` +#### `util.isRegExp(object)` - + - + * `object` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) * Returns: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) @@ -2411,11 +2411,11 @@ util.isRegExp({}); // Returns: false ``` -#### `util.isString(object)` +#### `util.isString(object)` - + - + * `object` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) * Returns: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) @@ -2435,11 +2435,11 @@ util.isString(5); // Returns: false ``` -#### `util.isSymbol(object)` +#### `util.isSymbol(object)` - + - + * `object` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) * Returns: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) @@ -2457,11 +2457,11 @@ util.isSymbol(Symbol('foo')); // Returns: true ``` -#### `util.isUndefined(object)` +#### `util.isUndefined(object)` - + - + * `object` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) * Returns: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) @@ -2480,11 +2480,11 @@ util.isUndefined(null); // Returns: false ``` -#### `util.log(string)` +#### `util.log(string)` - + - + * `string` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) diff --git a/content/api/v18/v8.en.md b/content/api/v18/v8.en.md index 1f3033f189..b068901eb1 100644 --- a/content/api/v18/v8.en.md +++ b/content/api/v18/v8.en.md @@ -2,13 +2,13 @@ title: 'v8' displayTitle: 'V8' category: 'api' -editPage: 'https://github.com/nodejs/node/blob/v18.8.0/doc/api/v8.md' +editPage: 'https://github.com/nodejs/node/blob/v18.9.0/doc/api/v8.md' version: 'v18' --- - + - + The `node:v8` module exposes APIs that are specific to the version of [V8][] built into the Node.js binary. It can be accessed using: @@ -17,9 +17,9 @@ built into the Node.js binary. It can be accessed using: const v8 = require('node:v8'); ``` -### `v8.cachedDataVersionTag()` +### `v8.cachedDataVersionTag()` - + * Returns: [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) @@ -37,9 +37,9 @@ v8.setFlagsFromString('--allow_natives_syntax'); console.log(v8.cachedDataVersionTag()); // 183726201 ``` -### `v8.getHeapCodeStatistics()` +### `v8.getHeapCodeStatistics()` - + * Returns: [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) @@ -63,9 +63,9 @@ following properties: } ``` -### `v8.getHeapSnapshot()` +### `v8.getHeapSnapshot()` - + * Returns: [`stream.Readable`](/api/stream#streamreadable) A Readable Stream containing the V8 heap snapshot @@ -89,9 +89,9 @@ const stream = v8.getHeapSnapshot(); stream.pipe(process.stdout); ``` -### `v8.getHeapSpaceStatistics()` +### `v8.getHeapSpaceStatistics()` - + * Returns: Object\[] @@ -149,9 +149,9 @@ The value returned is an array of objects containing the following properties: ] ``` -### `v8.getHeapStatistics()` +### `v8.getHeapStatistics()` - + * Returns: [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) @@ -216,9 +216,9 @@ buffers and external strings. } ``` -### `v8.setFlagsFromString(flags)` +### `v8.setFlagsFromString(flags)` - + * `flags` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) @@ -239,18 +239,18 @@ v8.setFlagsFromString('--trace_gc'); setTimeout(() => { v8.setFlagsFromString('--notrace_gc'); }, 60e3); ``` -### `v8.stopCoverage()` +### `v8.stopCoverage()` - + The `v8.stopCoverage()` method allows the user to stop the coverage collection started by [`NODE_V8_COVERAGE`][], so that V8 can release the execution count records and optimize code. This can be used in conjunction with [`v8.takeCoverage()`][] if the user wants to collect the coverage on demand. -### `v8.takeCoverage()` +### `v8.takeCoverage()` - + The `v8.takeCoverage()` method allows the user to write the coverage started by [`NODE_V8_COVERAGE`][] to disk on demand. This method can be invoked multiple @@ -261,15 +261,15 @@ by [`NODE_V8_COVERAGE`][]. When the process is about to exit, one last coverage will still be written to disk unless [`v8.stopCoverage()`][] is invoked before the process exits. -### `v8.writeHeapSnapshot([filename])` +### `v8.writeHeapSnapshot([filename])` - + * `filename` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The file path where the V8 heap snapshot is to be saved. If not specified, a file name with the pattern - `'Heap-$yyyymmdd-$hhmmss-$pid-${thread_id}.heapsnapshot'` will be + `'Heap-$yyyymmdd-$hhmmss-$pid-$```{thread_id}```.heapsnapshot'` will be generated, where `pid` will be the PID of the Node.js process, - `{thread_id}` will be `0` when `writeHeapSnapshot()` is called from + ````{thread_id}```` will be `0` when `writeHeapSnapshot()` is called from the main Node.js thread or the id of a worker thread. * Returns: [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The filename where the snapshot was saved. @@ -301,7 +301,7 @@ if (isMainThread) { const worker = new Worker(__filename); worker.once('message', (filename) => { - console.log(`worker heapdump: $filename`); + console.log(`worker heapdump: ${filename}`); // Now get a heapdump for the main thread. console.log(`main thread heapdump: ${writeHeapSnapshot()}`); }); @@ -327,9 +327,9 @@ that is compatible with the [HTML structured clone algorithm][]. The format is backward-compatible (i.e. safe to store to disk). Equal JavaScript values may result in different serialized output. -#### `v8.serialize(value)` +#### `v8.serialize(value)` - + * `value` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) * Returns: [`Buffer`](/api/buffer#buffer) @@ -340,28 +340,28 @@ Uses a [`DefaultSerializer`][] to serialize `value` into a buffer. serialize a huge object which requires buffer larger than [`buffer.constants.MAX_LENGTH`][]. -#### `v8.deserialize(buffer)` +#### `v8.deserialize(buffer)` - + * `buffer` [`Buffer`](/api/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) A buffer returned by [`serialize()`][]. Uses a [`DefaultDeserializer`][] with default options to read a JS value from a buffer. -#### `v8.Serializer` +#### `v8.Serializer` - + -##### `new Serializer()` +##### `new Serializer()` Creates a new `Serializer` object. -##### `serializer.writeHeader()` +##### `serializer.writeHeader()` Writes out a header, which includes the serialization format version. -##### `serializer.writeValue(value)` +##### `serializer.writeValue(value)` * `value` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) @@ -370,7 +370,7 @@ internal buffer. This throws an error if `value` cannot be serialized. -##### `serializer.releaseBuffer()` +##### `serializer.releaseBuffer()` * Returns: [`Buffer`](/api/buffer#buffer) @@ -378,7 +378,7 @@ Returns the stored internal buffer. This serializer should not be used once the buffer is released. Calling this method results in undefined behavior if a previous write has failed. -##### `serializer.transferArrayBuffer(id, arrayBuffer)` +##### `serializer.transferArrayBuffer(id, arrayBuffer)` * `id` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) A 32-bit unsigned integer. * `arrayBuffer` [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) An `ArrayBuffer` instance. @@ -387,14 +387,14 @@ Marks an `ArrayBuffer` as having its contents transferred out of band. Pass the corresponding `ArrayBuffer` in the deserializing context to [`deserializer.transferArrayBuffer()`][]. -##### `serializer.writeUint32(value)` +##### `serializer.writeUint32(value)` * `value` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Write a raw 32-bit unsigned integer. For use inside of a custom [`serializer._writeHostObject()`][]. -##### `serializer.writeUint64(hi, lo)` +##### `serializer.writeUint64(hi, lo)` * `hi` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) * `lo` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) @@ -402,14 +402,14 @@ For use inside of a custom [`serializer._writeHostObject()`][]. Write a raw 64-bit unsigned integer, split into high and low 32-bit parts. For use inside of a custom [`serializer._writeHostObject()`][]. -##### `serializer.writeDouble(value)` +##### `serializer.writeDouble(value)` * `value` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Write a JS `number` value. For use inside of a custom [`serializer._writeHostObject()`][]. -##### `serializer.writeRawBytes(buffer)` +##### `serializer.writeRawBytes(buffer)` * `buffer` [`Buffer`](/api/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) @@ -417,7 +417,7 @@ Write raw bytes into the serializer's internal buffer. The deserializer will require a way to compute the length of the buffer. For use inside of a custom [`serializer._writeHostObject()`][]. -##### `serializer._writeHostObject(object)` +##### `serializer._writeHostObject(object)` * `object` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) @@ -428,7 +428,7 @@ exception should be thrown. This method is not present on the `Serializer` class itself but can be provided by subclasses. -##### `serializer._getDataCloneError(message)` +##### `serializer._getDataCloneError(message)` * `message` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) @@ -438,7 +438,7 @@ object can not be cloned. This method defaults to the [`Error`][] constructor and can be overridden on subclasses. -##### `serializer._getSharedArrayBufferId(sharedArrayBuffer)` +##### `serializer._getSharedArrayBufferId(sharedArrayBuffer)` * `sharedArrayBuffer` [`SharedArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer) @@ -453,35 +453,35 @@ If the object cannot be serialized, an exception should be thrown. This method is not present on the `Serializer` class itself but can be provided by subclasses. -##### `serializer._setTreatArrayBufferViewsAsHostObjects(flag)` +##### `serializer._setTreatArrayBufferViewsAsHostObjects(flag)` * `flag` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) **Default:** `false` Indicate whether to treat `TypedArray` and `DataView` objects as host objects, i.e. pass them to [`serializer._writeHostObject()`][]. -#### `v8.Deserializer` +#### `v8.Deserializer` - + -##### `new Deserializer(buffer)` +##### `new Deserializer(buffer)` * `buffer` [`Buffer`](/api/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) A buffer returned by [`serializer.releaseBuffer()`][]. Creates a new `Deserializer` object. -##### `deserializer.readHeader()` +##### `deserializer.readHeader()` Reads and validates a header (including the format version). May, for example, reject an invalid or unsupported wire format. In that case, an `Error` is thrown. -##### `deserializer.readValue()` +##### `deserializer.readValue()` Deserializes a JavaScript value from the buffer and returns it. -##### `deserializer.transferArrayBuffer(id, arrayBuffer)` +##### `deserializer.transferArrayBuffer(id, arrayBuffer)` * `id` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) A 32-bit unsigned integer. * `arrayBuffer` [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) | [`SharedArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer) An `ArrayBuffer` instance. @@ -491,7 +491,7 @@ Pass the corresponding `ArrayBuffer` in the serializing context to [`serializer.transferArrayBuffer()`][] (or return the `id` from [`serializer._getSharedArrayBufferId()`][] in the case of `SharedArrayBuffer`s). -##### `deserializer.getWireFormatVersion()` +##### `deserializer.getWireFormatVersion()` * Returns: [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) @@ -499,14 +499,14 @@ Reads the underlying wire format version. Likely mostly to be useful to legacy code reading old wire format versions. May not be called before `.readHeader()`. -##### `deserializer.readUint32()` +##### `deserializer.readUint32()` * Returns: [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Read a raw 32-bit unsigned integer and return it. For use inside of a custom [`deserializer._readHostObject()`][]. -##### `deserializer.readUint64()` +##### `deserializer.readUint64()` * Returns: integer\[] @@ -514,14 +514,14 @@ Read a raw 64-bit unsigned integer and return it as an array `[hi, lo]` with two 32-bit unsigned integer entries. For use inside of a custom [`deserializer._readHostObject()`][]. -##### `deserializer.readDouble()` +##### `deserializer.readDouble()` * Returns: [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Read a JS `number` value. For use inside of a custom [`deserializer._readHostObject()`][]. -##### `deserializer.readRawBytes(length)` +##### `deserializer.readRawBytes(length)` * `length` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) * Returns: [`Buffer`](/api/buffer#buffer) @@ -531,7 +531,7 @@ must correspond to the length of the buffer that was passed to [`serializer.writeRawBytes()`][]. For use inside of a custom [`deserializer._readHostObject()`][]. -##### `deserializer._readHostObject()` +##### `deserializer._readHostObject()` This method is called to read some kind of host object, i.e. an object that is created by native C++ bindings. If it is not possible to deserialize the data, @@ -540,17 +540,17 @@ a suitable exception should be thrown. This method is not present on the `Deserializer` class itself but can be provided by subclasses. -#### `v8.DefaultSerializer` +#### `v8.DefaultSerializer` - + A subclass of [`Serializer`][] that serializes `TypedArray` (in particular [`Buffer`][]) and `DataView` objects as host objects, and only stores the part of their underlying `ArrayBuffer`s that they are referring to. -#### `v8.DefaultDeserializer` +#### `v8.DefaultDeserializer` - + A subclass of [`Deserializer`][] corresponding to the format written by [`DefaultSerializer`][]. @@ -617,9 +617,9 @@ stopWatchingAfters(); stopHookSet(); ``` -#### `promiseHooks.onInit(init)` +#### `promiseHooks.onInit(init)` - + * `init` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) The [`init` callback][] to call when a promise is created. * Returns: [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) Call to stop the hook. @@ -639,9 +639,9 @@ const { promiseHooks } = require('node:v8'); const stop = promiseHooks.onInit((promise, parent) => {}); ``` -#### `promiseHooks.onSettled(settled)` +#### `promiseHooks.onSettled(settled)` - + * `settled` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) The [`settled` callback][] to call when a promise is resolved or rejected. @@ -662,9 +662,9 @@ const { promiseHooks } = require('node:v8'); const stop = promiseHooks.onSettled((promise) => {}); ``` -#### `promiseHooks.onBefore(before)` +#### `promiseHooks.onBefore(before)` - + * `before` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) The [`before` callback][] to call before a promise continuation executes. @@ -685,9 +685,9 @@ const { promiseHooks } = require('node:v8'); const stop = promiseHooks.onBefore((promise) => {}); ``` -#### `promiseHooks.onAfter(after)` +#### `promiseHooks.onAfter(after)` - + * `after` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) The [`after` callback][] to call after a promise continuation executes. @@ -708,9 +708,9 @@ const { promiseHooks } = require('node:v8'); const stop = promiseHooks.onAfter((promise) => {}); ``` -#### `promiseHooks.createHook(callbacks)` +#### `promiseHooks.createHook(callbacks)` - + * `callbacks` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) The [Hook Callbacks][] to register * `init` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) The [`init` callback][]. @@ -771,7 +771,7 @@ While this API is used to feed promise events into [`async_hooks`][], the ordering between the two is undefined. Both APIs are multi-tenant and therefore could produce events in any order relative to each other. -##### `init(promise, parent)` +##### `init(promise, parent)` * `promise` [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) The promise being created. * `parent` [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) The promise continued from, if applicable. @@ -780,7 +780,7 @@ Called when a promise is constructed. This _does not_ mean that corresponding `before`/`after` events will occur, only that the possibility exists. This will happen if a promise is created without ever getting a continuation. -##### `before(promise)` +##### `before(promise)` * `promise` [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) @@ -792,7 +792,7 @@ will typically be called 0 times if no continuation was ever made for the promise. The `before` callback may be called many times in the case where many continuations have been made from the same promise. -##### `after(promise)` +##### `after(promise)` * `promise` [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) @@ -800,7 +800,7 @@ Called immediately after a promise continuation executes. This may be after a `then()`, `catch()`, or `finally()` handler or before an `await` after another `await`. -##### `settled(promise)` +##### `settled(promise)` * `promise` [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) @@ -809,9 +809,9 @@ occur synchronously in the case of `Promise.resolve()` or `Promise.reject()`. ### Startup Snapshot API - + - + The `v8.startupSnapshot` interface can be used to add serialization and deserialization hooks for custom startup snapshots. Currently the startup @@ -876,9 +876,9 @@ Currently the API is only available to a Node.js instance launched from the default snapshot, that is, the application deserialized from a user-land snapshot cannot use these APIs again. -#### `v8.startupSnapshot.addSerializeCallback(callback[, data])` +#### `v8.startupSnapshot.addSerializeCallback(callback[, data])` - + * `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) Callback to be invoked before serialization. * `data` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) Optional data that will be passed to the `callback` when it @@ -889,9 +889,9 @@ get serialized into a snapshot and exit. This can be used to release resources that should not or cannot be serialized or to convert user data into a form more suitable for serialization. -#### `v8.startupSnapshot.addDeserializeCallback(callback[, data])` +#### `v8.startupSnapshot.addDeserializeCallback(callback[, data])` - + * `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) Callback to be invoked after the snapshot is deserialized. @@ -904,9 +904,9 @@ serialized into the snapshot, they can be used to re-initialize the state of the application or to re-acquire resources that the application needs when the application is restarted from the snapshot. -#### `v8.startupSnapshot.setDeserializeMainFunction(callback[, data])` +#### `v8.startupSnapshot.setDeserializeMainFunction(callback[, data])` - + * `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) Callback to be invoked as the entry point after the snapshot is deserialized. @@ -920,9 +920,9 @@ entry point script to start up and will simply invoke the callback along with the deserialized data (if provided), otherwise an entry point script still needs to be provided to the deserialized application. -#### `v8.startupSnapshot.isBuildingSnapshot()` +#### `v8.startupSnapshot.isBuildingSnapshot()` - + * Returns: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) diff --git a/content/api/v18/vm.en.md b/content/api/v18/vm.en.md index 252f211f9c..16c2eeef66 100644 --- a/content/api/v18/vm.en.md +++ b/content/api/v18/vm.en.md @@ -2,17 +2,17 @@ title: 'vm' displayTitle: 'VM (executing JavaScript)' category: 'api' -editPage: 'https://github.com/nodejs/node/blob/v18.8.0/doc/api/vm.md' +editPage: 'https://github.com/nodejs/node/blob/v18.9.0/doc/api/vm.md' version: 'v18' --- - + - + - + - + The `node:vm` module enables compiling and running code within V8 Virtual Machine contexts. @@ -50,16 +50,16 @@ console.log(context.y); // 17 console.log(x); // 1; y is not defined. ``` -### `vm.Script` +### `vm.Script` - + Instances of the `vm.Script` class contain precompiled scripts that can be executed in specific contexts. -#### `new vm.Script(code[, options])` +#### `new vm.Script(code[, options])` - + * `code` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The JavaScript code to compile. * `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) @@ -91,7 +91,7 @@ executed in specific contexts. * `importAssertions` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) The `"assert"` value passed to the [`optionsExpression`][] optional parameter, or an empty object if no value was provided. - * Returns: {Module Namespace Object|vm.Module} Returning a `vm.Module` is + * Returns: [`Module Namespace Object`](https://tc39.github.io/ecma262/#sec-module-namespace-exotic-objects) | [`vm.Module`](/api/vm#vmmodule) Returning a `vm.Module` is recommended in order to take advantage of error tracking, and to avoid issues with namespaces that contain `then` function exports. @@ -101,9 +101,9 @@ Creating a new `vm.Script` object compiles `code` but does not run it. The compiled `vm.Script` can be run later multiple times. The `code` is not bound to any global object; rather, it is bound before each run, just for that run. -#### `script.createCachedData()` +#### `script.createCachedData()` - + * Returns: [`Buffer`](/api/buffer#buffer) @@ -127,9 +127,9 @@ script.runInThisContext(); const cacheWithX = script.createCachedData(); ``` -#### `script.runInContext(contextifiedObject[, options])` +#### `script.runInContext(contextifiedObject[, options])` - + * `contextifiedObject` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) A [contextified][] object as returned by the `vm.createContext()` method. @@ -178,9 +178,9 @@ Using the `timeout` or `breakOnSigint` options will result in new event loops and corresponding threads being started, which have a non-zero performance overhead. -#### `script.runInNewContext([contextObject[, options]])` +#### `script.runInNewContext([contextObject[, options]])` - + * `contextObject` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) An object that will be [contextified][]. If `undefined`, a new object will be created. @@ -239,9 +239,9 @@ console.log(contexts); // Prints: [{ globalVar: 'set' }, { globalVar: 'set' }, { globalVar: 'set' }] ``` -#### `script.runInThisContext([options])` +#### `script.runInThisContext([options])` - + * `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) * `displayErrors` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) When `true`, if an [`Error`][] occurs @@ -280,11 +280,11 @@ console.log(globalVar); // 1000 ``` -### `vm.Module` +### `vm.Module` - + - + This feature is only available with the `--experimental-vm-modules` command flag enabled. @@ -365,7 +365,7 @@ async function linker(specifier, referencingModule) { // Using `contextifiedObject` instead of `referencingModule.context` // here would work as well. } - throw new Error(`Unable to resolve dependency: $specifier`); + throw new Error(`Unable to resolve dependency: ${specifier}`); } await bar.link(linker); @@ -437,7 +437,7 @@ const contextifiedObject = vm.createContext({ // Using `contextifiedObject` instead of `referencingModule.context` // here would work as well. } - throw new Error(`Unable to resolve dependency: $specifier`); + throw new Error(`Unable to resolve dependency: ${specifier}`); } await bar.link(linker); @@ -451,7 +451,7 @@ const contextifiedObject = vm.createContext({ })(); ``` -#### `module.dependencySpecifiers` +#### `module.dependencySpecifiers` * string\[] @@ -461,7 +461,7 @@ to disallow any changes to it. Corresponds to the `[[RequestedModules]]` field of [Cyclic Module Record][]s in the ECMAScript specification. -#### `module.error` +#### `module.error` * [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) @@ -475,7 +475,7 @@ exception due to possible ambiguity with `throw undefined;`. Corresponds to the `[[EvaluationError]]` field of [Cyclic Module Record][]s in the ECMAScript specification. -#### `module.evaluate([options])` +#### `module.evaluate([options])` * `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) * `timeout` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Specifies the number of milliseconds to evaluate @@ -502,13 +502,13 @@ This method cannot be called while the module is being evaluated Corresponds to the [Evaluate() concrete method][] field of [Cyclic Module Record][]s in the ECMAScript specification. -#### `module.identifier` +#### `module.identifier` * [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The identifier of the current module, as set in the constructor. -#### `module.link(linker)` +#### `module.link(linker)` * `linker` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) * `specifier` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The specifier of the requested module: @@ -523,7 +523,7 @@ The identifier of the current module, as set in the constructor. * `assert` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) The data from the assertion: ```js - import foo from 'foo' assert { name: 'value' }; + import foo from 'foo' assert ```{ name: 'value' }```; // ^^^^^^^^^^^^^^^^^ the assertion ``` Per ECMA-262, hosts are expected to ignore assertions that they do not @@ -567,7 +567,7 @@ specification. Corresponds to the [Link() concrete method][] field of [Cyclic Module Record][]s in the ECMAScript specification. -#### `module.namespace` +#### `module.namespace` * [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) @@ -577,7 +577,7 @@ The namespace object of the module. This is only available after linking Corresponds to the [GetModuleNamespace][] abstract operation in the ECMAScript specification. -#### `module.status` +#### `module.status` * [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) @@ -603,11 +603,11 @@ Other than `'errored'`, this status string corresponds to the specification's `'evaluated'` in the specification, but with `[[EvaluationError]]` set to a value that is not `undefined`. -### `vm.SourceTextModule` +### `vm.SourceTextModule` - + - + This feature is only available with the `--experimental-vm-modules` command flag enabled. @@ -617,9 +617,9 @@ flag enabled. The `vm.SourceTextModule` class provides the [Source Text Module Record][] as defined in the ECMAScript specification. -#### `new vm.SourceTextModule(code[, options])` +#### `new vm.SourceTextModule(code[, options])` - + * `code` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) JavaScript Module code to parse * `options` @@ -648,7 +648,7 @@ defined in the ECMAScript specification. * `importAssertions` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) The `"assert"` value passed to the [`optionsExpression`][] optional parameter, or an empty object if no value was provided. - * Returns: {Module Namespace Object|vm.Module} Returning a `vm.Module` is + * Returns: [`Module Namespace Object`](https://tc39.github.io/ecma262/#sec-module-namespace-exotic-objects) | [`vm.Module`](/api/vm#vmmodule) Returning a `vm.Module` is recommended in order to take advantage of error tracking, and to avoid issues with namespaces that contain `then` function exports. @@ -713,9 +713,9 @@ const contextifiedObject = vm.createContext({ secret: 42 }); })(); ``` -#### `sourceTextModule.createCachedData()` +#### `sourceTextModule.createCachedData()` - + * Returns: [`Buffer`](/api/buffer#buffer) @@ -734,11 +734,11 @@ const cachedData = module.createCachedData(); const module2 = new vm.SourceTextModule('const a = 1;', { cachedData }); ``` -### `vm.SyntheticModule` +### `vm.SyntheticModule` - + - + This feature is only available with the `--experimental-vm-modules` command flag enabled. @@ -762,9 +762,9 @@ const module = new vm.SyntheticModule(['default'], function() { // Use `module` in linking... ``` -#### `new vm.SyntheticModule(exportNames, evaluateCallback[, options])` +#### `new vm.SyntheticModule(exportNames, evaluateCallback[, options])` - + * `exportNames` string\[] Array of names that will be exported from the module. @@ -782,9 +782,9 @@ Objects assigned to the exports of this instance may allow importers of the module to access information outside the specified `context`. Use `vm.runInContext()` to create objects in a specific context. -#### `syntheticModule.setExport(name, value)` +#### `syntheticModule.setExport(name, value)` - + * `name` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) Name of the export to set. * `value` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) The value to set the export to. @@ -818,9 +818,9 @@ const vm = require('node:vm'); })(); ``` -### `vm.compileFunction(code[, params[, options]])` +### `vm.compileFunction(code[, params[, options]])` - + * `code` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The body of the function to compile. * `params` string\[] An array of strings containing all parameters for the @@ -852,7 +852,7 @@ const vm = require('node:vm'); * `importAssertions` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) The `"assert"` value passed to the [`optionsExpression`][] optional parameter, or an empty object if no value was provided. - * Returns: {Module Namespace Object|vm.Module} Returning a `vm.Module` is + * Returns: [`Module Namespace Object`](https://tc39.github.io/ecma262/#sec-module-namespace-exotic-objects) | [`vm.Module`](/api/vm#vmmodule) Returning a `vm.Module` is recommended in order to take advantage of error tracking, and to avoid issues with namespaces that contain `then` function exports. * Returns: [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) @@ -861,9 +861,9 @@ Compiles the given code into the provided context (if no context is supplied, the current context is used), and returns it wrapped inside a function with the given `params`. -### `vm.createContext([contextObject[, options]])` +### `vm.createContext([contextObject[, options]])` - + * `contextObject` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) * `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) @@ -925,9 +925,9 @@ context. The provided `name` and `origin` of the context are made visible through the Inspector API. -### `vm.isContext(object)` +### `vm.isContext(object)` - + * `object` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) * Returns: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) @@ -935,11 +935,11 @@ Inspector API. Returns `true` if the given `object` object has been [contextified][] using [`vm.createContext()`][]. -### `vm.measureMemory([options])` +### `vm.measureMemory([options])` - + - + Measure the memory known to V8 and used by all contexts known to the current V8 isolate, or the main context. @@ -1009,9 +1009,9 @@ vm.measureMemory({ mode: 'detailed', execution: 'eager' }) }); ``` -### `vm.runInContext(code, contextifiedObject[, options])` +### `vm.runInContext(code, contextifiedObject[, options])` - + * `code` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The JavaScript code to compile and run. * `contextifiedObject` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) The [contextified][] object that will be used @@ -1056,7 +1056,7 @@ vm.measureMemory({ mode: 'detailed', execution: 'eager' }) * `importAssertions` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) The `"assert"` value passed to the [`optionsExpression`][] optional parameter, or an empty object if no value was provided. - * Returns: {Module Namespace Object|vm.Module} Returning a `vm.Module` is + * Returns: [`Module Namespace Object`](https://tc39.github.io/ecma262/#sec-module-namespace-exotic-objects) | [`vm.Module`](/api/vm#vmmodule) Returning a `vm.Module` is recommended in order to take advantage of error tracking, and to avoid issues with namespaces that contain `then` function exports. * Returns: [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) the result of the very last statement executed in the script. @@ -1084,9 +1084,9 @@ console.log(contextObject); // Prints: { globalVar: 1024 } ``` -### `vm.runInNewContext(code[, contextObject[, options]])` +### `vm.runInNewContext(code[, contextObject[, options]])` - + * `code` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The JavaScript code to compile and run. * `contextObject` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) An object that will be [contextified][]. If @@ -1146,7 +1146,7 @@ console.log(contextObject); * `importAssertions` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) The `"assert"` value passed to the [`optionsExpression`][] optional parameter, or an empty object if no value was provided. - * Returns: {Module Namespace Object|vm.Module} Returning a `vm.Module` is + * Returns: [`Module Namespace Object`](https://tc39.github.io/ecma262/#sec-module-namespace-exotic-objects) | [`vm.Module`](/api/vm#vmmodule) Returning a `vm.Module` is recommended in order to take advantage of error tracking, and to avoid issues with namespaces that contain `then` function exports. * `microtaskMode` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) If set to `afterEvaluate`, microtasks (tasks @@ -1178,9 +1178,9 @@ console.log(contextObject); // Prints: { animal: 'cat', count: 3, name: 'kitty' } ``` -### `vm.runInThisContext(code[, options])` +### `vm.runInThisContext(code[, options])` - + * `code` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The JavaScript code to compile and run. * `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) @@ -1223,7 +1223,7 @@ console.log(contextObject); * `importAssertions` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) The `"assert"` value passed to the [`optionsExpression`][] optional parameter, or an empty object if no value was provided. - * Returns: {Module Namespace Object|vm.Module} Returning a `vm.Module` is + * Returns: [`Module Namespace Object`](https://tc39.github.io/ecma262/#sec-module-namespace-exotic-objects) | [`vm.Module`](/api/vm#vmmodule) Returning a `vm.Module` is recommended in order to take advantage of error tracking, and to avoid issues with namespaces that contain `then` function exports. * Returns: [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) the result of the very last statement executed in the script. @@ -1244,11 +1244,11 @@ const vm = require('node:vm'); let localVar = 'initial value'; const vmResult = vm.runInThisContext('localVar = "vm";'); -console.log(`vmResult: '$vmResult', localVar: '$localVar'`); +console.log(`vmResult: '${vmResult}', localVar: '${localVar}'`); // Prints: vmResult: 'vm', localVar: 'initial value' const evalResult = eval('localVar = "eval";'); -console.log(`evalResult: '$evalResult', localVar: '$localVar'`); +console.log(`evalResult: '${evalResult}', localVar: '${localVar}'`); // Prints: evalResult: 'eval', localVar: 'eval' ``` diff --git a/content/api/v18/wasi.en.md b/content/api/v18/wasi.en.md index 56d0c82087..699af1ab38 100644 --- a/content/api/v18/wasi.en.md +++ b/content/api/v18/wasi.en.md @@ -2,15 +2,15 @@ title: 'wasi' displayTitle: 'WebAssembly System Interface (WASI)' category: 'api' -editPage: 'https://github.com/nodejs/node/blob/v18.8.0/doc/api/wasi.md' +editPage: 'https://github.com/nodejs/node/blob/v18.9.0/doc/api/wasi.md' version: 'v18' --- - + - + - + The WASI API provides an implementation of the [WebAssembly System Interface][] specification. WASI gives sandboxed WebAssembly applications access to the @@ -112,9 +112,9 @@ $ wat2wasm demo.wat The `--experimental-wasi-unstable-preview1` CLI argument is needed for this example to run. -### `WASI` +### `WASI` - + The `WASI` class provides the WASI system call API and additional convenience methods for working with WASI-based applications. Each `WASI` instance @@ -122,9 +122,9 @@ represents a distinct sandbox environment. For security purposes, each `WASI` instance must have its command-line arguments, environment variables, and sandbox directory structure configured explicitly. -#### `new WASI([options])` +#### `new WASI([options])` - + * `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) * `args` [`Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array) An array of strings that the WebAssembly application will @@ -147,9 +147,9 @@ sandbox directory structure configured explicitly. * `stderr` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The file descriptor used as standard error in the WebAssembly application. **Default:** `2`. -#### `wasi.start(instance)` +#### `wasi.start(instance)` - + * `instance` [`WebAssembly.Instance`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/Instance) @@ -162,9 +162,9 @@ Attempt to begin execution of `instance` as a WASI command by invoking its If `start()` is called more than once, an exception is thrown. -#### `wasi.initialize(instance)` +#### `wasi.initialize(instance)` - + * `instance` [`WebAssembly.Instance`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/Instance) @@ -177,9 +177,9 @@ export, then an exception is thrown. If `initialize()` is called more than once, an exception is thrown. -#### `wasi.wasiImport` +#### `wasi.wasiImport` - + * [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) diff --git a/content/api/v18/webcrypto.en.md b/content/api/v18/webcrypto.en.md index bf3e052cbb..3c7e74af84 100644 --- a/content/api/v18/webcrypto.en.md +++ b/content/api/v18/webcrypto.en.md @@ -2,15 +2,15 @@ title: 'webcrypto' displayTitle: 'Web Crypto API' category: 'api' -editPage: 'https://github.com/nodejs/node/blob/v18.8.0/doc/api/webcrypto.md' +editPage: 'https://github.com/nodejs/node/blob/v18.9.0/doc/api/webcrypto.md' version: 'v18' --- - + - + - + Node.js provides an implementation of the standard [Web Crypto API][]. @@ -79,7 +79,7 @@ async function generateEcKey(namedCurve = 'P-521') { ##### Ed25519/Ed448/X25519/X448 key pairs - + ```js const { subtle } = require('node:crypto').webcrypto; @@ -340,25 +340,25 @@ implementation and the APIs supported for each: | `'SHA-384'` | | | | | | | | | | | | ✔ | | `'SHA-512'` | | | | | | | | | | | | ✔ | -### `Crypto` +### `Crypto` - + Calling `require('node:crypto').webcrypto` returns an instance of the `Crypto` class. `Crypto` is a singleton that provides access to the remainder of the crypto API. -#### `crypto.subtle` +#### `crypto.subtle` - + * Type: [`SubtleCrypto`](/api/webcrypto#subtlecrypto) Provides access to the `SubtleCrypto` API. -#### `crypto.getRandomValues(typedArray)` +#### `crypto.getRandomValues(typedArray)` - + * `typedArray` [`Buffer`](/api/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) * Returns: [`Buffer`](/api/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) @@ -371,22 +371,22 @@ i.e. `Float32Array` and `Float64Array` are not accepted. An error will be thrown if the given `typedArray` is larger than 65,536 bytes. -#### `crypto.randomUUID()` +#### `crypto.randomUUID()` - + * Returns: [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) Generates a random [RFC 4122][] version 4 UUID. The UUID is generated using a cryptographic pseudorandom number generator. -### `CryptoKey` +### `CryptoKey` - + -#### `cryptoKey.algorithm` +#### `cryptoKey.algorithm` - + @@ -399,9 +399,9 @@ additional algorithm-specific parameters. Read-only. -#### `cryptoKey.extractable` +#### `cryptoKey.extractable` - + * Type: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) @@ -410,18 +410,18 @@ When `true`, the [`CryptoKey`](/api/webcrypto#cryptokey) can be extracted using Read-only. -#### `cryptoKey.type` +#### `cryptoKey.type` - + * Type: [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) One of `'secret'`, `'private'`, or `'public'`. A string identifying whether the key is a symmetric (`'secret'`) or asymmetric (`'private'` or `'public'`) key. -#### `cryptoKey.usages` +#### `cryptoKey.usages` - + * Type: string\[] @@ -461,32 +461,32 @@ Valid key usages depend on the key algorithm (identified by | `'RSA-PSS'` | | | ✔ | ✔ | | | | | | `'RSASSA-PKCS1-v1_5'` | | | ✔ | ✔ | | | | | -### `CryptoKeyPair` +### `CryptoKeyPair` - + The `CryptoKeyPair` is a simple dictionary object with `publicKey` and `privateKey` properties, representing an asymmetric key pair. -#### `cryptoKeyPair.privateKey` +#### `cryptoKeyPair.privateKey` - + * Type: [`CryptoKey`](/api/webcrypto#cryptokey) A [`CryptoKey`](/api/webcrypto#cryptokey) whose `type` will be `'private'`. -#### `cryptoKeyPair.publicKey` +#### `cryptoKeyPair.publicKey` - + * Type: [`CryptoKey`](/api/webcrypto#cryptokey) A [`CryptoKey`](/api/webcrypto#cryptokey) whose `type` will be `'public'`. -### `SubtleCrypto` +### `SubtleCrypto` - + -#### `subtle.decrypt(algorithm, key, data)` +#### `subtle.decrypt(algorithm, key, data)` - + * `algorithm`: [`RsaOaepParams`](/api/webcrypto#rsaoaepparams) | [`AesCtrParams`](/api/webcrypto#aesctrparams) | [`AesCbcParams`](/api/webcrypto#aescbcparams) | [`AesGcmParams`](/api/webcrypto#aesgcmparams) * `key`: [`CryptoKey`](/api/webcrypto#cryptokey) @@ -505,13 +505,13 @@ The algorithms currently supported include: * `'AES-CBC'` * `'AES-GCM`' -#### `subtle.deriveBits(algorithm, baseKey, length)` +#### `subtle.deriveBits(algorithm, baseKey, length)` - + -* `algorithm`: {AlgorithmIdentifier|EcdhKeyDeriveParams|HkdfParams|Pbkdf2Params} +* `algorithm`: [`AlgorithmIdentifier`](/api/webcrypto#algorithmidentifier) | [`EcdhKeyDeriveParams`](/api/webcrypto#ecdhkeyderiveparams) | [`HkdfParams`](/api/webcrypto#hkdfparams) | [`Pbkdf2Params`](/api/webcrypto#pbkdf2params) * `baseKey`: [`CryptoKey`](/api/webcrypto#cryptokey) * `length`: [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) * Returns: [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) containing [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) @@ -530,13 +530,13 @@ The algorithms currently supported include: * `'HKDF'` * `'PBKDF2'` -#### `subtle.deriveKey(algorithm, baseKey, derivedKeyAlgorithm, extractable, keyUsages)` +#### `subtle.deriveKey(algorithm, baseKey, derivedKeyAlgorithm, extractable, keyUsages)` - + -* `algorithm`: {AlgorithmIdentifier|EcdhKeyDeriveParams|HkdfParams|Pbkdf2Params} +* `algorithm`: [`AlgorithmIdentifier`](/api/webcrypto#algorithmidentifier) | [`EcdhKeyDeriveParams`](/api/webcrypto#ecdhkeyderiveparams) | [`HkdfParams`](/api/webcrypto#hkdfparams) | [`Pbkdf2Params`](/api/webcrypto#pbkdf2params) * `baseKey`: [`CryptoKey`](/api/webcrypto#cryptokey) * `derivedKeyAlgorithm`: [`HmacKeyGenParams`](/api/webcrypto#hmackeygenparams) | [`AesKeyGenParams`](/api/webcrypto#aeskeygenparams) * `extractable`: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) @@ -560,9 +560,9 @@ The algorithms currently supported include: * `'HKDF'` * `'PBKDF2'` -#### `subtle.digest(algorithm, data)` +#### `subtle.digest(algorithm, data)` - + * `algorithm`: [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) * `data`: [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) | [`Buffer`](/api/buffer#buffer) @@ -582,9 +582,9 @@ If `algorithm` is provided as a [`string`](https://developer.mozilla.org/en-US/d If `algorithm` is provided as an [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object), it must have a `name` property whose value is one of the above. -#### `subtle.encrypt(algorithm, key, data)` +#### `subtle.encrypt(algorithm, key, data)` - + * `algorithm`: [`RsaOaepParams`](/api/webcrypto#rsaoaepparams) | [`AesCtrParams`](/api/webcrypto#aesctrparams) | [`AesCbcParams`](/api/webcrypto#aescbcparams) | [`AesGcmParams`](/api/webcrypto#aesgcmparams) * `key`: [`CryptoKey`](/api/webcrypto#cryptokey) @@ -602,9 +602,9 @@ The algorithms currently supported include: * `'AES-CBC'` * `'AES-GCM`' -#### `subtle.exportKey(format, key)` +#### `subtle.exportKey(format, key)` - + * `format`: [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) Must be one of `'raw'`, `'pkcs8'`, `'spki'`, or `'jwk'`. * `key`: [`CryptoKey`](/api/webcrypto#cryptokey) @@ -639,9 +639,9 @@ specification. | `'RSA-PSS'` | ✔ | ✔ | ✔ | | | `'RSASSA-PKCS1-v1_5'` | ✔ | ✔ | ✔ | | -#### `subtle.generateKey(algorithm, extractable, keyUsages)` +#### `subtle.generateKey(algorithm, extractable, keyUsages)` - + @@ -678,9 +678,9 @@ The [`CryptoKey`](/api/webcrypto#cryptokey) (secret key) generating algorithms s * `'AES-GCM'` * `'AES-KW'` -#### `subtle.importKey(format, keyData, algorithm, extractable, keyUsages)` +#### `subtle.importKey(format, keyData, algorithm, extractable, keyUsages)` - + * `format`: [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) Must be one of `'raw'`, `'pkcs8'`, `'spki'`, or `'jwk'`. * `keyData`: [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) | [`Buffer`](/api/buffer#buffer) | [`KeyObject`](/api/crypto#keyobject) @@ -723,13 +723,13 @@ The algorithms currently supported include: | `'RSA-PSS'` | ✔ | ✔ | ✔ | | | `'RSASSA-PKCS1-v1_5'` | ✔ | ✔ | ✔ | | -#### `subtle.sign(algorithm, key, data)` +#### `subtle.sign(algorithm, key, data)` - + -* `algorithm`: {AlgorithmIdentifier|RsaPssParams|EcdsaParams|Ed448Params} +* `algorithm`: [`AlgorithmIdentifier`](/api/webcrypto#algorithmidentifier) | [`RsaPssParams`](/api/webcrypto#rsapssparams) | [`EcdsaParams`](/api/webcrypto#ecdsaparams) | [`Ed448Params`](/api/webcrypto#ed448params) * `key`: [`CryptoKey`](/api/webcrypto#cryptokey) * `data`: [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) | [`Buffer`](/api/buffer#buffer) * Returns: [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) containing [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) @@ -750,9 +750,9 @@ The algorithms currently supported include: * `'Ed448'`[^1] * `'HMAC'` -#### `subtle.unwrapKey(format, wrappedKey, unwrappingKey, unwrapAlgo, unwrappedKeyAlgo, extractable, keyUsages)` +#### `subtle.unwrapKey(format, wrappedKey, unwrappingKey, unwrapAlgo, unwrappedKeyAlgo, extractable, keyUsages)` - + * `format`: [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) Must be one of `'raw'`, `'pkcs8'`, `'spki'`, or `'jwk'`. * `wrappedKey`: [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) | [`Buffer`](/api/buffer#buffer) @@ -799,13 +799,13 @@ The unwrapped key algorithms supported include: * `'AES-GCM'` * `'AES-KW'` -#### `subtle.verify(algorithm, key, signature, data)` +#### `subtle.verify(algorithm, key, signature, data)` - + -* `algorithm`: {AlgorithmIdentifier|RsaPssParams|EcdsaParams|Ed448Params} +* `algorithm`: [`AlgorithmIdentifier`](/api/webcrypto#algorithmidentifier) | [`RsaPssParams`](/api/webcrypto#rsapssparams) | [`EcdsaParams`](/api/webcrypto#ecdsaparams) | [`Ed448Params`](/api/webcrypto#ed448params) * `key`: [`CryptoKey`](/api/webcrypto#cryptokey) * `signature`: [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) | [`Buffer`](/api/buffer#buffer) * `data`: [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) | [`Buffer`](/api/buffer#buffer) @@ -827,9 +827,9 @@ The algorithms currently supported include: * `'Ed448'`[^1] * `'HMAC'` -#### `subtle.wrapKey(format, key, wrappingKey, wrapAlgo)` +#### `subtle.wrapKey(format, key, wrappingKey, wrapAlgo)` - + @@ -865,42 +865,42 @@ The algorithm parameter objects define the methods and parameters used by the various [`SubtleCrypto`](/api/webcrypto#subtlecrypto) methods. While described here as "classes", they are simple JavaScript dictionary objects. -#### `AlgorithmIdentifier` +#### `AlgorithmIdentifier` - + -##### `algorithmIdentifier.name` +##### `algorithmIdentifier.name` - + * Type: [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) -#### `AesCbcParams` +#### `AesCbcParams` - + -##### `aesCbcParams.iv` +##### `aesCbcParams.iv` - + * Type: [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) | [`Buffer`](/api/buffer#buffer) Provides the initialization vector. It must be exactly 16-bytes in length and should be unpredictable and cryptographically random. -##### `aesCbcParams.name` +##### `aesCbcParams.name` - + * Type: [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) Must be `'AES-CBC'`. -#### `AesCtrParams` +#### `AesCtrParams` - + -##### `aesCtrParams.counter` +##### `aesCtrParams.counter` - + * Type: [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) | [`Buffer`](/api/buffer#buffer) @@ -909,26 +909,26 @@ The initial value of the counter block. This must be exactly 16 bytes long. The `AES-CTR` method uses the rightmost `length` bits of the block as the counter and the remaining bits as the nonce. -##### `aesCtrParams.length` +##### `aesCtrParams.length` - + * Type: [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The number of bits in the `aesCtrParams.counter` that are to be used as the counter. -##### `aesCtrParams.name` +##### `aesCtrParams.name` - + * Type: [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) Must be `'AES-CTR'`. -#### `AesGcmParams` +#### `AesGcmParams` - + -##### `aesGcmParams.additionalData` +##### `aesGcmParams.additionalData` - + * Type: [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) | [`Buffer`](/api/buffer#buffer) | [`undefined`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type) @@ -936,9 +936,9 @@ With the AES-GCM method, the `additionalData` is extra input that is not encrypted but is included in the authentication of the data. The use of `additionalData` is optional. -##### `aesGcmParams.iv` +##### `aesGcmParams.iv` - + * Type: [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) | [`Buffer`](/api/buffer#buffer) @@ -951,53 +951,53 @@ Alternatively, the initialization vector may consist of at least 12 cryptographically random bytes. For more information on constructing initialization vectors for AES-GCM, refer to Section 8 of [NIST SP 800-38D][]. -##### `aesGcmParams.name` +##### `aesGcmParams.name` - + * Type: [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) Must be `'AES-GCM'`. -##### `aesGcmParams.tagLength` +##### `aesGcmParams.tagLength` - + * Type: [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The size in bits of the generated authentication tag. This values must be one of `32`, `64`, `96`, `104`, `112`, `120`, or `128`. **Default:** `128`. -#### `AesKeyGenParams` +#### `AesKeyGenParams` - + -##### `aesKeyGenParams.length` +##### `aesKeyGenParams.length` - + * Type: [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The length of the AES key to be generated. This must be either `128`, `192`, or `256`. -##### `aesKeyGenParams.name` +##### `aesKeyGenParams.name` - + * Type: [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) Must be one of `'AES-CBC'`, `'AES-CTR'`, `'AES-GCM'`, or `'AES-KW'` -#### `EcdhKeyDeriveParams` +#### `EcdhKeyDeriveParams` - + -##### `ecdhKeyDeriveParams.name` +##### `ecdhKeyDeriveParams.name` - + * Type: [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) Must be `'ECDH'`, `'X25519'`, or `'X448'`. -##### `ecdhKeyDeriveParams.public` +##### `ecdhKeyDeriveParams.public` - + * Type: [`CryptoKey`](/api/webcrypto#cryptokey) @@ -1006,13 +1006,13 @@ another parties public key -- using both to generate a common shared secret. The `ecdhKeyDeriveParams.public` property is set to the other parties public key. -#### `EcdsaParams` +#### `EcdsaParams` - + -##### `ecdsaParams.hash` +##### `ecdsaParams.hash` - + * Type: [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) @@ -1026,57 +1026,57 @@ If represented as a [`string`](https://developer.mozilla.org/en-US/docs/Web/Java If represented as an [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object), the object must have a `name` property whose value is one of the above listed values. -##### `ecdsaParams.name` +##### `ecdsaParams.name` - + * Type: [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) Must be `'ECDSA'`. -#### `EcKeyGenParams` +#### `EcKeyGenParams` - + -##### `ecKeyGenParams.name` +##### `ecKeyGenParams.name` - + * Type: [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) Must be one of `'ECDSA'` or `'ECDH'`. -##### `ecKeyGenParams.namedCurve` +##### `ecKeyGenParams.namedCurve` - + * Type: [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) Must be one of `'P-256'`, `'P-384'`, `'P-521'`. -#### `EcKeyImportParams` +#### `EcKeyImportParams` - + -##### `ecKeyImportParams.name` +##### `ecKeyImportParams.name` - + * Type: [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) Must be one of `'ECDSA'` or `'ECDH'`. -##### `ecKeyImportParams.namedCurve` +##### `ecKeyImportParams.namedCurve` - + * Type: [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) Must be one of `'P-256'`, `'P-384'`, `'P-521'`. -#### `Ed448Params` +#### `Ed448Params` - + -##### `ed448Params.name` +##### `ed448Params.name` - + * Type: [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) Must be `'Ed448'`. -##### `ed448Params.context` +##### `ed448Params.context` - + * Type: [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) | [`Buffer`](/api/buffer#buffer) | [`undefined`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type) @@ -1085,13 +1085,13 @@ the message. The Node.js Web Crypto API implementation only supports zero-length context which is equivalent to not providing context at all. -#### `HkdfParams` +#### `HkdfParams` - + -##### `hkdfParams.hash` +##### `hkdfParams.hash` - + * Type: [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) @@ -1105,24 +1105,24 @@ If represented as a [`string`](https://developer.mozilla.org/en-US/docs/Web/Java If represented as an [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object), the object must have a `name` property whose value is one of the above listed values. -##### `hkdfParams.info` +##### `hkdfParams.info` - + * Type: [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) | [`Buffer`](/api/buffer#buffer) Provides application-specific contextual input to the HKDF algorithm. This can be zero-length but must be provided. -##### `hkdfParams.name` +##### `hkdfParams.name` - + * Type: [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) Must be `'HKDF'`. -##### `hkdfParams.salt` +##### `hkdfParams.salt` - + * Type: [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) | [`Buffer`](/api/buffer#buffer) @@ -1131,13 +1131,13 @@ It should be random or pseudorandom and should be the same length as the output of the digest function (for instance, if using `'SHA-256'` as the digest, the salt should be 256-bits of random data). -#### `HmacImportParams` +#### `HmacImportParams` - + -##### `hmacImportParams.hash` +##### `hmacImportParams.hash` - + * Type: [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) @@ -1151,28 +1151,28 @@ If represented as a [`string`](https://developer.mozilla.org/en-US/docs/Web/Java If represented as an [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object), the object must have a `name` property whose value is one of the above listed values. -##### `hmacImportParams.length` +##### `hmacImportParams.length` - + * Type: [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The optional number of bits in the HMAC key. This is optional and should be omitted for most cases. -##### `hmacImportParams.name` +##### `hmacImportParams.name` - + * Type: [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) Must be `'HMAC'`. -#### `HmacKeyGenParams` +#### `HmacKeyGenParams` - + -##### `hmacKeyGenParams.hash` +##### `hmacKeyGenParams.hash` - + * Type: [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) @@ -1186,9 +1186,9 @@ If represented as a [`string`](https://developer.mozilla.org/en-US/docs/Web/Java If represented as an [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object), the object must have a `name` property whose value is one of the above listed values. -##### `hmacKeyGenParams.length` +##### `hmacKeyGenParams.length` - + * Type: [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) @@ -1196,19 +1196,19 @@ The number of bits to generate for the HMAC key. If omitted, the length will be determined by the hash algorithm used. This is optional and should be omitted for most cases. -##### `hmacKeyGenParams.name` +##### `hmacKeyGenParams.name` - + * Type: [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) Must be `'HMAC'`. -#### `Pbkdf2Params` +#### `Pbkdf2Params` - + -##### `pbkdb2Params.hash` +##### `pbkdb2Params.hash` - + * Type: [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) @@ -1222,35 +1222,35 @@ If represented as a [`string`](https://developer.mozilla.org/en-US/docs/Web/Java If represented as an [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object), the object must have a `name` property whose value is one of the above listed values. -##### `pbkdf2Params.iterations` +##### `pbkdf2Params.iterations` - + * Type: [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The number of iterations the PBKDF2 algorithm should make when deriving bits. -##### `pbkdf2Params.name` +##### `pbkdf2Params.name` - + * Type: [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) Must be `'PBKDF2'`. -##### `pbkdf2Params.salt` +##### `pbkdf2Params.salt` - + * Type: [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) | [`Buffer`](/api/buffer#buffer) Should be at least 16 random or pseudorandom bytes. -#### `RsaHashedImportParams` +#### `RsaHashedImportParams` - + -##### `rsaHashedImportParams.hash` +##### `rsaHashedImportParams.hash` - + * Type: [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) @@ -1264,20 +1264,20 @@ If represented as a [`string`](https://developer.mozilla.org/en-US/docs/Web/Java If represented as an [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object), the object must have a `name` property whose value is one of the above listed values. -##### `rsaHashedImportParams.name` +##### `rsaHashedImportParams.name` - + * Type: [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) Must be one of `'RSASSA-PKCS1-v1_5'`, `'RSA-PSS'`, or `'RSA-OAEP'`. -#### `RsaHashedKeyGenParams` +#### `RsaHashedKeyGenParams` - + -##### `rsaHashedKeyGenParams.hash` +##### `rsaHashedKeyGenParams.hash` - + * Type: [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) @@ -1291,41 +1291,41 @@ If represented as a [`string`](https://developer.mozilla.org/en-US/docs/Web/Java If represented as an [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object), the object must have a `name` property whose value is one of the above listed values. -##### `rsaHashedKeyGenParams.modulusLength` +##### `rsaHashedKeyGenParams.modulusLength` - + * Type: [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The length in bits of the RSA modulus. As a best practice, this should be at least `2048`. -##### `rsaHashedKeyGenParams.name` +##### `rsaHashedKeyGenParams.name` - + * Type: [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) Must be one of `'RSASSA-PKCS1-v1_5'`, `'RSA-PSS'`, or `'RSA-OAEP'`. -##### `rsaHashedKeyGenParams.publicExponent` +##### `rsaHashedKeyGenParams.publicExponent` - + -* Type: {Uint8Array} +* Type: [`Uint8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array) -The RSA public exponent. This must be a {Uint8Array} containing a big-endian, -unsigned integer that must fit within 32-bits. The {Uint8Array} may contain an +The RSA public exponent. This must be a [`Uint8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array) containing a big-endian, +unsigned integer that must fit within 32-bits. The [`Uint8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array) may contain an arbitrary number of leading zero-bits. The value must be a prime number. Unless there is reason to use a different value, use `new Uint8Array([1, 0, 1])` (65537) as the public exponent. -#### `RsaOaepParams` +#### `RsaOaepParams` - + ##### rsaOaepParams.label - + * Type: [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) | [`Buffer`](/api/buffer#buffer) @@ -1336,23 +1336,23 @@ The `rsaOaepParams.label` parameter is optional. ##### rsaOaepParams.name - + * Type: [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) must be `'RSA-OAEP'`. -#### `RsaPssParams` +#### `RsaPssParams` - + -##### `rsaPssParams.name` +##### `rsaPssParams.name` - + * Type: [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) Must be `'RSA-PSS'`. -##### `rsaPssParams.saltLength` +##### `rsaPssParams.saltLength` - + * Type: [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) diff --git a/content/api/v18/webstreams.en.md b/content/api/v18/webstreams.en.md index a73b07aacf..b0efd6ab50 100644 --- a/content/api/v18/webstreams.en.md +++ b/content/api/v18/webstreams.en.md @@ -2,15 +2,15 @@ title: 'webstreams' displayTitle: 'Web Streams API' category: 'api' -editPage: 'https://github.com/nodejs/node/blob/v18.8.0/doc/api/webstreams.md' +editPage: 'https://github.com/nodejs/node/blob/v18.9.0/doc/api/webstreams.md' version: 'v18' --- - + - + - + An implementation of the [WHATWG Streams Standard][]. @@ -89,13 +89,13 @@ const stream = new ReadableStream({ ### API -#### `ReadableStream` +#### `ReadableStream` - + -##### `new ReadableStream([underlyingSource [, strategy]])` +##### `new ReadableStream([underlyingSource [, strategy]])` - + @@ -127,9 +127,9 @@ const stream = new ReadableStream({ -##### `readableStream.locked` +##### `readableStream.locked` - + * Type: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) Set to `true` if there is an active reader for this [`ReadableStream`](/api/webstreams#readablestream). @@ -138,17 +138,17 @@ The `readableStream.locked` property is `false` by default, and is switched to `true` while there is an active reader consuming the stream's data. -##### `readableStream.cancel([reason])` +##### `readableStream.cancel([reason])` - + * `reason` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) * Returns: A promise fulfilled with `undefined` once cancelation has been completed. -##### `readableStream.getReader([options])` +##### `readableStream.getReader([options])` - + * `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) * `mode` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) `'byob'` or `undefined` @@ -176,9 +176,9 @@ reader.read().then(console.log); Causes the `readableStream.locked` to be `true`. -##### `readableStream.pipeThrough(transform[, options])` +##### `readableStream.pipeThrough(transform[, options])` - + * `transform` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) * `readable` [`ReadableStream`](/api/webstreams#readablestream) The `ReadableStream` to which @@ -257,9 +257,9 @@ const transformedStream = stream.pipeThrough(transform); })(); ``` -##### `readableStream.pipeTo(destination, options)` +##### `readableStream.pipeTo(destination, options)` - + * `destination` [`WritableStream`](/api/webstreams#writablestream) A [`WritableStream`](/api/webstreams#writablestream) to which this `ReadableStream`'s data will be written. @@ -277,9 +277,9 @@ const transformedStream = stream.pipeThrough(transform); Causes the `readableStream.locked` to be `true` while the pipe operation is active. -##### `readableStream.tee()` +##### `readableStream.tee()` - + * Returns: ReadableStream\[] @@ -289,9 +289,9 @@ same data. Causes the `readableStream.locked` to be `true`. -##### `readableStream.values([options])` +##### `readableStream.values([options])` - + * `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) * `preventCancel` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) When `true`, prevents the [`ReadableStream`](/api/webstreams#readablestream) @@ -356,9 +356,9 @@ port1.onmessage = ({ data }) => { port2.postMessage(stream, [stream]); ``` -#### `ReadableStreamDefaultReader` +#### `ReadableStreamDefaultReader` - + By default, calling `readableStream.getReader()` with no arguments will return an instance of `ReadableStreamDefaultReader`. The default @@ -366,18 +366,18 @@ reader treats the chunks of data passed through the stream as opaque values, which allows the [`ReadableStream`](/api/webstreams#readablestream) to work with generally any JavaScript value. -##### `new ReadableStreamDefaultReader(stream)` +##### `new ReadableStreamDefaultReader(stream)` - + * `stream` [`ReadableStream`](/api/webstreams#readablestream) Creates a new [`ReadableStreamDefaultReader`](/api/webstreams#readablestreamdefaultreader) that is locked to the given [`ReadableStream`](/api/webstreams#readablestream). -##### `readableStreamDefaultReader.cancel([reason])` +##### `readableStreamDefaultReader.cancel([reason])` - + * `reason` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) * Returns: A promise fulfilled with `undefined`. @@ -385,17 +385,17 @@ given [`ReadableStream`](/api/webstreams#readablestream). Cancels the [`ReadableStream`](/api/webstreams#readablestream) and returns a promise that is fulfilled when the underlying stream has been canceled. -##### `readableStreamDefaultReader.closed` +##### `readableStreamDefaultReader.closed` - + * Type: [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) Fulfilled with `undefined` when the associated [`ReadableStream`](/api/webstreams#readablestream) is closed or rejected if the stream errors or the reader's lock is released before the stream finishes closing. -##### `readableStreamDefaultReader.read()` +##### `readableStreamDefaultReader.read()` - + * Returns: A promise fulfilled with an object: * `value` [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) @@ -405,15 +405,15 @@ Requests the next chunk of data from the underlying [`ReadableStream`](/api/webs and returns a promise that is fulfilled with the data once it is available. -##### `readableStreamDefaultReader.releaseLock()` +##### `readableStreamDefaultReader.releaseLock()` - + Releases this reader's lock on the underlying [`ReadableStream`](/api/webstreams#readablestream). -#### `ReadableStreamBYOBReader` +#### `ReadableStreamBYOBReader` - + The `ReadableStreamBYOBReader` is an alternative consumer for byte-oriented [`ReadableStream`](/api/webstreams#readablestream)s (those that are created with @@ -482,18 +482,18 @@ const data = await read(stream); console.log(Buffer.from(data).toString()); ``` -##### `new ReadableStreamBYOBReader(stream)` +##### `new ReadableStreamBYOBReader(stream)` - + * `stream` [`ReadableStream`](/api/webstreams#readablestream) Creates a new `ReadableStreamBYOBReader` that is locked to the given [`ReadableStream`](/api/webstreams#readablestream). -##### `readableStreamBYOBReader.cancel([reason])` +##### `readableStreamBYOBReader.cancel([reason])` - + * `reason` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) * Returns: A promise fulfilled with `undefined`. @@ -501,17 +501,17 @@ given [`ReadableStream`](/api/webstreams#readablestream). Cancels the [`ReadableStream`](/api/webstreams#readablestream) and returns a promise that is fulfilled when the underlying stream has been canceled. -##### `readableStreamBYOBReader.closed` +##### `readableStreamBYOBReader.closed` - + * Type: [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) Fulfilled with `undefined` when the associated [`ReadableStream`](/api/webstreams#readablestream) is closed or rejected if the stream errors or the reader's lock is released before the stream finishes closing. -##### `readableStreamBYOBReader.read(view)` +##### `readableStreamBYOBReader.read(view)` - + * `view` [`Buffer`](/api/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) * Returns: A promise fulfilled with an object: @@ -533,100 +533,100 @@ the view's underlying `ArrayBuffer` is _detached_, invalidating all existing views that may exist on that `ArrayBuffer`. This can have disastrous consequences for your application. -##### `readableStreamBYOBReader.releaseLock()` +##### `readableStreamBYOBReader.releaseLock()` - + Releases this reader's lock on the underlying [`ReadableStream`](/api/webstreams#readablestream). -#### `ReadableStreamDefaultController` +#### `ReadableStreamDefaultController` - + Every [`ReadableStream`](/api/webstreams#readablestream) has a controller that is responsible for the internal state and management of the stream's queue. The `ReadableStreamDefaultController` is the default controller implementation for `ReadableStream`s that are not byte-oriented. -##### `readableStreamDefaultController.close()` +##### `readableStreamDefaultController.close()` - + Closes the [`ReadableStream`](/api/webstreams#readablestream) to which this controller is associated. -##### `readableStreamDefaultController.desiredSize` +##### `readableStreamDefaultController.desiredSize` - + * Type: [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Returns the amount of data remaining to fill the [`ReadableStream`](/api/webstreams#readablestream)'s queue. -##### `readableStreamDefaultController.enqueue(chunk)` +##### `readableStreamDefaultController.enqueue(chunk)` - + * `chunk` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) Appends a new chunk of data to the [`ReadableStream`](/api/webstreams#readablestream)'s queue. -##### `readableStreamDefaultController.error(error)` +##### `readableStreamDefaultController.error(error)` - + * `error` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) Signals an error that causes the [`ReadableStream`](/api/webstreams#readablestream) to error and close. -#### `ReadableByteStreamController` +#### `ReadableByteStreamController` - + Every [`ReadableStream`](/api/webstreams#readablestream) has a controller that is responsible for the internal state and management of the stream's queue. The `ReadableByteStreamController` is for byte-oriented `ReadableStream`s. -##### `readableByteStreamController.byobRequest` +##### `readableByteStreamController.byobRequest` - + * Type: [`ReadableStreamBYOBRequest`](/api/webstreams#readablestreambyobrequest) -##### `readableByteStreamController.close()` +##### `readableByteStreamController.close()` - + Closes the [`ReadableStream`](/api/webstreams#readablestream) to which this controller is associated. -##### `readableByteStreamController.desiredSize` +##### `readableByteStreamController.desiredSize` - + * Type: [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Returns the amount of data remaining to fill the [`ReadableStream`](/api/webstreams#readablestream)'s queue. -##### `readableByteStreamController.enqueue(chunk)` +##### `readableByteStreamController.enqueue(chunk)` - + * `chunk`: [`Buffer`](/api/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) Appends a new chunk of data to the [`ReadableStream`](/api/webstreams#readablestream)'s queue. -##### `readableByteStreamController.error(error)` +##### `readableByteStreamController.error(error)` - + * `error` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) Signals an error that causes the [`ReadableStream`](/api/webstreams#readablestream) to error and close. -#### `ReadableStreamBYOBRequest` +#### `ReadableStreamBYOBRequest` - + When using `ReadableByteStreamController` in byte-oriented streams, and when using the `ReadableStreamBYOBReader`, @@ -638,33 +638,33 @@ that has been provided for the read request to fill, and provides methods for signaling that the data has been provided. -##### `readableStreamBYOBRequest.respond(bytesWritten)` +##### `readableStreamBYOBRequest.respond(bytesWritten)` - + * `bytesWritten` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Signals that a `bytesWritten` number of bytes have been written to `readableStreamBYOBRequest.view`. -##### `readableStreamBYOBRequest.respondWithNewView(view)` +##### `readableStreamBYOBRequest.respondWithNewView(view)` - + * `view` [`Buffer`](/api/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) Signals that the request has been fulfilled with bytes written to a new `Buffer`, `TypedArray`, or `DataView`. -##### `readableStreamBYOBRequest.view` +##### `readableStreamBYOBRequest.view` - + * Type: [`Buffer`](/api/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) -#### `WritableStream` +#### `WritableStream` - + The `WritableStream` is a destination to which stream data is sent. @@ -682,9 +682,9 @@ const stream = new WritableStream({ await stream.getWriter().write('Hello World'); ``` -##### `new WritableStream([underlyingSink[, strategy]])` +##### `new WritableStream([underlyingSink[, strategy]])` - + * `underlyingSink` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) * `start` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) A user-defined function that is invoked immediately when @@ -713,9 +713,9 @@ await stream.getWriter().write('Hello World'); * `chunk` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) * Returns: [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) -##### `writableStream.abort([reason])` +##### `writableStream.abort([reason])` - + * `reason` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) * Returns: A promise fulfilled with `undefined`. @@ -723,26 +723,26 @@ await stream.getWriter().write('Hello World'); Abruptly terminates the `WritableStream`. All queued writes will be canceled with their associated promises rejected. -##### `writableStream.close()` +##### `writableStream.close()` - + * Returns: A promise fulfilled with `undefined`. Closes the `WritableStream` when no additional writes are expected. -##### `writableStream.getWriter()` +##### `writableStream.getWriter()` - + * Returns: [`WritableStreamDefaultWriter`](/api/webstreams#writablestreamdefaultwriter) Creates and creates a new writer instance that can be used to write data into the `WritableStream`. -##### `writableStream.locked` +##### `writableStream.locked` - + * Type: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) @@ -766,22 +766,22 @@ port1.onmessage = ({ data }) => { port2.postMessage(stream, [stream]); ``` -#### `WritableStreamDefaultWriter` +#### `WritableStreamDefaultWriter` - + -##### `new WritableStreamDefaultWriter(stream)` +##### `new WritableStreamDefaultWriter(stream)` - + * `stream` [`WritableStream`](/api/webstreams#writablestream) Creates a new `WritableStreamDefaultWriter` that is locked to the given `WritableStream`. -##### `writableStreamDefaultWriter.abort([reason])` +##### `writableStreamDefaultWriter.abort([reason])` - + * `reason` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) * Returns: A promise fulfilled with `undefined`. @@ -789,66 +789,66 @@ Creates a new `WritableStreamDefaultWriter` that is locked to the given Abruptly terminates the `WritableStream`. All queued writes will be canceled with their associated promises rejected. -##### `writableStreamDefaultWriter.close()` +##### `writableStreamDefaultWriter.close()` - + * Returns: A promise fulfilled with `undefined`. Closes the `WritableStream` when no additional writes are expected. -##### `writableStreamDefaultWriter.closed` +##### `writableStreamDefaultWriter.closed` - + * Type: [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) Fulfilled with `undefined` when the associated [`WritableStream`](/api/webstreams#writablestream) is closed or rejected if the stream errors or the writer's lock is released before the stream finishes closing. -##### `writableStreamDefaultWriter.desiredSize` +##### `writableStreamDefaultWriter.desiredSize` - + * Type: [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The amount of data required to fill the [`WritableStream`](/api/webstreams#writablestream)'s queue. -##### `writableStreamDefaultWriter.ready` +##### `writableStreamDefaultWriter.ready` - + * type: A promise that is fulfilled with `undefined` when the writer is ready to be used. -##### `writableStreamDefaultWriter.releaseLock()` +##### `writableStreamDefaultWriter.releaseLock()` - + Releases this writer's lock on the underlying [`ReadableStream`](/api/webstreams#readablestream). -##### `writableStreamDefaultWriter.write([chunk])` +##### `writableStreamDefaultWriter.write([chunk])` - + * `chunk`: [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) * Returns: A promise fulfilled with `undefined`. Appends a new chunk of data to the [`WritableStream`](/api/webstreams#writablestream)'s queue. -#### `WritableStreamDefaultController` +#### `WritableStreamDefaultController` - + The `WritableStreamDefaultController` manage's the [`WritableStream`](/api/webstreams#writablestream)'s internal state. -##### `writableStreamDefaultController.abortReason` +##### `writableStreamDefaultController.abortReason` * Type: [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) The `reason` value passed to `writableStream.abort()`. -##### `writableStreamDefaultController.error(error)` +##### `writableStreamDefaultController.error(error)` - + * `error` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) @@ -856,14 +856,14 @@ Called by user-code to signal that an error has occurred while processing the `WritableStream` data. When called, the [`WritableStream`](/api/webstreams#writablestream) will be aborted, with currently pending writes canceled. -##### `writableStreamDefaultController.signal` +##### `writableStreamDefaultController.signal` * Type: [`AbortSignal`](/api/globals#abortsignal) An `AbortSignal` that can be used to cancel pending write or close operations when a [`WritableStream`](/api/webstreams#writablestream) is aborted. -#### `TransformStream` +#### `TransformStream` - + A `TransformStream` consists of a [`ReadableStream`](/api/webstreams#readablestream) and a [`WritableStream`](/api/webstreams#writablestream) that are connected such that the data written to the `WritableStream` is received, @@ -887,9 +887,9 @@ await Promise.all([ ]); ``` -##### `new TransformStream([transformer[, writableStrategy[, readableStrategy]]])` +##### `new TransformStream([transformer[, writableStrategy[, readableStrategy]]])` - + * `transformer` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) * `start` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) A user-defined function that is invoked immediately when @@ -926,15 +926,15 @@ await Promise.all([ * `chunk` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) * Returns: [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) -##### `transformStream.readable` +##### `transformStream.readable` - + * Type: [`ReadableStream`](/api/webstreams#readablestream) -##### `transformStream.writable` +##### `transformStream.writable` - + * Type: [`WritableStream`](/api/webstreams#writablestream) @@ -955,32 +955,32 @@ port1.onmessage = ({ data }) => { port2.postMessage(stream, [stream]); ``` -#### `TransformStreamDefaultController` +#### `TransformStreamDefaultController` - + The `TransformStreamDefaultController` manages the internal state of the `TransformStream`. -##### `transformStreamDefaultController.desiredSize` +##### `transformStreamDefaultController.desiredSize` - + * Type: [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The amount of data required to fill the readable side's queue. -##### `transformStreamDefaultController.enqueue([chunk])` +##### `transformStreamDefaultController.enqueue([chunk])` - + * `chunk` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) Appends a chunk of data to the readable side's queue. -##### `transformStreamDefaultController.error([reason])` +##### `transformStreamDefaultController.error([reason])` - + * `reason` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) @@ -988,100 +988,100 @@ Signals to both the readable and writable side that an error has occurred while processing the transform data, causing both sides to be abruptly closed. -##### `transformStreamDefaultController.terminate()` +##### `transformStreamDefaultController.terminate()` - + Closes the readable side of the transport and causes the writable side to be abruptly closed with an error. -#### `ByteLengthQueuingStrategy` +#### `ByteLengthQueuingStrategy` - + -##### `new ByteLengthQueuingStrategy(options)` +##### `new ByteLengthQueuingStrategy(options)` - + * `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) * `highWaterMark` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) -##### `byteLengthQueuingStrategy.highWaterMark` +##### `byteLengthQueuingStrategy.highWaterMark` - + * Type: [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) -##### `byteLengthQueuingStrategy.size` +##### `byteLengthQueuingStrategy.size` - + * Type: [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) * `chunk` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) * Returns: [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) -#### `CountQueuingStrategy` +#### `CountQueuingStrategy` - + -##### `new CountQueuingStrategy(options)` +##### `new CountQueuingStrategy(options)` - + * `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) * `highWaterMark` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) -##### `countQueuingStrategy.highWaterMark` +##### `countQueuingStrategy.highWaterMark` - + * Type: [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) -##### `countQueuingStrategy.size` +##### `countQueuingStrategy.size` - + * Type: [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) * `chunk` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) * Returns: [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) -#### `TextEncoderStream` +#### `TextEncoderStream` - + -##### `new TextEncoderStream()` +##### `new TextEncoderStream()` - + Creates a new `TextEncoderStream` instance. -##### `textEncoderStream.encoding` +##### `textEncoderStream.encoding` - + * Type: [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The encoding supported by the `TextEncoderStream` instance. -##### `textEncoderStream.readable` +##### `textEncoderStream.readable` - + * Type: [`ReadableStream`](/api/webstreams#readablestream) -##### `textEncoderStream.writable` +##### `textEncoderStream.writable` - + * Type: [`WritableStream`](/api/webstreams#writablestream) -#### `TextDecoderStream` +#### `TextDecoderStream` - + -##### `new TextDecoderStream([encoding[, options]])` +##### `new TextDecoderStream([encoding[, options]])` - + * `encoding` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) Identifies the `encoding` that this `TextDecoder` instance supports. **Default:** `'utf-8'`. @@ -1094,91 +1094,91 @@ The encoding supported by the `TextEncoderStream` instance. Creates a new `TextDecoderStream` instance. -##### `textDecoderStream.encoding` +##### `textDecoderStream.encoding` - + * Type: [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The encoding supported by the `TextDecoderStream` instance. -##### `textDecoderStream.fatal` +##### `textDecoderStream.fatal` - + * Type: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) The value will be `true` if decoding errors result in a `TypeError` being thrown. -##### `textDecoderStream.ignoreBOM` +##### `textDecoderStream.ignoreBOM` - + * Type: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) The value will be `true` if the decoding result will include the byte order mark. -##### `textDecoderStream.readable` +##### `textDecoderStream.readable` - + * Type: [`ReadableStream`](/api/webstreams#readablestream) -##### `textDecoderStream.writable` +##### `textDecoderStream.writable` - + * Type: [`WritableStream`](/api/webstreams#writablestream) -#### `CompressionStream` +#### `CompressionStream` - + -##### `new CompressionStream(format)` +##### `new CompressionStream(format)` - + * `format` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) One of either `'deflate'` or `'gzip'`. -##### `compressionStream.readable` +##### `compressionStream.readable` - + * Type: [`ReadableStream`](/api/webstreams#readablestream) -##### `compressionStream.writable` +##### `compressionStream.writable` - + * Type: [`WritableStream`](/api/webstreams#writablestream) -#### `DecompressionStream` +#### `DecompressionStream` - + -##### `new DecompressionStream(format)` +##### `new DecompressionStream(format)` - + * `format` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) One of either `'deflate'` or `'gzip'`. -##### `decompressionStream.readable` +##### `decompressionStream.readable` - + * Type: [`ReadableStream`](/api/webstreams#readablestream) -##### `decompressionStream.writable` +##### `decompressionStream.writable` - + * Type: [`WritableStream`](/api/webstreams#writablestream) #### Utility Consumers - + The utility consumer functions provide common options for consuming streams. @@ -1205,41 +1205,41 @@ const { } = require('node:stream/consumers'); ``` -##### `streamConsumers.arrayBuffer(stream)` +##### `streamConsumers.arrayBuffer(stream)` - + * `stream` [`ReadableStream`](/api/webstreams#readablestream) | [`stream.Readable`](/api/stream#streamreadable) | [`AsyncIterator`](https://tc39.github.io/ecma262/#sec-asynciterator-interface) * Returns: [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) Fulfills with an `ArrayBuffer` containing the full contents of the stream. -##### `streamConsumers.blob(stream)` +##### `streamConsumers.blob(stream)` - + * `stream` [`ReadableStream`](/api/webstreams#readablestream) | [`stream.Readable`](/api/stream#streamreadable) | [`AsyncIterator`](https://tc39.github.io/ecma262/#sec-asynciterator-interface) * Returns: [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) Fulfills with a [`Blob`](/api/buffer#blob) containing the full contents of the stream. -##### `streamConsumers.buffer(stream)` +##### `streamConsumers.buffer(stream)` - + * `stream` [`ReadableStream`](/api/webstreams#readablestream) | [`stream.Readable`](/api/stream#streamreadable) | [`AsyncIterator`](https://tc39.github.io/ecma262/#sec-asynciterator-interface) * Returns: [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) Fulfills with a [`Buffer`](/api/buffer#buffer) containing the full contents of the stream. -##### `streamConsumers.json(stream)` +##### `streamConsumers.json(stream)` - + * `stream` [`ReadableStream`](/api/webstreams#readablestream) | [`stream.Readable`](/api/stream#streamreadable) | [`AsyncIterator`](https://tc39.github.io/ecma262/#sec-asynciterator-interface) * Returns: [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) Fulfills with the contents of the stream parsed as a UTF-8 encoded string that is then passed through `JSON.parse()`. -##### `streamConsumers.text(stream)` +##### `streamConsumers.text(stream)` - + * `stream` [`ReadableStream`](/api/webstreams#readablestream) | [`stream.Readable`](/api/stream#streamreadable) | [`AsyncIterator`](https://tc39.github.io/ecma262/#sec-asynciterator-interface) * Returns: [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) Fulfills with the contents of the stream parsed as a diff --git a/content/api/v18/worker_threads.en.md b/content/api/v18/worker_threads.en.md index 0202b2b5c5..c20da9f569 100644 --- a/content/api/v18/worker_threads.en.md +++ b/content/api/v18/worker_threads.en.md @@ -2,15 +2,15 @@ title: 'worker_threads' displayTitle: 'Worker threads' category: 'api' -editPage: 'https://github.com/nodejs/node/blob/v18.8.0/doc/api/worker_threads.md' +editPage: 'https://github.com/nodejs/node/blob/v18.9.0/doc/api/worker_threads.md' version: 'v18' --- - + - + - + The `node:worker_threads` module enables the use of threads that execute JavaScript in parallel. To access it: @@ -42,7 +42,7 @@ if (isMainThread) { worker.on('error', reject); worker.on('exit', (code) => { if (code !== 0) - reject(new Error(`Worker stopped with exit code $code`)); + reject(new Error(`Worker stopped with exit code ${code}`)); }); }); }; @@ -67,9 +67,9 @@ 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)` +### `worker.getEnvironmentData(key)` - + * `key` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) Any arbitrary, cloneable JavaScript value that can be used as a [`Map`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map) key. @@ -96,9 +96,9 @@ if (isMainThread) { } ``` -### `worker.isMainThread` +### `worker.isMainThread` - + * [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) @@ -116,9 +116,9 @@ if (isMainThread) { } ``` -### `worker.markAsUntransferable(object)` +### `worker.markAsUntransferable(object)` - + Mark an object as not transferable. If `object` occurs in the transfer list of a [`port.postMessage()`][] call, it is ignored. @@ -152,9 +152,9 @@ console.log(typedArray2); There is no equivalent to this API in browsers. -### `worker.moveMessagePortToContext(port, contextifiedSandbox)` +### `worker.moveMessagePortToContext(port, contextifiedSandbox)` - + * `port` [`MessagePort`](/api/worker_threads#messageport) The message port to transfer. @@ -176,9 +176,9 @@ However, the created `MessagePort` no longer inherits from [`EventTarget`][], and only [`port.onmessage()`][] can be used to receive events using it. -### `worker.parentPort` +### `worker.parentPort` - + * [`null`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type) | [`MessagePort`](/api/worker_threads#messageport) @@ -206,9 +206,9 @@ if (isMainThread) { } ``` -### `worker.receiveMessageOnPort(port)` +### `worker.receiveMessageOnPort(port)` - + * `port` [`MessagePort`](/api/worker_threads#messageport) | [`BroadcastChannel`](/api/worker_threads#broadcastchannel-extends-eventtarget) @@ -233,9 +233,9 @@ console.log(receiveMessageOnPort(port2)); When this function is used, no `'message'` event is emitted and the `onmessage` listener is not invoked. -### `worker.resourceLimits` +### `worker.resourceLimits` - + * [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) * `maxYoungGenerationSizeMb` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) @@ -249,9 +249,9 @@ this matches its values. If this is used in the main thread, its value is an empty object. -### `worker.SHARE_ENV` +### `worker.SHARE_ENV` - + * [`symbol`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Symbol_type) @@ -267,9 +267,9 @@ new Worker('process.env.SET_IN_WORKER = "foo"', { eval: true, env: SHARE_ENV }) }); ``` -### `worker.setEnvironmentData(key[, value])` +### `worker.setEnvironmentData(key[, value])` - + * `key` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) Any arbitrary, cloneable JavaScript value that can be used as a [`Map`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map) key. @@ -281,9 +281,9 @@ 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` +### `worker.threadId` - + * [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) @@ -291,9 +291,9 @@ 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` +### `worker.workerData` - + An arbitrary JavaScript value that contains a clone of the data passed to this thread's `Worker` constructor. @@ -311,9 +311,9 @@ if (isMainThread) { } ``` -### `BroadcastChannel extends EventTarget` +### `BroadcastChannel extends EventTarget` - + Instances of `BroadcastChannel` allow asynchronous one-to-many communication with all other `BroadcastChannel` instances bound to the same channel name. @@ -343,59 +343,59 @@ if (isMainThread) { } ``` -#### `new BroadcastChannel(name)` +#### `new BroadcastChannel(name)` - + * `name` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) The name of the channel to connect to. Any JavaScript value that can be converted to a string using `` `$name` `` is permitted. -#### `broadcastChannel.close()` +#### `broadcastChannel.close()` - + Closes the `BroadcastChannel` connection. -#### `broadcastChannel.onmessage` +#### `broadcastChannel.onmessage` - + * Type: [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) Invoked with a single `MessageEvent` argument when a message is received. -#### `broadcastChannel.onmessageerror` +#### `broadcastChannel.onmessageerror` - + * Type: [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) Invoked with a received message cannot be deserialized. -#### `broadcastChannel.postMessage(message)` +#### `broadcastChannel.postMessage(message)` - + * `message` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) Any cloneable JavaScript value. -#### `broadcastChannel.ref()` +#### `broadcastChannel.ref()` - + 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()` +#### `broadcastChannel.unref()` - + 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. -### `MessageChannel` +### `MessageChannel` - + Instances of the `worker.MessageChannel` class represent an asynchronous, two-way communications channel. @@ -412,9 +412,9 @@ port2.postMessage({ foo: 'bar' }); // Prints: received { foo: 'bar' } from the `port1.on('message')` listener ``` -### `MessagePort` +### `MessagePort` - + * Extends: [`EventTarget`](/api/events#eventtarget) @@ -425,9 +425,9 @@ structured data, memory regions and other `MessagePort`s between different This implementation matches [browser `MessagePort`][]s. -#### `'close'` +#### `'close'` - + The `'close'` event is emitted once either side of the channel has been disconnected. @@ -446,9 +446,9 @@ port1.postMessage('foobar'); port1.close(); ``` -#### `'message'` +#### `'message'` - + * `value` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) The transmitted value @@ -458,9 +458,9 @@ input of [`port.postMessage()`][]. Listeners on this event receive a clone of the `value` parameter as passed to `postMessage()` and no further arguments. -#### `'messageerror'` +#### `'messageerror'` - + * `error` [`Error`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error) An Error object @@ -472,9 +472,9 @@ 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()` +#### `port.close()` - + Disables further sending of messages on either side of the connection. This method can be called when no further communication will happen over this @@ -483,9 +483,9 @@ This method can be called when no further communication will happen over this The [`'close'` event][] is emitted on both `MessagePort` instances that are part of the channel. -#### `port.postMessage(value[, transferList])` +#### `port.postMessage(value[, transferList])` - + * `value` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) * `transferList` Object\[] @@ -510,7 +510,7 @@ In particular, the significant differences to `JSON` are: * [`MessagePort`](/api/worker_threads#messageport)s, * [`net.BlockList`](/api/net#netblocklist)s, * [`net.SocketAddress`](/api/net#netsocketaddress)es, - * {X509Certificate}s. + * [`X509Certificate`](/api/crypto#x509certificate)s. ```js const { MessageChannel } = require('node:worker_threads'); @@ -658,19 +658,19 @@ port2.postMessage(new URL('https://example.org')); // Prints: { } ``` -#### `port.hasRef()` +#### `port.hasRef()` - + - + * Returns: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) If true, the `MessagePort` object will keep the Node.js event loop active. -#### `port.ref()` +#### `port.ref()` - + 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 @@ -680,9 +680,9 @@ 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()` +#### `port.start()` - + Starts receiving messages on this `MessagePort`. When using this port as an event emitter, this is called automatically once `'message'` @@ -694,9 +694,9 @@ 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()` +#### `port.unref()` - + 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 @@ -706,9 +706,9 @@ 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. -### `Worker` +### `Worker` - + * Extends: [`EventEmitter`](/api/events#eventemitter) @@ -780,9 +780,9 @@ if (isMainThread) { } ``` -#### `new Worker(filename[, options])` +#### `new Worker(filename[, options])` - + * `filename` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`URL`](/api/url#the-whatwg-url-api) 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 @@ -832,31 +832,34 @@ if (isMainThread) { 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`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/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`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The maximum size of the main heap in MB. + * `resourceLimits` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/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`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) 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`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The maximum size of a heap space for - recently created objects. + recently created objects. If the command-line argument + [`--max-semi-space-size`][] is set, it overrides this setting. * `codeRangeSizeMb` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The size of a pre-allocated memory range used for generated code. * `stackSizeMb` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The default maximum stack size for the thread. Small values may lead to unusable Worker instances. **Default:** `4`. -#### `'error'` +#### `'error'` - + * `err` [`Error`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error) The `'error'` event is emitted if the worker thread throws an uncaught exception. In that case, the worker is terminated. -#### `'exit'` +#### `'exit'` - + * `exitCode` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) @@ -867,9 +870,9 @@ passed exit code. If the worker was terminated, the `exitCode` parameter is This is the final event emitted by any `Worker` instance. -#### `'message'` +#### `'message'` - + * `value` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) The transmitted value @@ -880,24 +883,24 @@ 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. -#### `'messageerror'` +#### `'messageerror'` - + * `error` [`Error`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error) An Error object The `'messageerror'` event is emitted when deserializing a message failed. -#### `'online'` +#### `'online'` - + The `'online'` event is emitted when the worker thread has started executing JavaScript code. -#### `worker.getHeapSnapshot()` +#### `worker.getHeapSnapshot()` - + * Returns: [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) A promise for a Readable Stream containing a V8 heap snapshot @@ -909,16 +912,16 @@ 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.performance` +#### `worker.performance` - + An object that can be used to query performance information from a worker instance. Similar to [`perf_hooks.performance`][]. -##### `performance.eventLoopUtilization([utilization1[, utilization2]])` +##### `performance.eventLoopUtilization([utilization1[, utilization2]])` - + * `utilization1` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) The result of a previous call to `eventLoopUtilization()`. @@ -966,9 +969,9 @@ 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])` +#### `worker.postMessage(value[, transferList])` - + * `value` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) * `transferList` Object\[] @@ -977,18 +980,18 @@ 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()` +#### `worker.ref()` - + 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` +#### `worker.resourceLimits` - + * [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) * `maxYoungGenerationSizeMb` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) @@ -1002,9 +1005,9 @@ this matches its values. If the worker has stopped, the return value is an empty object. -#### `worker.stderr` +#### `worker.stderr` - + * [`stream.Readable`](/api/stream#streamreadable) @@ -1013,9 +1016,9 @@ 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` +#### `worker.stdin` - + * [`null`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type) | [`stream.Writable`](/api/stream#streamwritable) @@ -1023,9 +1026,9 @@ 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` +#### `worker.stdout` - + * [`stream.Readable`](/api/stream#streamreadable) @@ -1034,9 +1037,9 @@ 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()` +#### `worker.terminate()` - + * Returns: [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) @@ -1044,9 +1047,9 @@ Stop all JavaScript execution in the worker thread as soon as possible. Returns a Promise for the exit code that is fulfilled when the [`'exit'` event][] is emitted. -#### `worker.threadId` +#### `worker.threadId` - + * [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) @@ -1054,9 +1057,9 @@ 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()` +#### `worker.unref()` - + 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 @@ -1124,6 +1127,8 @@ thread spawned will spawn another until the application crashes. [`'close'` event]: #event-close [`'exit'` event]: #event-exit [`'online'` event]: #event-online +[`--max-old-space-size`]: (/api/cli#--max-old-space-sizesize-in-megabytes) +[`--max-semi-space-size`]: (/api/cli#--max-semi-space-sizesize-in-megabytes) [`ArrayBuffer`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer [`AsyncResource`]: async_hooks.md#class-asyncresource [`Buffer.allocUnsafe()`]: (/api/buffer#static-method-bufferallocunsafesize) diff --git a/content/api/v18/zlib.en.md b/content/api/v18/zlib.en.md index de438722d0..7b3a184b05 100644 --- a/content/api/v18/zlib.en.md +++ b/content/api/v18/zlib.en.md @@ -2,15 +2,15 @@ title: 'zlib' displayTitle: 'Zlib' category: 'api' -editPage: 'https://github.com/nodejs/node/blob/v18.8.0/doc/api/zlib.md' +editPage: 'https://github.com/nodejs/node/blob/v18.9.0/doc/api/zlib.md' version: 'v18' --- - + - + - + The `node:zlib` module provides compression functionality implemented using Gzip, Deflate/Inflate, and Brotli. @@ -262,7 +262,7 @@ decompressed result is valid. ### Memory usage tuning - + #### For zlib-based streams @@ -362,9 +362,9 @@ http.createServer((request, response) => { ### Constants - + - + #### zlib constants @@ -419,7 +419,7 @@ Compression strategy. #### Brotli constants - + There are several options and other constants available for Brotli-based streams: @@ -487,11 +487,11 @@ These advanced options are available for controlling decompression: * Boolean flag enabling “Large Window Brotli” mode (not compatible with the Brotli format as standardized in [RFC 7932][]). -### `Options` +### `Options` - + - + Each zlib-based class takes an `options` object. No options are required. @@ -514,11 +514,11 @@ ignored by the decompression classes. See the [`deflateInit2` and `inflateInit2`][] documentation for more information. -### `BrotliOptions` +### `BrotliOptions` - + - + Each Brotli-based class takes an `options` object. All options are optional. @@ -542,64 +542,64 @@ const stream = zlib.createBrotliCompress({ }); ``` -### `zlib.BrotliCompress` +### `zlib.BrotliCompress` - + Compress data using the Brotli algorithm. -### `zlib.BrotliDecompress` +### `zlib.BrotliDecompress` - + Decompress data using the Brotli algorithm. -### `zlib.Deflate` +### `zlib.Deflate` - + Compress data using deflate. -### `zlib.DeflateRaw` +### `zlib.DeflateRaw` - + Compress data using deflate, and do not append a `zlib` header. -### `zlib.Gunzip` +### `zlib.Gunzip` - + Decompress a gzip stream. -### `zlib.Gzip` +### `zlib.Gzip` - + Compress data using gzip. -### `zlib.Inflate` +### `zlib.Inflate` - + Decompress a deflate stream. -### `zlib.InflateRaw` +### `zlib.InflateRaw` - + Decompress a raw deflate stream. -### `zlib.Unzip` +### `zlib.Unzip` - + Decompress either a Gzip- or Deflate-compressed stream by auto-detecting the header. -### `zlib.ZlibBase` +### `zlib.ZlibBase` - + Not exported by the `node:zlib` module. It is documented here because it is the base class of the compressor/decompressor classes. @@ -607,11 +607,11 @@ base class of the compressor/decompressor classes. This class inherits from [`stream.Transform`][], allowing `node:zlib` objects to be used in pipes and similar stream operations. -#### `zlib.bytesRead` +#### `zlib.bytesRead` - + - + * [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) @@ -620,9 +620,9 @@ because it also made sense to interpret the value as the number of bytes read by the engine, but is inconsistent with other streams in Node.js that expose values under these names. -#### `zlib.bytesWritten` +#### `zlib.bytesWritten` - + * [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) @@ -630,17 +630,17 @@ The `zlib.bytesWritten` property specifies the number of bytes written to the engine, before the bytes are processed (compressed or decompressed, as appropriate for the derived class). -#### `zlib.close([callback])` +#### `zlib.close([callback])` - + * `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) Close the underlying handle. -#### `zlib.flush([kind, ]callback)` +#### `zlib.flush([kind, ]callback)` - + * `kind` **Default:** `zlib.constants.Z_FULL_FLUSH` for zlib-based streams, `zlib.constants.BROTLI_OPERATION_FLUSH` for Brotli-based streams. @@ -654,9 +654,9 @@ perform flushing of any kind on the streams level. Rather, it behaves like a normal call to `.write()`, i.e. it will be queued up behind other pending writes and will only produce output when data is being read from the stream. -#### `zlib.params(level, strategy, callback)` +#### `zlib.params(level, strategy, callback)` - + * `level` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) * `strategy` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) @@ -667,48 +667,48 @@ This function is only available for zlib-based streams, i.e. not Brotli. Dynamically update the compression level and compression strategy. Only applicable to deflate algorithm. -#### `zlib.reset()` +#### `zlib.reset()` - + Reset the compressor/decompressor to factory defaults. Only applicable to the inflate and deflate algorithms. -### `zlib.constants` +### `zlib.constants` - + Provides an object enumerating Zlib-related constants. -### `zlib.createBrotliCompress([options])` +### `zlib.createBrotliCompress([options])` - + -* `options` {brotli options} +* `options` [`brotli options`](/api/zlib#brotlioptions) Creates and returns a new [`BrotliCompress`][] object. -### `zlib.createBrotliDecompress([options])` +### `zlib.createBrotliDecompress([options])` - + -* `options` {brotli options} +* `options` [`brotli options`](/api/zlib#brotlioptions) Creates and returns a new [`BrotliDecompress`][] object. -### `zlib.createDeflate([options])` +### `zlib.createDeflate([options])` - + -* `options` {zlib options} +* `options` [`zlib options`](/api/zlib#options) Creates and returns a new [`Deflate`][] object. -### `zlib.createDeflateRaw([options])` +### `zlib.createDeflateRaw([options])` - + -* `options` {zlib options} +* `options` [`zlib options`](/api/zlib#options) Creates and returns a new [`DeflateRaw`][] object. @@ -719,50 +719,50 @@ so Node.js restored the original behavior of upgrading a value of 8 to 9, since passing `windowBits = 9` to zlib actually results in a compressed stream that effectively uses an 8-bit window only. -### `zlib.createGunzip([options])` +### `zlib.createGunzip([options])` - + -* `options` {zlib options} +* `options` [`zlib options`](/api/zlib#options) Creates and returns a new [`Gunzip`][] object. -### `zlib.createGzip([options])` +### `zlib.createGzip([options])` - + -* `options` {zlib options} +* `options` [`zlib options`](/api/zlib#options) Creates and returns a new [`Gzip`][] object. See [example][zlib.createGzip example]. -### `zlib.createInflate([options])` +### `zlib.createInflate([options])` - + -* `options` {zlib options} +* `options` [`zlib options`](/api/zlib#options) Creates and returns a new [`Inflate`][] object. -### `zlib.createInflateRaw([options])` +### `zlib.createInflateRaw([options])` - + -* `options` {zlib options} +* `options` [`zlib options`](/api/zlib#options) Creates and returns a new [`InflateRaw`][] object. -### `zlib.createUnzip([options])` +### `zlib.createUnzip([options])` - + -* `options` {zlib options} +* `options` [`zlib options`](/api/zlib#options) Creates and returns a new [`Unzip`][] object. ### Convenience methods - + All of these take a [`Buffer`][], [`TypedArray`][], [`DataView`][], [`ArrayBuffer`][] or string as the first argument, an optional second argument @@ -772,156 +772,156 @@ with `callback(error, result)`. Every method has a `*Sync` counterpart, which accept the same arguments, but without a callback. -#### `zlib.brotliCompress(buffer[, options], callback)` +#### `zlib.brotliCompress(buffer[, options], callback)` - + * `buffer` [`Buffer`](/api/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) | [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) -* `options` {brotli options} +* `options` [`brotli options`](/api/zlib#brotlioptions) * `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) -#### `zlib.brotliCompressSync(buffer[, options])` +#### `zlib.brotliCompressSync(buffer[, options])` - + * `buffer` [`Buffer`](/api/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) | [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) -* `options` {brotli options} +* `options` [`brotli options`](/api/zlib#brotlioptions) Compress a chunk of data with [`BrotliCompress`][]. -#### `zlib.brotliDecompress(buffer[, options], callback)` +#### `zlib.brotliDecompress(buffer[, options], callback)` - + * `buffer` [`Buffer`](/api/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) | [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) -* `options` {brotli options} +* `options` [`brotli options`](/api/zlib#brotlioptions) * `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) -#### `zlib.brotliDecompressSync(buffer[, options])` +#### `zlib.brotliDecompressSync(buffer[, options])` - + * `buffer` [`Buffer`](/api/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) | [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) -* `options` {brotli options} +* `options` [`brotli options`](/api/zlib#brotlioptions) Decompress a chunk of data with [`BrotliDecompress`][]. -#### `zlib.deflate(buffer[, options], callback)` +#### `zlib.deflate(buffer[, options], callback)` - + * `buffer` [`Buffer`](/api/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) | [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) -* `options` {zlib options} +* `options` [`zlib options`](/api/zlib#options) * `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) -#### `zlib.deflateSync(buffer[, options])` +#### `zlib.deflateSync(buffer[, options])` - + * `buffer` [`Buffer`](/api/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) | [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) -* `options` {zlib options} +* `options` [`zlib options`](/api/zlib#options) Compress a chunk of data with [`Deflate`][]. -#### `zlib.deflateRaw(buffer[, options], callback)` +#### `zlib.deflateRaw(buffer[, options], callback)` - + * `buffer` [`Buffer`](/api/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) | [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) -* `options` {zlib options} +* `options` [`zlib options`](/api/zlib#options) * `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) -#### `zlib.deflateRawSync(buffer[, options])` +#### `zlib.deflateRawSync(buffer[, options])` - + * `buffer` [`Buffer`](/api/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) | [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) -* `options` {zlib options} +* `options` [`zlib options`](/api/zlib#options) Compress a chunk of data with [`DeflateRaw`][]. -#### `zlib.gunzip(buffer[, options], callback)` +#### `zlib.gunzip(buffer[, options], callback)` - + * `buffer` [`Buffer`](/api/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) | [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) -* `options` {zlib options} +* `options` [`zlib options`](/api/zlib#options) * `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) -#### `zlib.gunzipSync(buffer[, options])` +#### `zlib.gunzipSync(buffer[, options])` - + * `buffer` [`Buffer`](/api/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) | [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) -* `options` {zlib options} +* `options` [`zlib options`](/api/zlib#options) Decompress a chunk of data with [`Gunzip`][]. -#### `zlib.gzip(buffer[, options], callback)` +#### `zlib.gzip(buffer[, options], callback)` - + * `buffer` [`Buffer`](/api/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) | [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) -* `options` {zlib options} +* `options` [`zlib options`](/api/zlib#options) * `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) -#### `zlib.gzipSync(buffer[, options])` +#### `zlib.gzipSync(buffer[, options])` - + * `buffer` [`Buffer`](/api/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) | [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) -* `options` {zlib options} +* `options` [`zlib options`](/api/zlib#options) Compress a chunk of data with [`Gzip`][]. -#### `zlib.inflate(buffer[, options], callback)` +#### `zlib.inflate(buffer[, options], callback)` - + * `buffer` [`Buffer`](/api/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) | [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) -* `options` {zlib options} +* `options` [`zlib options`](/api/zlib#options) * `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) -#### `zlib.inflateSync(buffer[, options])` +#### `zlib.inflateSync(buffer[, options])` - + * `buffer` [`Buffer`](/api/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) | [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) -* `options` {zlib options} +* `options` [`zlib options`](/api/zlib#options) Decompress a chunk of data with [`Inflate`][]. -#### `zlib.inflateRaw(buffer[, options], callback)` +#### `zlib.inflateRaw(buffer[, options], callback)` - + * `buffer` [`Buffer`](/api/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) | [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) -* `options` {zlib options} +* `options` [`zlib options`](/api/zlib#options) * `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) -#### `zlib.inflateRawSync(buffer[, options])` +#### `zlib.inflateRawSync(buffer[, options])` - + * `buffer` [`Buffer`](/api/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) | [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) -* `options` {zlib options} +* `options` [`zlib options`](/api/zlib#options) Decompress a chunk of data with [`InflateRaw`][]. -#### `zlib.unzip(buffer[, options], callback)` +#### `zlib.unzip(buffer[, options], callback)` - + * `buffer` [`Buffer`](/api/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) | [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) -* `options` {zlib options} +* `options` [`zlib options`](/api/zlib#options) * `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) -#### `zlib.unzipSync(buffer[, options])` +#### `zlib.unzipSync(buffer[, options])` - + * `buffer` [`Buffer`](/api/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) | [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) -* `options` {zlib options} +* `options` [`zlib options`](/api/zlib#options) Decompress a chunk of data with [`Unzip`][].