Skip to content
This repository has been archived by the owner on Apr 22, 2023. It is now read-only.

Original content updates #743

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
128 changes: 64 additions & 64 deletions content/v18.x/en-US/doc/api/assert.md

Large diffs are not rendered by default.

27 changes: 23 additions & 4 deletions content/v18.x/en-US/doc/api/async_context.md
Original file line number Diff line number Diff line change
Expand Up @@ -116,17 +116,35 @@ 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([options])`

<!-- YAML
added:
- v13.10.0
- v12.17.0
changes:
- version: v18.13.0
pr-url: https://github.com/nodejs/node/pull/45386
description: Add option onPropagate.
-->

> Stability: 1 - `options.onPropagate` is experimental.

* `options` {Object}
* `onPropagate` {Function} Optional callback invoked before a store is
propagated to a new async resource. Returning `true` allows propagation,
returning `false` avoids it. Default is to propagate always.

Creates a new instance of `AsyncLocalStorage`. Store is only provided within a
`run()` call or after an `enterWith()` call.

The `onPropagate` is called during creation of an async resource. Throwing at
this time will print the stack trace and exit. See
[`async_hooks` Error handling][] for details.

Creating an async resource within the `onPropagate` callback will result in
a recursive call to `onPropagate`.

### `asyncLocalStorage.disable()`

<!-- YAML
Expand Down Expand Up @@ -354,7 +372,7 @@ import { AsyncResource, executionAsyncId } from 'node:async_hooks';
// new AsyncResource() also triggers init. If triggerAsyncId is omitted then
// async_hook.executionAsyncId() is used.
const asyncResource = new AsyncResource(
type, { triggerAsyncId: executionAsyncId(), requireManualDestroy: false }
type, { triggerAsyncId: executionAsyncId(), requireManualDestroy: false },
);

// Run a function in the execution context of the resource. This will
Expand Down Expand Up @@ -382,7 +400,7 @@ const { AsyncResource, executionAsyncId } = require('node:async_hooks');
// new AsyncResource() also triggers init. If triggerAsyncId is omitted then
// async_hook.executionAsyncId() is used.
const asyncResource = new AsyncResource(
type, { triggerAsyncId: executionAsyncId(), requireManualDestroy: false }
type, { triggerAsyncId: executionAsyncId(), requireManualDestroy: false },
);

// Run a function in the execution context of the resource. This will
Expand Down Expand Up @@ -593,7 +611,7 @@ export default class WorkerPool extends EventEmitter {
}

addNewWorker() {
const worker = new Worker(new URL('task_processer.js', import.meta.url));
const worker = new Worker(new URL('task_processor.js', import.meta.url));
worker.on('message', (result) => {
// In case of success: Call the callback that was passed to `runTask`,
// remove the `TaskInfo` associated with the Worker, and mark it as free
Expand Down Expand Up @@ -812,4 +830,5 @@ const server = createServer((req, res) => {
[`EventEmitter`]: events.md#class-eventemitter
[`Stream`]: stream.md#stream
[`Worker`]: worker_threads.md#class-worker
[`async_hooks` Error handling]: async_hooks.md#error-handling
[`util.promisify()`]: util.md#utilpromisifyoriginal
73 changes: 46 additions & 27 deletions content/v18.x/en-US/doc/api/async_hooks.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,25 @@

<!--introduced_in=v8.1.0-->

> Stability: 1 - Experimental
> Stability: 1 - Experimental. Please migrate away from this API, if you can.
> We do not recommend using the [`createHook`][], [`AsyncHook`][], and
> [`executionAsyncResource`][] APIs as they have usability issues, safety risks,
> and performance implications. Async context tracking use cases are better
> served by the stable [`AsyncLocalStorage`][] API. If you have a use case for
> `createHook`, `AsyncHook`, or `executionAsyncResource` beyond the context
> tracking need solved by [`AsyncLocalStorage`][] or diagnostics data currently
> provided by [Diagnostics Channel][], please open an issue at
> <https://github.com/nodejs/node/issues> describing your use case so we can
> create a more purpose-focused API.

<!-- source_link=lib/async_hooks.js -->

We strongly discourage the use of the `async_hooks` API.
Other APIs that can cover most of its use cases include:

* [`AsyncLocalStorage`][] tracks async context
* [`process.getActiveResourcesInfo()`][] tracks active resources

The `node:async_hooks` module provides an API to track asynchronous resources.
It can be accessed using:

Expand Down Expand Up @@ -159,7 +174,7 @@ import { createHook } from 'node:async_hooks';

const asyncHook = createHook({
init(asyncId, type, triggerAsyncId, resource) { },
destroy(asyncId) { }
destroy(asyncId) { },
});
```

Expand All @@ -168,7 +183,7 @@ const async_hooks = require('node:async_hooks');

const asyncHook = async_hooks.createHook({
init(asyncId, type, triggerAsyncId, resource) { },
destroy(asyncId) { }
destroy(asyncId) { },
});
```

Expand Down Expand Up @@ -329,18 +344,14 @@ The `type` is a string identifying the type of resource that caused
`init` to be called. Generally, it will correspond to the name of the
resource's constructor.

Valid values are:

```text
FSEVENTWRAP, FSREQCALLBACK, GETADDRINFOREQWRAP, GETNAMEINFOREQWRAP, HTTPINCOMINGMESSAGE,
HTTPCLIENTREQUEST, JSSTREAM, PIPECONNECTWRAP, PIPEWRAP, PROCESSWRAP, QUERYWRAP,
SHUTDOWNWRAP, SIGNALWRAP, STATWATCHER, TCPCONNECTWRAP, TCPSERVERWRAP, TCPWRAP,
TTYWRAP, UDPSENDWRAP, UDPWRAP, WRITEWRAP, ZLIB, SSLCONNECTION, PBKDF2REQUEST,
RANDOMBYTESREQUEST, TLSWRAP, Microtask, Timeout, Immediate, TickObject
```
The `type` of resources created by Node.js itself can change in any Node.js
release. Valid values include `TLSWRAP`,
`TCPWRAP`, `TCPSERVERWRAP`, `GETADDRINFOREQWRAP`, `FSREQCALLBACK`,
`Microtask`, and `Timeout`. Inspect the source code of the Node.js version used
to get the full list.

These values can change in any Node.js release. Furthermore users of [`AsyncResource`][]
likely provide other values.
Furthermore users of [`AsyncResource`][] create async resources independent
of Node.js itself.

There is also the `PROMISE` resource type, which is used to track `Promise`
instances and asynchronous work scheduled by them.
Expand Down Expand Up @@ -371,7 +382,7 @@ createHook({
fs.writeSync(
stdout.fd,
`${type}(${asyncId}): trigger: ${triggerAsyncId} execution: ${eid}\n`);
}
},
}).enable();

net.createServer((conn) => {}).listen(8080);
Expand All @@ -388,7 +399,7 @@ createHook({
fs.writeSync(
stdout.fd,
`${type}(${asyncId}): trigger: ${triggerAsyncId} execution: ${eid}\n`);
}
},
}).enable();

net.createServer((conn) => {}).listen(8080);
Expand All @@ -414,19 +425,19 @@ of propagating what resource is responsible for the new resource's existence.
##### `resource`

`resource` is an object that represents the actual async resource that has
been initialized. This can contain useful information that can vary based on
the value of `type`. For instance, for the `GETADDRINFOREQWRAP` resource type,
`resource` provides the host name used when looking up the IP address for the
host in `net.Server.listen()`. The API for accessing this information is
not supported, but using the Embedder API, users can provide
and document their own resource objects. For example, such a resource object
could contain the SQL query being executed.
been initialized. The API to access the object may be specified by the
creator of the resource. Resources created by Node.js itself are internal
and may change at any time. Therefore no API is specified for these.

In some cases the resource object is reused for performance reasons, it is
thus not safe to use it as a key in a `WeakMap` or add properties to it.

##### Asynchronous context example

The context tracking use case is covered by the stable API [`AsyncLocalStorage`][].
This example only illustrates async hooks operation but [`AsyncLocalStorage`][]
fits better to this use case.

The following is an example with additional information about the calls to
`init` between the `before` and `after` calls, specifically what the
callback to `listen()` will look like. The output formatting is slightly more
Expand Down Expand Up @@ -568,6 +579,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.

Using the destroy hook results in additional overhead because it enables
tracking of `Promise` instances via the garbage collector.

#### `promiseResolve(asyncId)`

<!-- YAML
Expand Down Expand Up @@ -646,7 +660,7 @@ import { createServer } from 'node:http';
import {
executionAsyncId,
executionAsyncResource,
createHook
createHook,
} from 'async_hooks';
const sym = Symbol('state'); // Private symbol to avoid pollution

Expand All @@ -656,7 +670,7 @@ createHook({
if (cr) {
resource[sym] = cr[sym];
}
}
},
}).enable();

const server = createServer((req, res) => {
Expand All @@ -672,7 +686,7 @@ const { createServer } = require('node:http');
const {
executionAsyncId,
executionAsyncResource,
createHook
createHook,
} = require('node:async_hooks');
const sym = Symbol('state'); // Private symbol to avoid pollution

Expand All @@ -682,7 +696,7 @@ createHook({
if (cr) {
resource[sym] = cr[sym];
}
}
},
}).enable();

const server = createServer((req, res) => {
Expand Down Expand Up @@ -864,14 +878,19 @@ The documentation for this class has moved [`AsyncResource`][].
The documentation for this class has moved [`AsyncLocalStorage`][].

[DEP0111]: deprecations.md#dep0111-processbinding
[Diagnostics Channel]: diagnostics_channel.md
[Hook Callbacks]: #hook-callbacks
[PromiseHooks]: https://docs.google.com/document/d/1rda3yKGHimKIhg5YeoAmCOtyURgsbTH_qaYR79FELlk/edit
[`AsyncHook`]: #class-asynchook
[`AsyncLocalStorage`]: async_context.md#class-asynclocalstorage
[`AsyncResource`]: async_context.md#class-asyncresource
[`Worker`]: worker_threads.md#class-worker
[`after` callback]: #afterasyncid
[`before` callback]: #beforeasyncid
[`createHook`]: #async_hookscreatehookcallbacks
[`destroy` callback]: #destroyasyncid
[`executionAsyncResource`]: #async_hooksexecutionasyncresource
[`init` callback]: #initasyncid-type-triggerasyncid-resource
[`process.getActiveResourcesInfo()`]: process.md#processgetactiveresourcesinfo
[`promiseResolve` callback]: #promiseresolveasyncid
[promise execution tracking]: #promise-execution-tracking
64 changes: 64 additions & 0 deletions content/v18.x/en-US/doc/api/buffer.md
Original file line number Diff line number Diff line change
Expand Up @@ -1882,6 +1882,7 @@ changes:
-->

* `value` {string|Buffer|Uint8Array|integer} The value with which to fill `buf`.
Empty value (string, Uint8Array, Buffer) is coerced to `0`.
* `offset` {integer} Number of bytes to skip before starting to fill `buf`.
**Default:** `0`.
* `end` {integer} Where to stop filling `buf` (not inclusive). **Default:**
Expand All @@ -1902,6 +1903,12 @@ const b = Buffer.allocUnsafe(50).fill('h');

console.log(b.toString());
// Prints: hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh

// Fill a buffer with empty string
const c = Buffer.allocUnsafe(5).fill('');

console.log(c.fill(''));
// Prints: <Buffer 00 00 00 00 00>
```

```cjs
Expand All @@ -1913,6 +1920,12 @@ const b = Buffer.allocUnsafe(50).fill('h');

console.log(b.toString());
// Prints: hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh

// Fill a buffer with empty string
const c = Buffer.allocUnsafe(5).fill('');

console.log(c.fill(''));
// Prints: <Buffer 00 00 00 00 00>
```

`value` is coerced to a `uint32` value if it is not a string, `Buffer`, or
Expand Down Expand Up @@ -5009,6 +5022,56 @@ changes:

See [`Buffer.from(string[, encoding])`][`Buffer.from(string)`].

## Class: `File`

<!-- YAML
added: v18.13.0
-->

> Stability: 1 - Experimental

* Extends: {Blob}

A [`File`][] provides information about files.

### `new buffer.File(sources, fileName[, options])`

<!-- YAML
added: v18.13.0
-->

* `sources` {string\[]|ArrayBuffer\[]|TypedArray\[]|DataView\[]|Blob\[]|File\[]}
An array of string, {ArrayBuffer}, {TypedArray}, {DataView}, {File}, or {Blob}
objects, or any mix of such objects, that will be stored within the `File`.
* `fileName` {string} The name of the file.
* `options` {Object}
* `endings` {string} One of either `'transparent'` or `'native'`. When set
to `'native'`, line endings in string source parts will be converted to
the platform native line-ending as specified by `require('node:os').EOL`.
* `type` {string} The File content-type.
* `lastModified` {number} The last modified date of the file.
**Default:** `Date.now()`.

### `file.name`

<!-- YAML
added: v18.13.0
-->

* Type: {string}

The name of the `File`.

### `file.lastModified`

<!-- YAML
added: v18.13.0
-->

* Type: {number}

The last modified date of the `File`.

## `node:buffer` module APIs

While, the `Buffer` object is available as a global, there are additional
Expand Down Expand Up @@ -5355,6 +5418,7 @@ introducing security vulnerabilities into an application.
[`ERR_INVALID_ARG_VALUE`]: errors.md#err_invalid_arg_value
[`ERR_INVALID_BUFFER_SIZE`]: errors.md#err_invalid_buffer_size
[`ERR_OUT_OF_RANGE`]: errors.md#err_out_of_range
[`File`]: https://developer.mozilla.org/en-US/docs/Web/API/File
[`JSON.stringify()`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify
[`SharedArrayBuffer`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer
[`String.prototype.indexOf()`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/indexOf
Expand Down
Loading