mirror of
https://github.com/nodejs/node.git
synced 2025-12-28 07:50:41 +00:00
doc: add node: prefix for all core modules
Some core modules can be loaded with or without the `node:` prefix. Using the prefix disambiguates which specifiers refer to core modules. This commit updates the docs to use the prefix everywhere a core module is referenced. PR-URL: https://github.com/nodejs/node/pull/42752 Fixes: https://github.com/nodejs/node/issues/38343 Reviewed-By: Matteo Collina <matteo.collina@gmail.com> Reviewed-By: Mestery <mestery@protonmail.com> Reviewed-By: Darshan Sen <raisinten@gmail.com> Reviewed-By: Akhil Marsonya <akhil.marsonya27@gmail.com> Reviewed-By: Rafael Gonzaga <rafael.nunu@hotmail.com> Reviewed-By: Mohammed Keyvanzadeh <mohammadkeyvanzade94@gmail.com> Reviewed-By: Geoffrey Booth <webadmin@geoffreybooth.com> Reviewed-By: Stephen Belanger <admin@stephenbelanger.com>
This commit is contained in:
parent
1fe5d56403
commit
6afd3fcf65
@ -6,7 +6,7 @@
|
||||
|
||||
<!-- source_link=lib/assert.js -->
|
||||
|
||||
The `assert` module provides a set of assertion functions for verifying
|
||||
The `node:assert` module provides a set of assertion functions for verifying
|
||||
invariants.
|
||||
|
||||
## Strict assertion mode
|
||||
@ -16,7 +16,7 @@ added: v9.9.0
|
||||
changes:
|
||||
- version: v15.0.0
|
||||
pr-url: https://github.com/nodejs/node/pull/34001
|
||||
description: Exposed as `require('assert/strict')`.
|
||||
description: Exposed as `require('node:assert/strict')`.
|
||||
- version:
|
||||
- v13.9.0
|
||||
- v12.16.2
|
||||
@ -42,25 +42,25 @@ assertion mode, error messages for objects display the objects, often truncated.
|
||||
To use strict assertion mode:
|
||||
|
||||
```mjs
|
||||
import { strict as assert } from 'assert';
|
||||
import { strict as assert } from 'node:assert';
|
||||
```
|
||||
|
||||
```cjs
|
||||
const assert = require('assert').strict;
|
||||
const assert = require('node:assert').strict;
|
||||
```
|
||||
|
||||
```mjs
|
||||
import assert from 'assert/strict';
|
||||
import assert from 'node:assert/strict';
|
||||
```
|
||||
|
||||
```cjs
|
||||
const assert = require('assert/strict');
|
||||
const assert = require('node:assert/strict');
|
||||
```
|
||||
|
||||
Example error diff:
|
||||
|
||||
```mjs
|
||||
import { strict as assert } from 'assert';
|
||||
import { strict as assert } from 'node:assert';
|
||||
|
||||
assert.deepEqual([[[1, 2, 3]], 4, 5], [[[1, 2, '3']], 4, 5]);
|
||||
// AssertionError: Expected inputs to be strictly deep-equal:
|
||||
@ -79,7 +79,7 @@ assert.deepEqual([[[1, 2, 3]], 4, 5], [[[1, 2, '3']], 4, 5]);
|
||||
```
|
||||
|
||||
```cjs
|
||||
const assert = require('assert/strict');
|
||||
const assert = require('node:assert/strict');
|
||||
|
||||
assert.deepEqual([[[1, 2, 3]], 4, 5], [[[1, 2, '3']], 4, 5]);
|
||||
// AssertionError: Expected inputs to be strictly deep-equal:
|
||||
@ -114,11 +114,11 @@ Legacy assertion mode uses the [`==` operator][] in:
|
||||
To use legacy assertion mode:
|
||||
|
||||
```mjs
|
||||
import assert from 'assert';
|
||||
import assert from 'node:assert';
|
||||
```
|
||||
|
||||
```cjs
|
||||
const assert = require('assert');
|
||||
const assert = require('node:assert');
|
||||
```
|
||||
|
||||
Legacy assertion mode may have surprising results, especially when using
|
||||
@ -133,8 +133,8 @@ assert.deepEqual(/a/gi, new Date());
|
||||
|
||||
* Extends: {errors.Error}
|
||||
|
||||
Indicates the failure of an assertion. All errors thrown by the `assert` module
|
||||
will be instances of the `AssertionError` class.
|
||||
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)`
|
||||
|
||||
@ -166,7 +166,7 @@ and:
|
||||
* `operator` {string} Set to the passed in operator value.
|
||||
|
||||
```mjs
|
||||
import assert from 'assert';
|
||||
import assert from 'node:assert';
|
||||
|
||||
// Generate an AssertionError to compare the error message later:
|
||||
const { message } = new assert.AssertionError({
|
||||
@ -191,7 +191,7 @@ try {
|
||||
```
|
||||
|
||||
```cjs
|
||||
const assert = require('assert');
|
||||
const assert = require('node:assert');
|
||||
|
||||
// Generate an AssertionError to compare the error message later:
|
||||
const { message } = new assert.AssertionError({
|
||||
@ -241,8 +241,8 @@ for the verification to take place. The usual pattern would be to call it in a
|
||||
[`process.on('exit')`][] handler.
|
||||
|
||||
```mjs
|
||||
import assert from 'assert';
|
||||
import process from 'process';
|
||||
import assert from 'node:assert';
|
||||
import process from 'node:process';
|
||||
|
||||
const tracker = new assert.CallTracker();
|
||||
|
||||
@ -261,7 +261,7 @@ process.on('exit', () => {
|
||||
```
|
||||
|
||||
```cjs
|
||||
const assert = require('assert');
|
||||
const assert = require('node:assert');
|
||||
|
||||
const tracker = new assert.CallTracker();
|
||||
|
||||
@ -297,7 +297,7 @@ function has not been called exactly `exact` times when
|
||||
error.
|
||||
|
||||
```mjs
|
||||
import assert from 'assert';
|
||||
import assert from 'node:assert';
|
||||
|
||||
// Creates call tracker.
|
||||
const tracker = new assert.CallTracker();
|
||||
@ -310,7 +310,7 @@ const callsfunc = tracker.calls(func);
|
||||
```
|
||||
|
||||
```cjs
|
||||
const assert = require('assert');
|
||||
const assert = require('node:assert');
|
||||
|
||||
// Creates call tracker.
|
||||
const tracker = new assert.CallTracker();
|
||||
@ -344,7 +344,7 @@ The arrays contains information about the expected and actual number of calls of
|
||||
the functions that have not been called the expected number of times.
|
||||
|
||||
```mjs
|
||||
import assert from 'assert';
|
||||
import assert from 'node:assert';
|
||||
|
||||
// Creates call tracker.
|
||||
const tracker = new assert.CallTracker();
|
||||
@ -372,7 +372,7 @@ tracker.report();
|
||||
```
|
||||
|
||||
```cjs
|
||||
const assert = require('assert');
|
||||
const assert = require('node:assert');
|
||||
|
||||
// Creates call tracker.
|
||||
const tracker = new assert.CallTracker();
|
||||
@ -412,7 +412,7 @@ Iterates through the list of functions passed to
|
||||
have not been called the expected number of times.
|
||||
|
||||
```mjs
|
||||
import assert from 'assert';
|
||||
import assert from 'node:assert';
|
||||
|
||||
// Creates call tracker.
|
||||
const tracker = new assert.CallTracker();
|
||||
@ -430,7 +430,7 @@ tracker.verify();
|
||||
```
|
||||
|
||||
```cjs
|
||||
const assert = require('assert');
|
||||
const assert = require('node:assert');
|
||||
|
||||
// Creates call tracker.
|
||||
const tracker = new assert.CallTracker();
|
||||
@ -547,14 +547,14 @@ The following example does not throw an [`AssertionError`][] because the
|
||||
primitives are compared using the [`==` operator][].
|
||||
|
||||
```mjs
|
||||
import assert from 'assert';
|
||||
import assert from 'node:assert';
|
||||
// WARNING: This does not throw an AssertionError!
|
||||
|
||||
assert.deepEqual('+00000000', false);
|
||||
```
|
||||
|
||||
```cjs
|
||||
const assert = require('assert');
|
||||
const assert = require('node:assert');
|
||||
// WARNING: This does not throw an AssertionError!
|
||||
|
||||
assert.deepEqual('+00000000', false);
|
||||
@ -564,7 +564,7 @@ assert.deepEqual('+00000000', false);
|
||||
are evaluated also:
|
||||
|
||||
```mjs
|
||||
import assert from 'assert';
|
||||
import assert from 'node:assert';
|
||||
|
||||
const obj1 = {
|
||||
a: {
|
||||
@ -599,7 +599,7 @@ assert.deepEqual(obj1, obj4);
|
||||
```
|
||||
|
||||
```cjs
|
||||
const assert = require('assert');
|
||||
const assert = require('node:assert');
|
||||
|
||||
const obj1 = {
|
||||
a: {
|
||||
@ -705,7 +705,7 @@ are recursively evaluated also by the following rules.
|
||||
are not enumerable properties.
|
||||
|
||||
```mjs
|
||||
import assert from 'assert/strict';
|
||||
import assert from 'node:assert/strict';
|
||||
|
||||
// This fails because 1 !== '1'.
|
||||
assert.deepStrictEqual({ a: 1 }, { a: '1' });
|
||||
@ -797,7 +797,7 @@ assert.deepStrictEqual(weakMap1, weakMap3);
|
||||
```
|
||||
|
||||
```cjs
|
||||
const assert = require('assert/strict');
|
||||
const assert = require('node:assert/strict');
|
||||
|
||||
// This fails because 1 !== '1'.
|
||||
assert.deepStrictEqual({ a: 1 }, { a: '1' });
|
||||
@ -913,7 +913,7 @@ changes:
|
||||
Expects the `string` input not to match the regular expression.
|
||||
|
||||
```mjs
|
||||
import assert from 'assert/strict';
|
||||
import assert from 'node:assert/strict';
|
||||
|
||||
assert.doesNotMatch('I will fail', /fail/);
|
||||
// AssertionError [ERR_ASSERTION]: The input was expected to not match the ...
|
||||
@ -926,7 +926,7 @@ assert.doesNotMatch('I will pass', /different/);
|
||||
```
|
||||
|
||||
```cjs
|
||||
const assert = require('assert/strict');
|
||||
const assert = require('node:assert/strict');
|
||||
|
||||
assert.doesNotMatch('I will fail', /fail/);
|
||||
// AssertionError [ERR_ASSERTION]: The input was expected to not match the ...
|
||||
@ -977,7 +977,7 @@ Besides the async nature to await the completion behaves identically to
|
||||
[`assert.doesNotThrow()`][].
|
||||
|
||||
```mjs
|
||||
import assert from 'assert/strict';
|
||||
import assert from 'node:assert/strict';
|
||||
|
||||
await assert.doesNotReject(
|
||||
async () => {
|
||||
@ -988,7 +988,7 @@ await assert.doesNotReject(
|
||||
```
|
||||
|
||||
```cjs
|
||||
const assert = require('assert/strict');
|
||||
const assert = require('node:assert/strict');
|
||||
|
||||
(async () => {
|
||||
await assert.doesNotReject(
|
||||
@ -1001,7 +1001,7 @@ const assert = require('assert/strict');
|
||||
```
|
||||
|
||||
```mjs
|
||||
import assert from 'assert/strict';
|
||||
import assert from 'node:assert/strict';
|
||||
|
||||
assert.doesNotReject(Promise.reject(new TypeError('Wrong value')))
|
||||
.then(() => {
|
||||
@ -1010,7 +1010,7 @@ assert.doesNotReject(Promise.reject(new TypeError('Wrong value')))
|
||||
```
|
||||
|
||||
```cjs
|
||||
const assert = require('assert/strict');
|
||||
const assert = require('node:assert/strict');
|
||||
|
||||
assert.doesNotReject(Promise.reject(new TypeError('Wrong value')))
|
||||
.then(() => {
|
||||
@ -1059,7 +1059,7 @@ The following, for instance, will throw the [`TypeError`][] because there is no
|
||||
matching error type in the assertion:
|
||||
|
||||
```mjs
|
||||
import assert from 'assert/strict';
|
||||
import assert from 'node:assert/strict';
|
||||
|
||||
assert.doesNotThrow(
|
||||
() => {
|
||||
@ -1070,7 +1070,7 @@ assert.doesNotThrow(
|
||||
```
|
||||
|
||||
```cjs
|
||||
const assert = require('assert/strict');
|
||||
const assert = require('node:assert/strict');
|
||||
|
||||
assert.doesNotThrow(
|
||||
() => {
|
||||
@ -1084,7 +1084,7 @@ However, the following will result in an [`AssertionError`][] with the message
|
||||
'Got unwanted exception...':
|
||||
|
||||
```mjs
|
||||
import assert from 'assert/strict';
|
||||
import assert from 'node:assert/strict';
|
||||
|
||||
assert.doesNotThrow(
|
||||
() => {
|
||||
@ -1095,7 +1095,7 @@ assert.doesNotThrow(
|
||||
```
|
||||
|
||||
```cjs
|
||||
const assert = require('assert/strict');
|
||||
const assert = require('node:assert/strict');
|
||||
|
||||
assert.doesNotThrow(
|
||||
() => {
|
||||
@ -1110,7 +1110,7 @@ parameter, the value of `message` will be appended to the [`AssertionError`][]
|
||||
message:
|
||||
|
||||
```mjs
|
||||
import assert from 'assert/strict';
|
||||
import assert from 'node:assert/strict';
|
||||
|
||||
assert.doesNotThrow(
|
||||
() => {
|
||||
@ -1123,7 +1123,7 @@ assert.doesNotThrow(
|
||||
```
|
||||
|
||||
```cjs
|
||||
const assert = require('assert/strict');
|
||||
const assert = require('node:assert/strict');
|
||||
|
||||
assert.doesNotThrow(
|
||||
() => {
|
||||
@ -1169,7 +1169,7 @@ using the [`==` operator][]. `NaN` is specially handled
|
||||
and treated as being identical if both sides are `NaN`.
|
||||
|
||||
```mjs
|
||||
import assert from 'assert';
|
||||
import assert from 'node:assert';
|
||||
|
||||
assert.equal(1, 1);
|
||||
// OK, 1 == 1
|
||||
@ -1185,7 +1185,7 @@ assert.equal({ a: { b: 1 } }, { a: { b: 1 } });
|
||||
```
|
||||
|
||||
```cjs
|
||||
const assert = require('assert');
|
||||
const assert = require('node:assert');
|
||||
|
||||
assert.equal(1, 1);
|
||||
// OK, 1 == 1
|
||||
@ -1219,7 +1219,7 @@ error message. If the `message` parameter is an instance of an [`Error`][] then
|
||||
it will be thrown instead of the [`AssertionError`][].
|
||||
|
||||
```mjs
|
||||
import assert from 'assert/strict';
|
||||
import assert from 'node:assert/strict';
|
||||
|
||||
assert.fail();
|
||||
// AssertionError [ERR_ASSERTION]: Failed
|
||||
@ -1232,7 +1232,7 @@ assert.fail(new TypeError('need array'));
|
||||
```
|
||||
|
||||
```cjs
|
||||
const assert = require('assert/strict');
|
||||
const assert = require('node:assert/strict');
|
||||
|
||||
assert.fail();
|
||||
// AssertionError [ERR_ASSERTION]: Failed
|
||||
@ -1277,7 +1277,7 @@ removed from stacktrace (see [`Error.captureStackTrace`][]). If no arguments are
|
||||
given, the default message `Failed` will be used.
|
||||
|
||||
```mjs
|
||||
import assert from 'assert/strict';
|
||||
import assert from 'node:assert/strict';
|
||||
|
||||
assert.fail('a', 'b');
|
||||
// AssertionError [ERR_ASSERTION]: 'a' != 'b'
|
||||
@ -1296,7 +1296,7 @@ assert.fail(1, 2, new TypeError('need array'));
|
||||
```
|
||||
|
||||
```cjs
|
||||
const assert = require('assert/strict');
|
||||
const assert = require('node:assert/strict');
|
||||
|
||||
assert.fail('a', 'b');
|
||||
// AssertionError [ERR_ASSERTION]: 'a' != 'b'
|
||||
@ -1320,7 +1320,7 @@ influence on the error message.
|
||||
Example use of `stackStartFn` for truncating the exception's stacktrace:
|
||||
|
||||
```mjs
|
||||
import assert from 'assert/strict';
|
||||
import assert from 'node:assert/strict';
|
||||
|
||||
function suppressFrame() {
|
||||
assert.fail('a', 'b', undefined, '!==', suppressFrame);
|
||||
@ -1333,7 +1333,7 @@ suppressFrame();
|
||||
```
|
||||
|
||||
```cjs
|
||||
const assert = require('assert/strict');
|
||||
const assert = require('node:assert/strict');
|
||||
|
||||
function suppressFrame() {
|
||||
assert.fail('a', 'b', undefined, '!==', suppressFrame);
|
||||
@ -1368,7 +1368,7 @@ from the error passed to `ifError()` including the potential new frames for
|
||||
`ifError()` itself.
|
||||
|
||||
```mjs
|
||||
import assert from 'assert/strict';
|
||||
import assert from 'node:assert/strict';
|
||||
|
||||
assert.ifError(null);
|
||||
// OK
|
||||
@ -1394,7 +1394,7 @@ let err;
|
||||
```
|
||||
|
||||
```cjs
|
||||
const assert = require('assert/strict');
|
||||
const assert = require('node:assert/strict');
|
||||
|
||||
assert.ifError(null);
|
||||
// OK
|
||||
@ -1438,7 +1438,7 @@ changes:
|
||||
Expects the `string` input to match the regular expression.
|
||||
|
||||
```mjs
|
||||
import assert from 'assert/strict';
|
||||
import assert from 'node:assert/strict';
|
||||
|
||||
assert.match('I will fail', /pass/);
|
||||
// AssertionError [ERR_ASSERTION]: The input did not match the regular ...
|
||||
@ -1451,7 +1451,7 @@ assert.match('I will pass', /pass/);
|
||||
```
|
||||
|
||||
```cjs
|
||||
const assert = require('assert/strict');
|
||||
const assert = require('node:assert/strict');
|
||||
|
||||
assert.match('I will fail', /pass/);
|
||||
// AssertionError [ERR_ASSERTION]: The input did not match the regular ...
|
||||
@ -1523,7 +1523,7 @@ An alias of [`assert.notDeepStrictEqual()`][].
|
||||
Tests for any deep inequality. Opposite of [`assert.deepEqual()`][].
|
||||
|
||||
```mjs
|
||||
import assert from 'assert';
|
||||
import assert from 'node:assert';
|
||||
|
||||
const obj1 = {
|
||||
a: {
|
||||
@ -1556,7 +1556,7 @@ assert.notDeepEqual(obj1, obj4);
|
||||
```
|
||||
|
||||
```cjs
|
||||
const assert = require('assert');
|
||||
const assert = require('node:assert');
|
||||
|
||||
const obj1 = {
|
||||
a: {
|
||||
@ -1635,14 +1635,14 @@ changes:
|
||||
Tests for deep strict inequality. Opposite of [`assert.deepStrictEqual()`][].
|
||||
|
||||
```mjs
|
||||
import assert from 'assert/strict';
|
||||
import assert from 'node:assert/strict';
|
||||
|
||||
assert.notDeepStrictEqual({ a: 1 }, { a: '1' });
|
||||
// OK
|
||||
```
|
||||
|
||||
```cjs
|
||||
const assert = require('assert/strict');
|
||||
const assert = require('node:assert/strict');
|
||||
|
||||
assert.notDeepStrictEqual({ a: 1 }, { a: '1' });
|
||||
// OK
|
||||
@ -1687,7 +1687,7 @@ Tests shallow, coercive inequality with the [`!=` operator][]. `NaN` is
|
||||
specially handled and treated as being identical if both sides are `NaN`.
|
||||
|
||||
```mjs
|
||||
import assert from 'assert';
|
||||
import assert from 'node:assert';
|
||||
|
||||
assert.notEqual(1, 2);
|
||||
// OK
|
||||
@ -1700,7 +1700,7 @@ assert.notEqual(1, '1');
|
||||
```
|
||||
|
||||
```cjs
|
||||
const assert = require('assert');
|
||||
const assert = require('node:assert');
|
||||
|
||||
assert.notEqual(1, 2);
|
||||
// OK
|
||||
@ -1736,7 +1736,7 @@ Tests strict inequality between the `actual` and `expected` parameters as
|
||||
determined by [`Object.is()`][].
|
||||
|
||||
```mjs
|
||||
import assert from 'assert/strict';
|
||||
import assert from 'node:assert/strict';
|
||||
|
||||
assert.notStrictEqual(1, 2);
|
||||
// OK
|
||||
@ -1751,7 +1751,7 @@ assert.notStrictEqual(1, '1');
|
||||
```
|
||||
|
||||
```cjs
|
||||
const assert = require('assert/strict');
|
||||
const assert = require('node:assert/strict');
|
||||
|
||||
assert.notStrictEqual(1, 2);
|
||||
// OK
|
||||
@ -1800,7 +1800,7 @@ Be aware that in the `repl` the error message will be different to the one
|
||||
thrown in a file! See below for further details.
|
||||
|
||||
```mjs
|
||||
import assert from 'assert/strict';
|
||||
import assert from 'node:assert/strict';
|
||||
|
||||
assert.ok(true);
|
||||
// OK
|
||||
@ -1835,7 +1835,7 @@ assert.ok(0);
|
||||
```
|
||||
|
||||
```cjs
|
||||
const assert = require('assert/strict');
|
||||
const assert = require('node:assert/strict');
|
||||
|
||||
assert.ok(true);
|
||||
// OK
|
||||
@ -1870,7 +1870,7 @@ assert.ok(0);
|
||||
```
|
||||
|
||||
```mjs
|
||||
import assert from 'assert/strict';
|
||||
import assert from 'node:assert/strict';
|
||||
|
||||
// Using `assert()` works the same:
|
||||
assert(0);
|
||||
@ -1880,7 +1880,7 @@ assert(0);
|
||||
```
|
||||
|
||||
```cjs
|
||||
const assert = require('assert');
|
||||
const assert = require('node:assert');
|
||||
|
||||
// Using `assert()` works the same:
|
||||
assert(0);
|
||||
@ -1921,7 +1921,7 @@ If specified, `message` will be the message provided by the [`AssertionError`][]
|
||||
if the `asyncFn` fails to reject.
|
||||
|
||||
```mjs
|
||||
import assert from 'assert/strict';
|
||||
import assert from 'node:assert/strict';
|
||||
|
||||
await assert.rejects(
|
||||
async () => {
|
||||
@ -1935,7 +1935,7 @@ await assert.rejects(
|
||||
```
|
||||
|
||||
```cjs
|
||||
const assert = require('assert/strict');
|
||||
const assert = require('node:assert/strict');
|
||||
|
||||
(async () => {
|
||||
await assert.rejects(
|
||||
@ -1951,7 +1951,7 @@ const assert = require('assert/strict');
|
||||
```
|
||||
|
||||
```mjs
|
||||
import assert from 'assert/strict';
|
||||
import assert from 'node:assert/strict';
|
||||
|
||||
await assert.rejects(
|
||||
async () => {
|
||||
@ -1966,7 +1966,7 @@ await assert.rejects(
|
||||
```
|
||||
|
||||
```cjs
|
||||
const assert = require('assert/strict');
|
||||
const assert = require('node:assert/strict');
|
||||
|
||||
(async () => {
|
||||
await assert.rejects(
|
||||
@ -1983,7 +1983,7 @@ const assert = require('assert/strict');
|
||||
```
|
||||
|
||||
```mjs
|
||||
import assert from 'assert/strict';
|
||||
import assert from 'node:assert/strict';
|
||||
|
||||
assert.rejects(
|
||||
Promise.reject(new Error('Wrong value')),
|
||||
@ -1994,7 +1994,7 @@ assert.rejects(
|
||||
```
|
||||
|
||||
```cjs
|
||||
const assert = require('assert/strict');
|
||||
const assert = require('node:assert/strict');
|
||||
|
||||
assert.rejects(
|
||||
Promise.reject(new Error('Wrong value')),
|
||||
@ -2028,7 +2028,7 @@ Tests strict equality between the `actual` and `expected` parameters as
|
||||
determined by [`Object.is()`][].
|
||||
|
||||
```mjs
|
||||
import assert from 'assert/strict';
|
||||
import assert from 'node:assert/strict';
|
||||
|
||||
assert.strictEqual(1, 2);
|
||||
// AssertionError [ERR_ASSERTION]: Expected inputs to be strictly equal:
|
||||
@ -2056,7 +2056,7 @@ assert.strictEqual(1, '1', new TypeError('Inputs are not identical'));
|
||||
```
|
||||
|
||||
```cjs
|
||||
const assert = require('assert/strict');
|
||||
const assert = require('node:assert/strict');
|
||||
|
||||
assert.strictEqual(1, 2);
|
||||
// AssertionError [ERR_ASSERTION]: Expected inputs to be strictly equal:
|
||||
@ -2126,7 +2126,7 @@ fails.
|
||||
Custom validation object/error instance:
|
||||
|
||||
```mjs
|
||||
import assert from 'assert/strict';
|
||||
import assert from 'node:assert/strict';
|
||||
|
||||
const err = new TypeError('Wrong value');
|
||||
err.code = 404;
|
||||
@ -2195,7 +2195,7 @@ throws(
|
||||
```
|
||||
|
||||
```cjs
|
||||
const assert = require('assert/strict');
|
||||
const assert = require('node:assert/strict');
|
||||
|
||||
const err = new TypeError('Wrong value');
|
||||
err.code = 404;
|
||||
@ -2266,7 +2266,7 @@ throws(
|
||||
Validate instanceof using constructor:
|
||||
|
||||
```mjs
|
||||
import assert from 'assert/strict';
|
||||
import assert from 'node:assert/strict';
|
||||
|
||||
assert.throws(
|
||||
() => {
|
||||
@ -2277,7 +2277,7 @@ assert.throws(
|
||||
```
|
||||
|
||||
```cjs
|
||||
const assert = require('assert/strict');
|
||||
const assert = require('node:assert/strict');
|
||||
|
||||
assert.throws(
|
||||
() => {
|
||||
@ -2293,7 +2293,7 @@ Using a regular expression runs `.toString` on the error object, and will
|
||||
therefore also include the error name.
|
||||
|
||||
```mjs
|
||||
import assert from 'assert/strict';
|
||||
import assert from 'node:assert/strict';
|
||||
|
||||
assert.throws(
|
||||
() => {
|
||||
@ -2304,7 +2304,7 @@ assert.throws(
|
||||
```
|
||||
|
||||
```cjs
|
||||
const assert = require('assert/strict');
|
||||
const assert = require('node:assert/strict');
|
||||
|
||||
assert.throws(
|
||||
() => {
|
||||
@ -2320,7 +2320,7 @@ The function must return `true` to indicate all internal validations passed.
|
||||
It will otherwise fail with an [`AssertionError`][].
|
||||
|
||||
```mjs
|
||||
import assert from 'assert/strict';
|
||||
import assert from 'node:assert/strict';
|
||||
|
||||
assert.throws(
|
||||
() => {
|
||||
@ -2341,7 +2341,7 @@ assert.throws(
|
||||
```
|
||||
|
||||
```cjs
|
||||
const assert = require('assert/strict');
|
||||
const assert = require('node:assert/strict');
|
||||
|
||||
assert.throws(
|
||||
() => {
|
||||
@ -2369,7 +2369,7 @@ message as the thrown error message is going to result in an
|
||||
a string as the second argument gets considered:
|
||||
|
||||
```mjs
|
||||
import assert from 'assert/strict';
|
||||
import assert from 'node:assert/strict';
|
||||
|
||||
function throwingFirst() {
|
||||
throw new Error('First');
|
||||
@ -2405,7 +2405,7 @@ assert.throws(throwingFirst, /Second$/);
|
||||
```
|
||||
|
||||
```cjs
|
||||
const assert = require('assert/strict');
|
||||
const assert = require('node:assert/strict');
|
||||
|
||||
function throwingFirst() {
|
||||
throw new Error('First');
|
||||
|
||||
@ -15,14 +15,14 @@ or any other asynchronous duration. It is similar to thread-local storage
|
||||
in other languages.
|
||||
|
||||
The `AsyncLocalStorage` and `AsyncResource` classes are part of the
|
||||
`async_hooks` module:
|
||||
`node:async_hooks` module:
|
||||
|
||||
```mjs
|
||||
import { AsyncLocalStorage, AsyncResource } from 'async_hooks';
|
||||
import { AsyncLocalStorage, AsyncResource } from 'node:async_hooks';
|
||||
```
|
||||
|
||||
```cjs
|
||||
const { AsyncLocalStorage, AsyncResource } = require('async_hooks');
|
||||
const { AsyncLocalStorage, AsyncResource } = require('node:async_hooks');
|
||||
```
|
||||
|
||||
## Class: `AsyncLocalStorage`
|
||||
@ -39,18 +39,18 @@ changes:
|
||||
|
||||
This class creates stores that stay coherent through asynchronous operations.
|
||||
|
||||
While you can create your own implementation on top of the `async_hooks` module,
|
||||
`AsyncLocalStorage` should be preferred as it is a performant and memory safe
|
||||
implementation that involves significant optimizations that are non-obvious to
|
||||
implement.
|
||||
While you can create your own implementation on top of the `node:async_hooks`
|
||||
module, `AsyncLocalStorage` should be preferred as it is a performant and memory
|
||||
safe implementation that involves significant optimizations that are non-obvious
|
||||
to implement.
|
||||
|
||||
The following example uses `AsyncLocalStorage` to build a simple logger
|
||||
that assigns IDs to incoming HTTP requests and includes them in messages
|
||||
logged within each request.
|
||||
|
||||
```mjs
|
||||
import http from 'http';
|
||||
import { AsyncLocalStorage } from 'async_hooks';
|
||||
import http from 'node:http';
|
||||
import { AsyncLocalStorage } from 'node:async_hooks';
|
||||
|
||||
const asyncLocalStorage = new AsyncLocalStorage();
|
||||
|
||||
@ -81,8 +81,8 @@ http.get('http://localhost:8080');
|
||||
```
|
||||
|
||||
```cjs
|
||||
const http = require('http');
|
||||
const { AsyncLocalStorage } = require('async_hooks');
|
||||
const http = require('node:http');
|
||||
const { AsyncLocalStorage } = require('node:async_hooks');
|
||||
|
||||
const asyncLocalStorage = new AsyncLocalStorage();
|
||||
|
||||
@ -348,7 +348,7 @@ The `init` hook will trigger when an `AsyncResource` is instantiated.
|
||||
The following is an overview of the `AsyncResource` API.
|
||||
|
||||
```mjs
|
||||
import { AsyncResource, executionAsyncId } from 'async_hooks';
|
||||
import { AsyncResource, executionAsyncId } from 'node:async_hooks';
|
||||
|
||||
// AsyncResource() is meant to be extended. Instantiating a
|
||||
// new AsyncResource() also triggers init. If triggerAsyncId is omitted then
|
||||
@ -376,7 +376,7 @@ asyncResource.triggerAsyncId();
|
||||
```
|
||||
|
||||
```cjs
|
||||
const { AsyncResource, executionAsyncId } = require('async_hooks');
|
||||
const { AsyncResource, executionAsyncId } = require('node:async_hooks');
|
||||
|
||||
// AsyncResource() is meant to be extended. Instantiating a
|
||||
// new AsyncResource() also triggers init. If triggerAsyncId is omitted then
|
||||
@ -535,14 +535,14 @@ Assuming that the task is adding two numbers, using a file named
|
||||
`task_processor.js` with the following content:
|
||||
|
||||
```mjs
|
||||
import { parentPort } from 'worker_threads';
|
||||
import { parentPort } from 'node:worker_threads';
|
||||
parentPort.on('message', (task) => {
|
||||
parentPort.postMessage(task.a + task.b);
|
||||
});
|
||||
```
|
||||
|
||||
```cjs
|
||||
const { parentPort } = require('worker_threads');
|
||||
const { parentPort } = require('node:worker_threads');
|
||||
parentPort.on('message', (task) => {
|
||||
parentPort.postMessage(task.a + task.b);
|
||||
});
|
||||
@ -551,10 +551,10 @@ parentPort.on('message', (task) => {
|
||||
a Worker pool around it could use the following structure:
|
||||
|
||||
```mjs
|
||||
import { AsyncResource } from 'async_hooks';
|
||||
import { EventEmitter } from 'events';
|
||||
import path from 'path';
|
||||
import { Worker } from 'worker_threads';
|
||||
import { AsyncResource } from 'node:async_hooks';
|
||||
import { EventEmitter } from 'node:events';
|
||||
import path from 'node:path';
|
||||
import { Worker } from 'node:worker_threads';
|
||||
|
||||
const kTaskInfo = Symbol('kTaskInfo');
|
||||
const kWorkerFreedEvent = Symbol('kWorkerFreedEvent');
|
||||
@ -639,10 +639,10 @@ export default class WorkerPool extends EventEmitter {
|
||||
```
|
||||
|
||||
```cjs
|
||||
const { AsyncResource } = require('async_hooks');
|
||||
const { EventEmitter } = require('events');
|
||||
const path = require('path');
|
||||
const { Worker } = require('worker_threads');
|
||||
const { AsyncResource } = require('node:async_hooks');
|
||||
const { EventEmitter } = require('node:events');
|
||||
const path = require('node:path');
|
||||
const { Worker } = require('node:worker_threads');
|
||||
|
||||
const kTaskInfo = Symbol('kTaskInfo');
|
||||
const kWorkerFreedEvent = Symbol('kWorkerFreedEvent');
|
||||
@ -738,7 +738,7 @@ This pool could be used as follows:
|
||||
|
||||
```mjs
|
||||
import WorkerPool from './worker_pool.js';
|
||||
import os from 'os';
|
||||
import os from 'node:os';
|
||||
|
||||
const pool = new WorkerPool(os.cpus().length);
|
||||
|
||||
@ -754,7 +754,7 @@ for (let i = 0; i < 10; i++) {
|
||||
|
||||
```cjs
|
||||
const WorkerPool = require('./worker_pool.js');
|
||||
const os = require('os');
|
||||
const os = require('node:os');
|
||||
|
||||
const pool = new WorkerPool(os.cpus().length);
|
||||
|
||||
@ -779,8 +779,8 @@ associate an event listener with the correct execution context. The same
|
||||
approach can be applied to a [`Stream`][] or a similar event-driven class.
|
||||
|
||||
```mjs
|
||||
import { createServer } from 'http';
|
||||
import { AsyncResource, executionAsyncId } from 'async_hooks';
|
||||
import { createServer } from 'node:http';
|
||||
import { AsyncResource, executionAsyncId } from 'node:async_hooks';
|
||||
|
||||
const server = createServer((req, res) => {
|
||||
req.on('close', AsyncResource.bind(() => {
|
||||
@ -794,8 +794,8 @@ const server = createServer((req, res) => {
|
||||
```
|
||||
|
||||
```cjs
|
||||
const { createServer } = require('http');
|
||||
const { AsyncResource, executionAsyncId } = require('async_hooks');
|
||||
const { createServer } = require('node:http');
|
||||
const { AsyncResource, executionAsyncId } = require('node:async_hooks');
|
||||
|
||||
const server = createServer((req, res) => {
|
||||
req.on('close', AsyncResource.bind(() => {
|
||||
|
||||
@ -6,15 +6,15 @@
|
||||
|
||||
<!-- source_link=lib/async_hooks.js -->
|
||||
|
||||
The `async_hooks` module provides an API to track asynchronous resources. It
|
||||
can be accessed using:
|
||||
The `node:async_hooks` module provides an API to track asynchronous resources.
|
||||
It can be accessed using:
|
||||
|
||||
```mjs
|
||||
import async_hooks from 'async_hooks';
|
||||
import async_hooks from 'node:async_hooks';
|
||||
```
|
||||
|
||||
```cjs
|
||||
const async_hooks = require('async_hooks');
|
||||
const async_hooks = require('node:async_hooks');
|
||||
```
|
||||
|
||||
## Terminology
|
||||
@ -34,7 +34,7 @@ interface, and each thread will use a new set of async IDs.
|
||||
Following is a simple overview of the public API.
|
||||
|
||||
```mjs
|
||||
import async_hooks from 'async_hooks';
|
||||
import async_hooks from 'node:async_hooks';
|
||||
|
||||
// Return the ID of the current execution context.
|
||||
const eid = async_hooks.executionAsyncId();
|
||||
@ -82,7 +82,7 @@ function promiseResolve(asyncId) { }
|
||||
```
|
||||
|
||||
```cjs
|
||||
const async_hooks = require('async_hooks');
|
||||
const async_hooks = require('node:async_hooks');
|
||||
|
||||
// Return the ID of the current execution context.
|
||||
const eid = async_hooks.executionAsyncId();
|
||||
@ -155,7 +155,7 @@ specifics of all functions that can be passed to `callbacks` is in the
|
||||
[Hook Callbacks][] section.
|
||||
|
||||
```mjs
|
||||
import { createHook } from 'async_hooks';
|
||||
import { createHook } from 'node:async_hooks';
|
||||
|
||||
const asyncHook = createHook({
|
||||
init(asyncId, type, triggerAsyncId, resource) { },
|
||||
@ -164,7 +164,7 @@ const asyncHook = createHook({
|
||||
```
|
||||
|
||||
```cjs
|
||||
const async_hooks = require('async_hooks');
|
||||
const async_hooks = require('node:async_hooks');
|
||||
|
||||
const asyncHook = async_hooks.createHook({
|
||||
init(asyncId, type, triggerAsyncId, resource) { },
|
||||
@ -220,8 +220,8 @@ This will print to the file and will not invoke `AsyncHook` recursively because
|
||||
it is synchronous.
|
||||
|
||||
```mjs
|
||||
import { writeFileSync } from 'fs';
|
||||
import { format } from 'util';
|
||||
import { writeFileSync } from 'node:fs';
|
||||
import { format } from 'node:util';
|
||||
|
||||
function debug(...args) {
|
||||
// Use a function like this one when debugging inside an AsyncHook callback
|
||||
@ -230,8 +230,8 @@ function debug(...args) {
|
||||
```
|
||||
|
||||
```cjs
|
||||
const fs = require('fs');
|
||||
const util = require('util');
|
||||
const fs = require('node:fs');
|
||||
const util = require('node:util');
|
||||
|
||||
function debug(...args) {
|
||||
// Use a function like this one when debugging inside an AsyncHook callback
|
||||
@ -261,13 +261,13 @@ The `AsyncHook` instance is disabled by default. If the `AsyncHook` instance
|
||||
should be enabled immediately after creation, the following pattern can be used.
|
||||
|
||||
```mjs
|
||||
import { createHook } from 'async_hooks';
|
||||
import { createHook } from 'node:async_hooks';
|
||||
|
||||
const hook = createHook(callbacks).enable();
|
||||
```
|
||||
|
||||
```cjs
|
||||
const async_hooks = require('async_hooks');
|
||||
const async_hooks = require('node:async_hooks');
|
||||
|
||||
const hook = async_hooks.createHook(callbacks).enable();
|
||||
```
|
||||
@ -307,7 +307,7 @@ closing it before the resource can be used. The following snippet demonstrates
|
||||
this.
|
||||
|
||||
```mjs
|
||||
import { createServer } from 'net';
|
||||
import { createServer } from 'node:net';
|
||||
|
||||
createServer().listen(function() { this.close(); });
|
||||
// OR
|
||||
@ -315,7 +315,7 @@ clearTimeout(setTimeout(() => {}, 10));
|
||||
```
|
||||
|
||||
```cjs
|
||||
require('net').createServer().listen(function() { this.close(); });
|
||||
require('node:net').createServer().listen(function() { this.close(); });
|
||||
// OR
|
||||
clearTimeout(setTimeout(() => {}, 10));
|
||||
```
|
||||
@ -361,9 +361,9 @@ created, while `triggerAsyncId` shows _why_ a resource was created.
|
||||
The following is a simple demonstration of `triggerAsyncId`:
|
||||
|
||||
```mjs
|
||||
import { createHook, executionAsyncId } from 'async_hooks';
|
||||
import { stdout } from 'process';
|
||||
import net from 'net';
|
||||
import { createHook, executionAsyncId } from 'node:async_hooks';
|
||||
import { stdout } from 'node:process';
|
||||
import net from 'node:net';
|
||||
|
||||
createHook({
|
||||
init(asyncId, type, triggerAsyncId) {
|
||||
@ -378,9 +378,9 @@ net.createServer((conn) => {}).listen(8080);
|
||||
```
|
||||
|
||||
```cjs
|
||||
const { createHook, executionAsyncId } = require('async_hooks');
|
||||
const { stdout } = require('process');
|
||||
const net = require('net');
|
||||
const { createHook, executionAsyncId } = require('node:async_hooks');
|
||||
const { stdout } = require('node:process');
|
||||
const net = require('node:net');
|
||||
|
||||
createHook({
|
||||
init(asyncId, type, triggerAsyncId) {
|
||||
@ -433,9 +433,9 @@ callback to `listen()` will look like. The output formatting is slightly more
|
||||
elaborate to make calling context easier to see.
|
||||
|
||||
```js
|
||||
const async_hooks = require('async_hooks');
|
||||
const fs = require('fs');
|
||||
const net = require('net');
|
||||
const async_hooks = require('node:async_hooks');
|
||||
const fs = require('node:fs');
|
||||
const net = require('node:net');
|
||||
const { fd } = process.stdout;
|
||||
|
||||
let indent = 0;
|
||||
@ -619,8 +619,8 @@ return an empty object as there is no handle or request object to use,
|
||||
but having an object representing the top-level can be helpful.
|
||||
|
||||
```mjs
|
||||
import { open } from 'fs';
|
||||
import { executionAsyncId, executionAsyncResource } from 'async_hooks';
|
||||
import { open } from 'node:fs';
|
||||
import { executionAsyncId, executionAsyncResource } from 'node:async_hooks';
|
||||
|
||||
console.log(executionAsyncId(), executionAsyncResource()); // 1 {}
|
||||
open(new URL(import.meta.url), 'r', (err, fd) => {
|
||||
@ -629,8 +629,8 @@ open(new URL(import.meta.url), 'r', (err, fd) => {
|
||||
```
|
||||
|
||||
```cjs
|
||||
const { open } = require('fs');
|
||||
const { executionAsyncId, executionAsyncResource } = require('async_hooks');
|
||||
const { open } = require('node:fs');
|
||||
const { executionAsyncId, executionAsyncResource } = require('node:async_hooks');
|
||||
|
||||
console.log(executionAsyncId(), executionAsyncResource()); // 1 {}
|
||||
open(__filename, 'r', (err, fd) => {
|
||||
@ -642,7 +642,7 @@ This can be used to implement continuation local storage without the
|
||||
use of a tracking `Map` to store the metadata:
|
||||
|
||||
```mjs
|
||||
import { createServer } from 'http';
|
||||
import { createServer } from 'node:http';
|
||||
import {
|
||||
executionAsyncId,
|
||||
executionAsyncResource,
|
||||
@ -668,12 +668,12 @@ const server = createServer((req, res) => {
|
||||
```
|
||||
|
||||
```cjs
|
||||
const { createServer } = require('http');
|
||||
const { createServer } = require('node:http');
|
||||
const {
|
||||
executionAsyncId,
|
||||
executionAsyncResource,
|
||||
createHook
|
||||
} = require('async_hooks');
|
||||
} = require('node:async_hooks');
|
||||
const sym = Symbol('state'); // Private symbol to avoid pollution
|
||||
|
||||
createHook({
|
||||
@ -707,7 +707,7 @@ changes:
|
||||
track when something calls.
|
||||
|
||||
```mjs
|
||||
import { executionAsyncId } from 'async_hooks';
|
||||
import { executionAsyncId } from 'node:async_hooks';
|
||||
|
||||
console.log(executionAsyncId()); // 1 - bootstrap
|
||||
fs.open(path, 'r', (err, fd) => {
|
||||
@ -716,7 +716,7 @@ fs.open(path, 'r', (err, fd) => {
|
||||
```
|
||||
|
||||
```cjs
|
||||
const async_hooks = require('async_hooks');
|
||||
const async_hooks = require('node:async_hooks');
|
||||
|
||||
console.log(async_hooks.executionAsyncId()); // 1 - bootstrap
|
||||
fs.open(path, 'r', (err, fd) => {
|
||||
@ -788,7 +788,7 @@ V8. This means that programs using promises or `async`/`await` will not get
|
||||
correct execution and trigger ids for promise callback contexts by default.
|
||||
|
||||
```mjs
|
||||
import { executionAsyncId, triggerAsyncId } from 'async_hooks';
|
||||
import { executionAsyncId, triggerAsyncId } from 'node:async_hooks';
|
||||
|
||||
Promise.resolve(1729).then(() => {
|
||||
console.log(`eid ${executionAsyncId()} tid ${triggerAsyncId()}`);
|
||||
@ -798,7 +798,7 @@ Promise.resolve(1729).then(() => {
|
||||
```
|
||||
|
||||
```cjs
|
||||
const { executionAsyncId, triggerAsyncId } = require('async_hooks');
|
||||
const { executionAsyncId, triggerAsyncId } = require('node:async_hooks');
|
||||
|
||||
Promise.resolve(1729).then(() => {
|
||||
console.log(`eid ${executionAsyncId()} tid ${triggerAsyncId()}`);
|
||||
@ -816,7 +816,7 @@ Installing async hooks via `async_hooks.createHook` enables promise execution
|
||||
tracking:
|
||||
|
||||
```mjs
|
||||
import { createHook, executionAsyncId, triggerAsyncId } from 'async_hooks';
|
||||
import { createHook, executionAsyncId, triggerAsyncId } from 'node:async_hooks';
|
||||
createHook({ init() {} }).enable(); // forces PromiseHooks to be enabled.
|
||||
Promise.resolve(1729).then(() => {
|
||||
console.log(`eid ${executionAsyncId()} tid ${triggerAsyncId()}`);
|
||||
@ -826,7 +826,7 @@ Promise.resolve(1729).then(() => {
|
||||
```
|
||||
|
||||
```cjs
|
||||
const { createHook, executionAsyncId, triggerAsyncId } = require('async_hooks');
|
||||
const { createHook, executionAsyncId, triggerAsyncId } = require('node:async_hooks');
|
||||
|
||||
createHook({ init() {} }).enable(); // forces PromiseHooks to be enabled.
|
||||
Promise.resolve(1729).then(() => {
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@ -6,12 +6,12 @@
|
||||
|
||||
<!-- source_link=lib/child_process.js -->
|
||||
|
||||
The `child_process` module provides the ability to spawn subprocesses in
|
||||
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
|
||||
is primarily provided by the [`child_process.spawn()`][] function:
|
||||
|
||||
```js
|
||||
const { spawn } = require('child_process');
|
||||
const { spawn } = require('node:child_process');
|
||||
const ls = spawn('ls', ['-lh', '/usr']);
|
||||
|
||||
ls.stdout.on('data', (data) => {
|
||||
@ -54,8 +54,8 @@ without blocking the Node.js event loop. The [`child_process.spawnSync()`][]
|
||||
function provides equivalent functionality in a synchronous manner that blocks
|
||||
the event loop until the spawned process either exits or is terminated.
|
||||
|
||||
For convenience, the `child_process` module provides a handful of synchronous
|
||||
and asynchronous alternatives to [`child_process.spawn()`][] and
|
||||
For convenience, the `node:child_process` module provides a handful of
|
||||
synchronous and asynchronous alternatives to [`child_process.spawn()`][] and
|
||||
[`child_process.spawnSync()`][]. Each of these alternatives are implemented on
|
||||
top of [`child_process.spawn()`][] or [`child_process.spawnSync()`][].
|
||||
|
||||
@ -110,7 +110,7 @@ spaces it needs to be quoted.
|
||||
|
||||
```js
|
||||
// On Windows Only...
|
||||
const { spawn } = require('child_process');
|
||||
const { spawn } = require('node:child_process');
|
||||
const bat = spawn('cmd.exe', ['/c', 'my.bat']);
|
||||
|
||||
bat.stdout.on('data', (data) => {
|
||||
@ -128,7 +128,7 @@ bat.on('exit', (code) => {
|
||||
|
||||
```js
|
||||
// OR...
|
||||
const { exec, spawn } = require('child_process');
|
||||
const { exec, spawn } = require('node:child_process');
|
||||
exec('my.bat', (err, stdout, stderr) => {
|
||||
if (err) {
|
||||
console.error(err);
|
||||
@ -198,7 +198,7 @@ directly by the shell and special characters (vary based on
|
||||
need to be dealt with accordingly:
|
||||
|
||||
```js
|
||||
const { exec } = require('child_process');
|
||||
const { exec } = require('node:child_process');
|
||||
|
||||
exec('"/path/to/test file/test.sh" arg1 arg2');
|
||||
// Double quotes are used so that the space in the path is not interpreted as
|
||||
@ -226,7 +226,7 @@ stderr output. If `encoding` is `'buffer'`, or an unrecognized character
|
||||
encoding, `Buffer` objects will be passed to the callback instead.
|
||||
|
||||
```js
|
||||
const { exec } = require('child_process');
|
||||
const { exec } = require('node:child_process');
|
||||
exec('cat *.js missing_file | wc -l', (error, stdout, stderr) => {
|
||||
if (error) {
|
||||
console.error(`exec error: ${error}`);
|
||||
@ -252,8 +252,8 @@ rejected promise is returned, with the same `error` object given in the
|
||||
callback, but with two additional properties `stdout` and `stderr`.
|
||||
|
||||
```js
|
||||
const util = require('util');
|
||||
const exec = util.promisify(require('child_process').exec);
|
||||
const util = require('node:util');
|
||||
const exec = util.promisify(require('node:child_process').exec);
|
||||
|
||||
async function lsExample() {
|
||||
const { stdout, stderr } = await exec('ls');
|
||||
@ -268,7 +268,7 @@ If the `signal` option is enabled, calling `.abort()` on the corresponding
|
||||
the error passed to the callback will be an `AbortError`:
|
||||
|
||||
```js
|
||||
const { exec } = require('child_process');
|
||||
const { exec } = require('node:child_process');
|
||||
const controller = new AbortController();
|
||||
const { signal } = controller;
|
||||
const child = exec('grep ssh', { signal }, (error) => {
|
||||
@ -338,7 +338,7 @@ not spawned, behaviors such as I/O redirection and file globbing are not
|
||||
supported.
|
||||
|
||||
```js
|
||||
const { execFile } = require('child_process');
|
||||
const { execFile } = require('node:child_process');
|
||||
const child = execFile('node', ['--version'], (error, stdout, stderr) => {
|
||||
if (error) {
|
||||
throw error;
|
||||
@ -362,8 +362,8 @@ rejected promise is returned, with the same `error` object given in the
|
||||
callback, but with two additional properties `stdout` and `stderr`.
|
||||
|
||||
```js
|
||||
const util = require('util');
|
||||
const execFile = util.promisify(require('child_process').execFile);
|
||||
const util = require('node:util');
|
||||
const execFile = util.promisify(require('node:child_process').execFile);
|
||||
async function getVersion() {
|
||||
const { stdout } = await execFile('node', ['--version']);
|
||||
console.log(stdout);
|
||||
@ -380,7 +380,7 @@ If the `signal` option is enabled, calling `.abort()` on the corresponding
|
||||
the error passed to the callback will be an `AbortError`:
|
||||
|
||||
```js
|
||||
const { execFile } = require('child_process');
|
||||
const { execFile } = require('node:child_process');
|
||||
const controller = new AbortController();
|
||||
const { signal } = controller;
|
||||
const child = execFile('node', ['--version'], { signal }, (error) => {
|
||||
@ -506,7 +506,7 @@ if (process.argv[2] === 'child') {
|
||||
console.log(`Hello from ${process.argv[2]}!`);
|
||||
}, 1_000);
|
||||
} else {
|
||||
const { fork } = require('child_process');
|
||||
const { fork } = require('node:child_process');
|
||||
const controller = new AbortController();
|
||||
const { signal } = controller;
|
||||
const child = fork(__filename, ['child'], { signal });
|
||||
@ -625,7 +625,7 @@ Example of running `ls -lh /usr`, capturing `stdout`, `stderr`, and the
|
||||
exit code:
|
||||
|
||||
```js
|
||||
const { spawn } = require('child_process');
|
||||
const { spawn } = require('node:child_process');
|
||||
const ls = spawn('ls', ['-lh', '/usr']);
|
||||
|
||||
ls.stdout.on('data', (data) => {
|
||||
@ -644,7 +644,7 @@ ls.on('close', (code) => {
|
||||
Example: A very elaborate way to run `ps ax | grep ssh`
|
||||
|
||||
```js
|
||||
const { spawn } = require('child_process');
|
||||
const { spawn } = require('node:child_process');
|
||||
const ps = spawn('ps', ['ax']);
|
||||
const grep = spawn('grep', ['ssh']);
|
||||
|
||||
@ -681,7 +681,7 @@ grep.on('close', (code) => {
|
||||
Example of checking for failed `spawn`:
|
||||
|
||||
```js
|
||||
const { spawn } = require('child_process');
|
||||
const { spawn } = require('node:child_process');
|
||||
const subprocess = spawn('bad_command');
|
||||
|
||||
subprocess.on('error', (err) => {
|
||||
@ -702,7 +702,7 @@ If the `signal` option is enabled, calling `.abort()` on the corresponding
|
||||
the error passed to the callback will be an `AbortError`:
|
||||
|
||||
```js
|
||||
const { spawn } = require('child_process');
|
||||
const { spawn } = require('node:child_process');
|
||||
const controller = new AbortController();
|
||||
const { signal } = controller;
|
||||
const grep = spawn('grep', ['ssh'], { signal });
|
||||
@ -745,7 +745,7 @@ Example of a long-running process, by detaching and also ignoring its parent
|
||||
`stdio` file descriptors, in order to ignore the parent's termination:
|
||||
|
||||
```js
|
||||
const { spawn } = require('child_process');
|
||||
const { spawn } = require('node:child_process');
|
||||
|
||||
const subprocess = spawn(process.argv[0], ['child_program.js'], {
|
||||
detached: true,
|
||||
@ -758,8 +758,8 @@ subprocess.unref();
|
||||
Alternatively one can redirect the child process' output into files:
|
||||
|
||||
```js
|
||||
const fs = require('fs');
|
||||
const { spawn } = require('child_process');
|
||||
const fs = require('node:fs');
|
||||
const { spawn } = require('node:child_process');
|
||||
const out = fs.openSync('./out.log', 'a');
|
||||
const err = fs.openSync('./out.log', 'a');
|
||||
|
||||
@ -853,7 +853,7 @@ pipes between the parent and child. The value is one of the following:
|
||||
default is `'ignore'`.
|
||||
|
||||
```js
|
||||
const { spawn } = require('child_process');
|
||||
const { spawn } = require('node:child_process');
|
||||
|
||||
// Child will use parent's stdios.
|
||||
spawn('prg', [], { stdio: 'inherit' });
|
||||
@ -1152,7 +1152,7 @@ streams. The `'close'` event will always emit after [`'exit'`][] was
|
||||
already emitted, or [`'error'`][] if the child failed to spawn.
|
||||
|
||||
```js
|
||||
const { spawn } = require('child_process');
|
||||
const { spawn } = require('node:child_process');
|
||||
const ls = spawn('ls', ['-lh', '/usr']);
|
||||
|
||||
ls.stdout.on('data', (data) => {
|
||||
@ -1348,7 +1348,7 @@ signal(7) for a list of available signals. This function returns `true` if
|
||||
kill(2) succeeds, and `false` otherwise.
|
||||
|
||||
```js
|
||||
const { spawn } = require('child_process');
|
||||
const { spawn } = require('node:child_process');
|
||||
const grep = spawn('grep', ['ssh']);
|
||||
|
||||
grep.on('close', (code, signal) => {
|
||||
@ -1382,7 +1382,7 @@ new process in a shell or with the use of the `shell` option of `ChildProcess`:
|
||||
|
||||
```js
|
||||
'use strict';
|
||||
const { spawn } = require('child_process');
|
||||
const { spawn } = require('node:child_process');
|
||||
|
||||
const subprocess = spawn(
|
||||
'sh',
|
||||
@ -1427,7 +1427,7 @@ fails to spawn due to errors, then the value is `undefined` and `error` is
|
||||
emitted.
|
||||
|
||||
```js
|
||||
const { spawn } = require('child_process');
|
||||
const { spawn } = require('node:child_process');
|
||||
const grep = spawn('grep', ['ssh']);
|
||||
|
||||
console.log(`Spawned child pid: ${grep.pid}`);
|
||||
@ -1445,7 +1445,7 @@ restore the removed reference count for the child process, forcing the parent
|
||||
to wait for the child to exit before exiting itself.
|
||||
|
||||
```js
|
||||
const { spawn } = require('child_process');
|
||||
const { spawn } = require('node:child_process');
|
||||
|
||||
const subprocess = spawn(process.argv[0], ['child_program.js'], {
|
||||
detached: true,
|
||||
@ -1495,7 +1495,7 @@ message might not be the same as what is originally sent.
|
||||
For example, in the parent script:
|
||||
|
||||
```js
|
||||
const cp = require('child_process');
|
||||
const cp = require('node:child_process');
|
||||
const n = cp.fork(`${__dirname}/sub.js`);
|
||||
|
||||
n.on('message', (m) => {
|
||||
@ -1553,10 +1553,10 @@ The `sendHandle` argument can be used, for instance, to pass the handle of
|
||||
a TCP server object to the child process as illustrated in the example below:
|
||||
|
||||
```js
|
||||
const subprocess = require('child_process').fork('subprocess.js');
|
||||
const subprocess = require('node:child_process').fork('subprocess.js');
|
||||
|
||||
// Open up the server object and send the handle.
|
||||
const server = require('net').createServer();
|
||||
const server = require('node:net').createServer();
|
||||
server.on('connection', (socket) => {
|
||||
socket.end('handled by parent');
|
||||
});
|
||||
@ -1580,11 +1580,11 @@ process.on('message', (m, server) => {
|
||||
Once the server is now shared between the parent and child, some connections
|
||||
can be handled by the parent and some by the child.
|
||||
|
||||
While the example above uses a server created using the `net` module, `dgram`
|
||||
module servers use exactly the same workflow with the exceptions of listening on
|
||||
a `'message'` event instead of `'connection'` and using `server.bind()` instead
|
||||
of `server.listen()`. This is, however, currently only supported on Unix
|
||||
platforms.
|
||||
While the example above uses a server created using the `node:net` module,
|
||||
`node:dgram` module servers use exactly the same workflow with the exceptions of
|
||||
listening on a `'message'` event instead of `'connection'` and using
|
||||
`server.bind()` instead of `server.listen()`. This is, however, currently only
|
||||
supported on Unix platforms.
|
||||
|
||||
#### Example: sending a socket object
|
||||
|
||||
@ -1593,13 +1593,13 @@ socket to the child process. The example below spawns two children that each
|
||||
handle connections with "normal" or "special" priority:
|
||||
|
||||
```js
|
||||
const { fork } = require('child_process');
|
||||
const { fork } = require('node:child_process');
|
||||
const normal = fork('subprocess.js', ['normal']);
|
||||
const special = fork('subprocess.js', ['special']);
|
||||
|
||||
// Open up the server and send sockets to child. Use pauseOnConnect to prevent
|
||||
// the sockets from being read before they are sent to the child process.
|
||||
const server = require('net').createServer({ pauseOnConnect: true });
|
||||
const server = require('node:net').createServer({ pauseOnConnect: true });
|
||||
server.on('connection', (socket) => {
|
||||
|
||||
// If this is special priority...
|
||||
@ -1724,9 +1724,9 @@ pipe, so only the parent's `subprocess.stdio[1]` is a stream, all other values
|
||||
in the array are `null`.
|
||||
|
||||
```js
|
||||
const assert = require('assert');
|
||||
const fs = require('fs');
|
||||
const child_process = require('child_process');
|
||||
const assert = require('node:assert');
|
||||
const fs = require('node:fs');
|
||||
const child_process = require('node:child_process');
|
||||
|
||||
const subprocess = child_process.spawn('ls', {
|
||||
stdio: [
|
||||
@ -1766,7 +1766,7 @@ then this will be `null`.
|
||||
refer to the same value.
|
||||
|
||||
```js
|
||||
const { spawn } = require('child_process');
|
||||
const { spawn } = require('node:child_process');
|
||||
|
||||
const subprocess = spawn('ls');
|
||||
|
||||
@ -1792,7 +1792,7 @@ independently of the child, unless there is an established IPC channel between
|
||||
the child and the parent.
|
||||
|
||||
```js
|
||||
const { spawn } = require('child_process');
|
||||
const { spawn } = require('node:child_process');
|
||||
|
||||
const subprocess = spawn(process.argv[0], ['child_program.js'], {
|
||||
detached: true,
|
||||
@ -1833,7 +1833,7 @@ added:
|
||||
-->
|
||||
|
||||
Child processes support a serialization mechanism for IPC that is based on the
|
||||
[serialization API of the `v8` module][v8.serdes], based on the
|
||||
[serialization API of the `node:v8` module][v8.serdes], based on the
|
||||
[HTML structured clone algorithm][]. This is generally more powerful and
|
||||
supports more built-in JavaScript object types, such as `BigInt`, `Map`
|
||||
and `Set`, `ArrayBuffer` and `TypedArray`, `Buffer`, `Error`, `RegExp` etc.
|
||||
|
||||
@ -98,7 +98,7 @@ analysis using a debugger (such as `lldb`, `gdb`, and `mdb`).
|
||||
|
||||
If this flag is passed, the behavior can still be set to not abort through
|
||||
[`process.setUncaughtExceptionCaptureCallback()`][] (and through usage of the
|
||||
`domain` module that uses it).
|
||||
`node:domain` module that uses it).
|
||||
|
||||
### `--completion-bash`
|
||||
|
||||
@ -226,7 +226,7 @@ added: v9.8.0
|
||||
|
||||
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
|
||||
`vm` module.
|
||||
`node:vm` module.
|
||||
|
||||
### `--dns-result-order=order`
|
||||
|
||||
@ -364,7 +364,7 @@ See [customizing ESM specifier resolution][] for example usage.
|
||||
added: v9.6.0
|
||||
-->
|
||||
|
||||
Enable experimental ES Module support in the `vm` module.
|
||||
Enable experimental ES Module support in the `node:vm` module.
|
||||
|
||||
### `--experimental-wasi-unstable-preview1`
|
||||
|
||||
|
||||
@ -15,10 +15,10 @@ The cluster module allows easy creation of child processes that all share
|
||||
server ports.
|
||||
|
||||
```mjs
|
||||
import cluster from 'cluster';
|
||||
import http from 'http';
|
||||
import { cpus } from 'os';
|
||||
import process from 'process';
|
||||
import cluster from 'node:cluster';
|
||||
import http from 'node:http';
|
||||
import { cpus } from 'node:os';
|
||||
import process from 'node:process';
|
||||
|
||||
const numCPUs = cpus().length;
|
||||
|
||||
@ -46,10 +46,10 @@ if (cluster.isPrimary) {
|
||||
```
|
||||
|
||||
```cjs
|
||||
const cluster = require('cluster');
|
||||
const http = require('http');
|
||||
const numCPUs = require('os').cpus().length;
|
||||
const process = require('process');
|
||||
const cluster = require('node:cluster');
|
||||
const http = require('node:http');
|
||||
const numCPUs = require('node:os').cpus().length;
|
||||
const process = require('node:process');
|
||||
|
||||
if (cluster.isPrimary) {
|
||||
console.log(`Primary ${process.pid} is running`);
|
||||
@ -143,7 +143,7 @@ will be dropped and new connections will be refused. Node.js does not
|
||||
automatically manage the number of workers, however. It is the application's
|
||||
responsibility to manage the worker pool based on its own needs.
|
||||
|
||||
Although a primary use case for the `cluster` module is networking, it can
|
||||
Although a primary use case for the `node:cluster` module is networking, it can
|
||||
also be used for other use cases requiring worker processes.
|
||||
|
||||
## Class: `Worker`
|
||||
@ -195,7 +195,7 @@ added: v0.11.2
|
||||
Similar to the `cluster.on('exit')` event, but specific to this worker.
|
||||
|
||||
```mjs
|
||||
import cluster from 'cluster';
|
||||
import cluster from 'node:cluster';
|
||||
|
||||
const worker = cluster.fork();
|
||||
worker.on('exit', (code, signal) => {
|
||||
@ -210,7 +210,7 @@ worker.on('exit', (code, signal) => {
|
||||
```
|
||||
|
||||
```cjs
|
||||
const cluster = require('cluster');
|
||||
const cluster = require('node:cluster');
|
||||
|
||||
const worker = cluster.fork();
|
||||
worker.on('exit', (code, signal) => {
|
||||
@ -235,7 +235,7 @@ added: v0.7.0
|
||||
Similar to the `cluster.on('listening')` event, but specific to this worker.
|
||||
|
||||
```mjs
|
||||
import cluster from 'cluster';
|
||||
import cluster from 'node:cluster';
|
||||
|
||||
cluster.fork().on('listening', (address) => {
|
||||
// Worker is listening
|
||||
@ -243,7 +243,7 @@ cluster.fork().on('listening', (address) => {
|
||||
```
|
||||
|
||||
```cjs
|
||||
const cluster = require('cluster');
|
||||
const cluster = require('node:cluster');
|
||||
|
||||
cluster.fork().on('listening', (address) => {
|
||||
// Worker is listening
|
||||
@ -271,10 +271,10 @@ Here is an example using the message system. It keeps a count in the primary
|
||||
process of the number of HTTP requests received by the workers:
|
||||
|
||||
```mjs
|
||||
import cluster from 'cluster';
|
||||
import http from 'http';
|
||||
import { cpus } from 'os';
|
||||
import process from 'process';
|
||||
import cluster from 'node:cluster';
|
||||
import http from 'node:http';
|
||||
import { cpus } from 'node:os';
|
||||
import process from 'node:process';
|
||||
|
||||
if (cluster.isPrimary) {
|
||||
|
||||
@ -315,9 +315,9 @@ if (cluster.isPrimary) {
|
||||
```
|
||||
|
||||
```cjs
|
||||
const cluster = require('cluster');
|
||||
const http = require('http');
|
||||
const process = require('process');
|
||||
const cluster = require('node:cluster');
|
||||
const http = require('node:http');
|
||||
const process = require('node:process');
|
||||
|
||||
if (cluster.isPrimary) {
|
||||
|
||||
@ -335,7 +335,7 @@ if (cluster.isPrimary) {
|
||||
}
|
||||
|
||||
// Start workers and listen for messages containing notifyRequest
|
||||
const numCPUs = require('os').cpus().length;
|
||||
const numCPUs = require('node:os').cpus().length;
|
||||
for (let i = 0; i < numCPUs; i++) {
|
||||
cluster.fork();
|
||||
}
|
||||
@ -429,7 +429,7 @@ if (cluster.isPrimary) {
|
||||
});
|
||||
|
||||
} else if (cluster.isWorker) {
|
||||
const net = require('net');
|
||||
const net = require('node:net');
|
||||
const server = net.createServer((socket) => {
|
||||
// Connections never end
|
||||
});
|
||||
@ -505,10 +505,10 @@ This function returns `true` if the worker's process has terminated (either
|
||||
because of exiting or being signaled). Otherwise, it returns `false`.
|
||||
|
||||
```mjs
|
||||
import cluster from 'cluster';
|
||||
import http from 'http';
|
||||
import { cpus } from 'os';
|
||||
import process from 'process';
|
||||
import cluster from 'node:cluster';
|
||||
import http from 'node:http';
|
||||
import { cpus } from 'node:os';
|
||||
import process from 'node:process';
|
||||
|
||||
const numCPUs = cpus().length;
|
||||
|
||||
@ -538,10 +538,10 @@ if (cluster.isPrimary) {
|
||||
```
|
||||
|
||||
```cjs
|
||||
const cluster = require('cluster');
|
||||
const http = require('http');
|
||||
const numCPUs = require('os').cpus().length;
|
||||
const process = require('process');
|
||||
const cluster = require('node:cluster');
|
||||
const http = require('node:http');
|
||||
const numCPUs = require('node:os').cpus().length;
|
||||
const process = require('node:process');
|
||||
|
||||
if (cluster.isPrimary) {
|
||||
console.log(`Primary ${process.pid} is running`);
|
||||
@ -982,7 +982,7 @@ The defaults above apply to the first call only; the defaults for later
|
||||
calls are the current values at the time of `cluster.setupPrimary()` is called.
|
||||
|
||||
```mjs
|
||||
import cluster from 'cluster';
|
||||
import cluster from 'node:cluster';
|
||||
|
||||
cluster.setupPrimary({
|
||||
exec: 'worker.js',
|
||||
@ -998,7 +998,7 @@ cluster.fork(); // http worker
|
||||
```
|
||||
|
||||
```cjs
|
||||
const cluster = require('cluster');
|
||||
const cluster = require('node:cluster');
|
||||
|
||||
cluster.setupPrimary({
|
||||
exec: 'worker.js',
|
||||
@ -1026,7 +1026,7 @@ added: v0.7.0
|
||||
A reference to the current worker object. Not available in the primary process.
|
||||
|
||||
```mjs
|
||||
import cluster from 'cluster';
|
||||
import cluster from 'node:cluster';
|
||||
|
||||
if (cluster.isPrimary) {
|
||||
console.log('I am primary');
|
||||
@ -1038,7 +1038,7 @@ if (cluster.isPrimary) {
|
||||
```
|
||||
|
||||
```cjs
|
||||
const cluster = require('cluster');
|
||||
const cluster = require('node:cluster');
|
||||
|
||||
if (cluster.isPrimary) {
|
||||
console.log('I am primary');
|
||||
@ -1067,7 +1067,7 @@ advance. However, it is guaranteed that the removal from the `cluster.workers`
|
||||
list happens before the last `'disconnect'` or `'exit'` event is emitted.
|
||||
|
||||
```mjs
|
||||
import cluster from 'cluster';
|
||||
import cluster from 'node:cluster';
|
||||
|
||||
for (const worker of Object.values(cluster.workers)) {
|
||||
worker.send('big announcement to all workers');
|
||||
@ -1075,7 +1075,7 @@ for (const worker of Object.values(cluster.workers)) {
|
||||
```
|
||||
|
||||
```cjs
|
||||
const cluster = require('cluster');
|
||||
const cluster = require('node:cluster');
|
||||
|
||||
for (const worker of Object.values(cluster.workers)) {
|
||||
worker.send('big announcement to all workers');
|
||||
|
||||
@ -6,8 +6,8 @@
|
||||
|
||||
<!-- source_link=lib/console.js -->
|
||||
|
||||
The `console` module provides a simple debugging console that is similar to the
|
||||
JavaScript console mechanism provided by web browsers.
|
||||
The `node:console` module provides a simple debugging console that is similar to
|
||||
the JavaScript console mechanism provided by web browsers.
|
||||
|
||||
The module exports two specific components:
|
||||
|
||||
@ -15,7 +15,7 @@ The module exports two specific components:
|
||||
`console.warn()` that can be used to write to any Node.js stream.
|
||||
* A global `console` instance configured to write to [`process.stdout`][] and
|
||||
[`process.stderr`][]. The global `console` can be used without calling
|
||||
`require('console')`.
|
||||
`require('node:console')`.
|
||||
|
||||
_**Warning**_: The global console object's methods are neither consistently
|
||||
synchronous like the browser APIs they resemble, nor are they consistently
|
||||
@ -77,11 +77,11 @@ changes:
|
||||
<!--type=class-->
|
||||
|
||||
The `Console` class can be used to create a simple logger with configurable
|
||||
output streams and can be accessed using either `require('console').Console`
|
||||
output streams and can be accessed using either `require('node:console').Console`
|
||||
or `console.Console` (or their destructured counterparts):
|
||||
|
||||
```js
|
||||
const { Console } = require('console');
|
||||
const { Console } = require('node:console');
|
||||
```
|
||||
|
||||
```js
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@ -217,7 +217,7 @@ provide an indication of how and why the `Worker` instance exited. In Node.js
|
||||
[`worker.exitedAfterDisconnect`][] property. The old property name did not
|
||||
precisely describe the actual semantics and was unnecessarily emotion-laden.
|
||||
|
||||
### DEP0008: `require('constants')`
|
||||
### DEP0008: `require('node:constants')`
|
||||
|
||||
<!-- YAML
|
||||
changes:
|
||||
@ -231,10 +231,10 @@ changes:
|
||||
|
||||
Type: Documentation-only
|
||||
|
||||
The `constants` module is deprecated. When requiring access to constants
|
||||
The `node:constants` module is deprecated. When requiring access to constants
|
||||
relevant to specific Node.js builtin modules, developers should instead refer
|
||||
to the `constants` property exposed by the relevant module. For instance,
|
||||
`require('fs').constants` and `require('os').constants`.
|
||||
`require('node:fs').constants` and `require('node:os').constants`.
|
||||
|
||||
### DEP0009: `crypto.pbkdf2` without digest
|
||||
|
||||
@ -581,7 +581,7 @@ Type: End-of-Life
|
||||
|
||||
The `REPLServer.prototype.convertToContext()` API has been removed.
|
||||
|
||||
### DEP0025: `require('sys')`
|
||||
### DEP0025: `require('node:sys')`
|
||||
|
||||
<!-- YAML
|
||||
changes:
|
||||
@ -597,7 +597,7 @@ changes:
|
||||
|
||||
Type: Runtime
|
||||
|
||||
The `sys` module is deprecated. Please use the [`util`][] module instead.
|
||||
The `node:sys` module is deprecated. Please use the [`util`][] module instead.
|
||||
|
||||
### DEP0026: `util.print()`
|
||||
|
||||
@ -717,7 +717,7 @@ Type: Documentation-only
|
||||
The [`ecdh.setPublicKey()`][] method is now deprecated as its inclusion in the
|
||||
API is not useful.
|
||||
|
||||
### DEP0032: `domain` module
|
||||
### DEP0032: `node:domain` module
|
||||
|
||||
<!-- YAML
|
||||
changes:
|
||||
@ -868,7 +868,7 @@ Type: Documentation-only
|
||||
|
||||
The [`require.extensions`][] property is deprecated.
|
||||
|
||||
### DEP0040: `punycode` module
|
||||
### DEP0040: `node:punycode` module
|
||||
|
||||
<!-- YAML
|
||||
changes:
|
||||
@ -1341,7 +1341,7 @@ changes:
|
||||
|
||||
Type: Documentation-only
|
||||
|
||||
The `http` module `ServerResponse.prototype.writeHeader()` API is
|
||||
The `node:http` module `ServerResponse.prototype.writeHeader()` API is
|
||||
deprecated. Please use `ServerResponse.prototype.writeHead()` instead.
|
||||
|
||||
The `ServerResponse.prototype.writeHeader()` method was never documented as an
|
||||
@ -1389,8 +1389,8 @@ changes:
|
||||
|
||||
Type: End-of-Life
|
||||
|
||||
The `repl` module's `REPL_MODE_MAGIC` constant, used for `replMode` option, has
|
||||
been removed. Its behavior has been functionally identical to that of
|
||||
The `node:repl` module's `REPL_MODE_MAGIC` constant, used for `replMode` option,
|
||||
has been removed. Its behavior has been functionally identical to that of
|
||||
`REPL_MODE_SLOPPY` since Node.js 6.0.0, when V8 5.0 was imported. Please use
|
||||
`REPL_MODE_SLOPPY` instead.
|
||||
|
||||
@ -1412,7 +1412,7 @@ changes:
|
||||
|
||||
Type: Runtime
|
||||
|
||||
The `http` module `OutgoingMessage.prototype._headers` and
|
||||
The `node:http` module `OutgoingMessage.prototype._headers` and
|
||||
`OutgoingMessage.prototype._headerNames` properties are deprecated. Use one of
|
||||
the public methods (e.g. `OutgoingMessage.prototype.getHeader()`,
|
||||
`OutgoingMessage.prototype.getHeaders()`,
|
||||
@ -1437,7 +1437,7 @@ changes:
|
||||
|
||||
Type: Documentation-only
|
||||
|
||||
The `http` module `OutgoingMessage.prototype._renderHeaders()` API is
|
||||
The `node:http` module `OutgoingMessage.prototype._renderHeaders()` API is
|
||||
deprecated.
|
||||
|
||||
The `OutgoingMessage.prototype._renderHeaders` property was never documented as
|
||||
@ -1819,7 +1819,7 @@ cause a lot of issues. See <https://github.com/nodejs/node/issues/14328>.
|
||||
|
||||
<!-- md-lint skip-deprecation DEP0088 -->
|
||||
|
||||
### DEP0089: `require('assert')`
|
||||
### DEP0089: `require('node:assert')`
|
||||
|
||||
<!-- YAML
|
||||
changes:
|
||||
@ -1836,8 +1836,9 @@ changes:
|
||||
Type: Deprecation revoked
|
||||
|
||||
Importing assert directly was not recommended as the exposed functions use
|
||||
loose equality checks. The deprecation was revoked because use of the `assert`
|
||||
module is not discouraged, and the deprecation caused developer confusion.
|
||||
loose equality checks. The deprecation was revoked because use of the
|
||||
`node:assert` module is not discouraged, and the deprecation caused developer
|
||||
confusion.
|
||||
|
||||
### DEP0090: Invalid GCM authentication tag lengths
|
||||
|
||||
@ -1913,7 +1914,7 @@ changes:
|
||||
Type: Runtime
|
||||
|
||||
Using `assert.fail()` with more than one argument is deprecated. Use
|
||||
`assert.fail()` with only one argument or use a different `assert` module
|
||||
`assert.fail()` with only one argument or use a different `node:assert` module
|
||||
method.
|
||||
|
||||
### DEP0095: `timers.enroll()`
|
||||
@ -2218,8 +2219,8 @@ changes:
|
||||
|
||||
Type: Runtime
|
||||
|
||||
The `dgram` module previously contained several APIs that were never meant to
|
||||
accessed outside of Node.js core: `Socket.prototype._handle`,
|
||||
The `node:dgram` module previously contained several APIs that were never meant
|
||||
to accessed outside of Node.js core: `Socket.prototype._handle`,
|
||||
`Socket.prototype._receiving`, `Socket.prototype._bindState`,
|
||||
`Socket.prototype._queue`, `Socket.prototype._reuseAddr`,
|
||||
`Socket.prototype._healthCheck()`, `Socket.prototype._stopReceiving()`, and
|
||||
@ -2385,9 +2386,9 @@ changes:
|
||||
Type: Runtime
|
||||
|
||||
The undocumented `net._setSimultaneousAccepts()` function was originally
|
||||
intended for debugging and performance tuning when using the `child_process`
|
||||
and `cluster` modules on Windows. The function is not generally useful and
|
||||
is being removed. See discussion here:
|
||||
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>
|
||||
|
||||
### DEP0122: `tls` `Server.prototype.setOptions()`
|
||||
@ -2433,7 +2434,7 @@ Type: End-of-Life
|
||||
|
||||
This property is a reference to the instance itself.
|
||||
|
||||
### DEP0125: `require('_stream_wrap')`
|
||||
### DEP0125: `require('node:_stream_wrap')`
|
||||
|
||||
<!-- YAML
|
||||
changes:
|
||||
@ -2444,7 +2445,7 @@ changes:
|
||||
|
||||
Type: Runtime
|
||||
|
||||
The `_stream_wrap` module is deprecated.
|
||||
The `node:_stream_wrap` module is deprecated.
|
||||
|
||||
### DEP0126: `timers.active()`
|
||||
|
||||
@ -2656,7 +2657,7 @@ Please ensure that all `fs.FileHandle` objects are explicitly closed using
|
||||
`FileHandle.prototype.close()` when the `fs.FileHandle` is no longer needed:
|
||||
|
||||
```js
|
||||
const fsPromises = require('fs').promises;
|
||||
const fsPromises = require('node:fs').promises;
|
||||
async function openAndClose() {
|
||||
let filehandle;
|
||||
try {
|
||||
@ -2730,7 +2731,7 @@ changes:
|
||||
|
||||
Type: Documentation-only (supports [`--pending-deprecation`][])
|
||||
|
||||
The `repl` module exported the input and output stream twice. Use `.input`
|
||||
The `node:repl` module exported the input and output stream twice. Use `.input`
|
||||
instead of `.inputStream` and `.output` instead of `.outputStream`.
|
||||
|
||||
### DEP0142: `repl._builtinLibs`
|
||||
@ -2744,9 +2745,9 @@ changes:
|
||||
|
||||
Type: Documentation-only
|
||||
|
||||
The `repl` module exports a `_builtinLibs` property that contains an array with
|
||||
native modules. It was incomplete so far and instead it's better to rely upon
|
||||
`require('module').builtinModules`.
|
||||
The `node:repl` module exports a `_builtinLibs` property that contains an array
|
||||
with native modules. It was incomplete so far and instead it's better to rely
|
||||
upon `require('node:module').builtinModules`.
|
||||
|
||||
### DEP0143: `Transform._transformState`
|
||||
|
||||
|
||||
@ -8,10 +8,10 @@
|
||||
|
||||
<!-- source_link=lib/dgram.js -->
|
||||
|
||||
The `dgram` module provides an implementation of UDP datagram sockets.
|
||||
The `node:dgram` module provides an implementation of UDP datagram sockets.
|
||||
|
||||
```mjs
|
||||
import dgram from 'dgram';
|
||||
import dgram from 'node:dgram';
|
||||
|
||||
const server = dgram.createSocket('udp4');
|
||||
|
||||
@ -34,7 +34,7 @@ server.bind(41234);
|
||||
```
|
||||
|
||||
```cjs
|
||||
const dgram = require('dgram');
|
||||
const dgram = require('node:dgram');
|
||||
const server = dgram.createSocket('udp4');
|
||||
|
||||
server.on('error', (err) => {
|
||||
@ -154,8 +154,8 @@ When sharing a UDP socket across multiple `cluster` workers, the
|
||||
`EADDRINUSE` error will occur:
|
||||
|
||||
```mjs
|
||||
import cluster from 'cluster';
|
||||
import dgram from 'dgram';
|
||||
import cluster from 'node:cluster';
|
||||
import dgram from 'node:dgram';
|
||||
|
||||
if (cluster.isPrimary) {
|
||||
cluster.fork(); // Works ok.
|
||||
@ -169,8 +169,8 @@ if (cluster.isPrimary) {
|
||||
```
|
||||
|
||||
```cjs
|
||||
const cluster = require('cluster');
|
||||
const dgram = require('dgram');
|
||||
const cluster = require('node:cluster');
|
||||
const dgram = require('node:dgram');
|
||||
|
||||
if (cluster.isPrimary) {
|
||||
cluster.fork(); // Works ok.
|
||||
@ -256,7 +256,7 @@ attempting to bind with a closed socket), an [`Error`][] may be thrown.
|
||||
Example of a UDP server listening on port 41234:
|
||||
|
||||
```mjs
|
||||
import dgram from 'dgram';
|
||||
import dgram from 'node:dgram';
|
||||
|
||||
const server = dgram.createSocket('udp4');
|
||||
|
||||
@ -279,7 +279,7 @@ server.bind(41234);
|
||||
```
|
||||
|
||||
```cjs
|
||||
const dgram = require('dgram');
|
||||
const dgram = require('node:dgram');
|
||||
const server = dgram.createSocket('udp4');
|
||||
|
||||
server.on('error', (err) => {
|
||||
@ -569,8 +569,8 @@ This method throws [`ERR_SOCKET_BAD_PORT`][] if called on an unbound socket.
|
||||
Example of sending a UDP packet to a port on `localhost`;
|
||||
|
||||
```mjs
|
||||
import dgram from 'dgram';
|
||||
import { Buffer } from 'buffer';
|
||||
import dgram from 'node:dgram';
|
||||
import { Buffer } from 'node:buffer';
|
||||
|
||||
const message = Buffer.from('Some bytes');
|
||||
const client = dgram.createSocket('udp4');
|
||||
@ -580,8 +580,8 @@ client.send(message, 41234, 'localhost', (err) => {
|
||||
```
|
||||
|
||||
```cjs
|
||||
const dgram = require('dgram');
|
||||
const { Buffer } = require('buffer');
|
||||
const dgram = require('node:dgram');
|
||||
const { Buffer } = require('node:buffer');
|
||||
|
||||
const message = Buffer.from('Some bytes');
|
||||
const client = dgram.createSocket('udp4');
|
||||
@ -594,8 +594,8 @@ Example of sending a UDP packet composed of multiple buffers to a port on
|
||||
`127.0.0.1`;
|
||||
|
||||
```mjs
|
||||
import dgram from 'dgram';
|
||||
import { Buffer } from 'buffer';
|
||||
import dgram from 'node:dgram';
|
||||
import { Buffer } from 'node:buffer';
|
||||
|
||||
const buf1 = Buffer.from('Some ');
|
||||
const buf2 = Buffer.from('bytes');
|
||||
@ -606,8 +606,8 @@ client.send([buf1, buf2], 41234, (err) => {
|
||||
```
|
||||
|
||||
```cjs
|
||||
const dgram = require('dgram');
|
||||
const { Buffer } = require('buffer');
|
||||
const dgram = require('node:dgram');
|
||||
const { Buffer } = require('node:buffer');
|
||||
|
||||
const buf1 = Buffer.from('Some ');
|
||||
const buf2 = Buffer.from('bytes');
|
||||
@ -626,8 +626,8 @@ Example of sending a UDP packet using a socket connected to a port on
|
||||
`localhost`:
|
||||
|
||||
```mjs
|
||||
import dgram from 'dgram';
|
||||
import { Buffer } from 'buffer';
|
||||
import dgram from 'node:dgram';
|
||||
import { Buffer } from 'node:buffer';
|
||||
|
||||
const message = Buffer.from('Some bytes');
|
||||
const client = dgram.createSocket('udp4');
|
||||
@ -639,8 +639,8 @@ client.connect(41234, 'localhost', (err) => {
|
||||
```
|
||||
|
||||
```cjs
|
||||
const dgram = require('dgram');
|
||||
const { Buffer } = require('buffer');
|
||||
const dgram = require('node:dgram');
|
||||
const { Buffer } = require('node:buffer');
|
||||
|
||||
const message = Buffer.from('Some bytes');
|
||||
const client = dgram.createSocket('udp4');
|
||||
@ -868,7 +868,7 @@ 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.
|
||||
|
||||
## `dgram` module functions
|
||||
## `node:dgram` module functions
|
||||
|
||||
### `dgram.createSocket(options[, callback])`
|
||||
|
||||
|
||||
@ -6,17 +6,17 @@
|
||||
|
||||
<!-- source_link=lib/diagnostics_channel.js -->
|
||||
|
||||
The `diagnostics_channel` module provides an API to create named channels
|
||||
The `node:diagnostics_channel` module provides an API to create named channels
|
||||
to report arbitrary message data for diagnostics purposes.
|
||||
|
||||
It can be accessed using:
|
||||
|
||||
```mjs
|
||||
import diagnostics_channel from 'diagnostics_channel';
|
||||
import diagnostics_channel from 'node:diagnostics_channel';
|
||||
```
|
||||
|
||||
```cjs
|
||||
const diagnostics_channel = require('diagnostics_channel');
|
||||
const diagnostics_channel = require('node:diagnostics_channel');
|
||||
```
|
||||
|
||||
It is intended that a module writer wanting to report diagnostics messages
|
||||
@ -38,7 +38,7 @@ other modules.
|
||||
Following is a simple overview of the public API.
|
||||
|
||||
```mjs
|
||||
import diagnostics_channel from 'diagnostics_channel';
|
||||
import diagnostics_channel from 'node:diagnostics_channel';
|
||||
|
||||
// Get a reusable channel object
|
||||
const channel = diagnostics_channel.channel('my-channel');
|
||||
@ -58,7 +58,7 @@ if (channel.hasSubscribers) {
|
||||
```
|
||||
|
||||
```cjs
|
||||
const diagnostics_channel = require('diagnostics_channel');
|
||||
const diagnostics_channel = require('node:diagnostics_channel');
|
||||
|
||||
// Get a reusable channel object
|
||||
const channel = diagnostics_channel.channel('my-channel');
|
||||
@ -95,7 +95,7 @@ This API is optional but helpful when trying to publish messages from very
|
||||
performance-sensitive code.
|
||||
|
||||
```mjs
|
||||
import diagnostics_channel from 'diagnostics_channel';
|
||||
import diagnostics_channel from 'node:diagnostics_channel';
|
||||
|
||||
if (diagnostics_channel.hasSubscribers('my-channel')) {
|
||||
// There are subscribers, prepare and publish message
|
||||
@ -103,7 +103,7 @@ if (diagnostics_channel.hasSubscribers('my-channel')) {
|
||||
```
|
||||
|
||||
```cjs
|
||||
const diagnostics_channel = require('diagnostics_channel');
|
||||
const diagnostics_channel = require('node:diagnostics_channel');
|
||||
|
||||
if (diagnostics_channel.hasSubscribers('my-channel')) {
|
||||
// There are subscribers, prepare and publish message
|
||||
@ -126,13 +126,13 @@ channel. It produces a channel object which is optimized to reduce overhead at
|
||||
publish time as much as possible.
|
||||
|
||||
```mjs
|
||||
import diagnostics_channel from 'diagnostics_channel';
|
||||
import diagnostics_channel from 'node:diagnostics_channel';
|
||||
|
||||
const channel = diagnostics_channel.channel('my-channel');
|
||||
```
|
||||
|
||||
```cjs
|
||||
const diagnostics_channel = require('diagnostics_channel');
|
||||
const diagnostics_channel = require('node:diagnostics_channel');
|
||||
|
||||
const channel = diagnostics_channel.channel('my-channel');
|
||||
```
|
||||
@ -170,7 +170,7 @@ This API is optional but helpful when trying to publish messages from very
|
||||
performance-sensitive code.
|
||||
|
||||
```mjs
|
||||
import diagnostics_channel from 'diagnostics_channel';
|
||||
import diagnostics_channel from 'node:diagnostics_channel';
|
||||
|
||||
const channel = diagnostics_channel.channel('my-channel');
|
||||
|
||||
@ -180,7 +180,7 @@ if (channel.hasSubscribers) {
|
||||
```
|
||||
|
||||
```cjs
|
||||
const diagnostics_channel = require('diagnostics_channel');
|
||||
const diagnostics_channel = require('node:diagnostics_channel');
|
||||
|
||||
const channel = diagnostics_channel.channel('my-channel');
|
||||
|
||||
@ -203,7 +203,7 @@ Publish a message to any subscribers to the channel. This will trigger
|
||||
message handlers synchronously so they will execute within the same context.
|
||||
|
||||
```mjs
|
||||
import diagnostics_channel from 'diagnostics_channel';
|
||||
import diagnostics_channel from 'node:diagnostics_channel';
|
||||
|
||||
const channel = diagnostics_channel.channel('my-channel');
|
||||
|
||||
@ -213,7 +213,7 @@ channel.publish({
|
||||
```
|
||||
|
||||
```cjs
|
||||
const diagnostics_channel = require('diagnostics_channel');
|
||||
const diagnostics_channel = require('node:diagnostics_channel');
|
||||
|
||||
const channel = diagnostics_channel.channel('my-channel');
|
||||
|
||||
@ -239,7 +239,7 @@ will be run synchronously whenever a message is published to the channel. Any
|
||||
errors thrown in the message handler will trigger an [`'uncaughtException'`][].
|
||||
|
||||
```mjs
|
||||
import diagnostics_channel from 'diagnostics_channel';
|
||||
import diagnostics_channel from 'node:diagnostics_channel';
|
||||
|
||||
const channel = diagnostics_channel.channel('my-channel');
|
||||
|
||||
@ -249,7 +249,7 @@ channel.subscribe((message, name) => {
|
||||
```
|
||||
|
||||
```cjs
|
||||
const diagnostics_channel = require('diagnostics_channel');
|
||||
const diagnostics_channel = require('node:diagnostics_channel');
|
||||
|
||||
const channel = diagnostics_channel.channel('my-channel');
|
||||
|
||||
@ -280,7 +280,7 @@ Remove a message handler previously registered to this channel with
|
||||
[`channel.subscribe(onMessage)`][].
|
||||
|
||||
```mjs
|
||||
import diagnostics_channel from 'diagnostics_channel';
|
||||
import diagnostics_channel from 'node:diagnostics_channel';
|
||||
|
||||
const channel = diagnostics_channel.channel('my-channel');
|
||||
|
||||
@ -294,7 +294,7 @@ channel.unsubscribe(onMessage);
|
||||
```
|
||||
|
||||
```cjs
|
||||
const diagnostics_channel = require('diagnostics_channel');
|
||||
const diagnostics_channel = require('node:diagnostics_channel');
|
||||
|
||||
const channel = diagnostics_channel.channel('my-channel');
|
||||
|
||||
|
||||
@ -6,7 +6,7 @@
|
||||
|
||||
<!-- source_link=lib/dns.js -->
|
||||
|
||||
The `dns` module enables name resolution. For example, use it to look up IP
|
||||
The `node:dns` module enables name resolution. For example, use it to look up IP
|
||||
addresses of host names.
|
||||
|
||||
Although named for the [Domain Name System (DNS)][], it does not always use the
|
||||
@ -16,7 +16,7 @@ communication. To perform name resolution the way other applications on the same
|
||||
system do, use [`dns.lookup()`][].
|
||||
|
||||
```js
|
||||
const dns = require('dns');
|
||||
const dns = require('node:dns');
|
||||
|
||||
dns.lookup('example.org', (err, address, family) => {
|
||||
console.log('address: %j family: IPv%s', address, family);
|
||||
@ -24,14 +24,14 @@ dns.lookup('example.org', (err, address, family) => {
|
||||
// address: "93.184.216.34" family: IPv4
|
||||
```
|
||||
|
||||
All other functions in the `dns` module connect to an actual DNS server to
|
||||
All other functions in the `node:dns` module connect to an actual DNS server to
|
||||
perform name resolution. They will always use the network to perform DNS
|
||||
queries. These functions do not use the same set of configuration files used by
|
||||
[`dns.lookup()`][] (e.g. `/etc/hosts`). Use these functions to always perform
|
||||
DNS queries, bypassing other name-resolution facilities.
|
||||
|
||||
```js
|
||||
const dns = require('dns');
|
||||
const dns = require('node:dns');
|
||||
|
||||
dns.resolve4('archive.org', (err, addresses) => {
|
||||
if (err) throw err;
|
||||
@ -65,7 +65,7 @@ the servers used for a resolver using
|
||||
other resolvers:
|
||||
|
||||
```js
|
||||
const { Resolver } = require('dns');
|
||||
const { Resolver } = require('node:dns');
|
||||
const resolver = new Resolver();
|
||||
resolver.setServers(['4.4.4.4']);
|
||||
|
||||
@ -75,7 +75,7 @@ resolver.resolve4('example.org', (err, addresses) => {
|
||||
});
|
||||
```
|
||||
|
||||
The following methods from the `dns` module are available:
|
||||
The following methods from the `node:dns` module are available:
|
||||
|
||||
* [`resolver.getServers()`][`dns.getServers()`]
|
||||
* [`resolver.resolve()`][`dns.resolve()`]
|
||||
@ -241,7 +241,7 @@ time to consult the [Implementation considerations section][] before using
|
||||
Example usage:
|
||||
|
||||
```js
|
||||
const dns = require('dns');
|
||||
const dns = require('node:dns');
|
||||
const options = {
|
||||
family: 6,
|
||||
hints: dns.ADDRCONFIG | dns.V4MAPPED,
|
||||
@ -312,7 +312,7 @@ will be thrown.
|
||||
On an error, `err` is an [`Error`][] object, where `err.code` is the error code.
|
||||
|
||||
```js
|
||||
const dns = require('dns');
|
||||
const dns = require('node:dns');
|
||||
dns.lookupService('127.0.0.1', 22, (err, hostname, service) => {
|
||||
console.log(hostname, service);
|
||||
// Prints: localhost ssh
|
||||
@ -826,7 +826,7 @@ added: v10.6.0
|
||||
changes:
|
||||
- version: v15.0.0
|
||||
pr-url: https://github.com/nodejs/node/pull/32953
|
||||
description: Exposed as `require('dns/promises')`.
|
||||
description: Exposed as `require('node:dns/promises')`.
|
||||
- version:
|
||||
- v11.14.0
|
||||
- v10.17.0
|
||||
@ -836,7 +836,7 @@ changes:
|
||||
|
||||
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('dns').promises` or `require('dns/promises')`.
|
||||
via `require('node:dns').promises` or `require('node:dns/promises')`.
|
||||
|
||||
### Class: `dnsPromises.Resolver`
|
||||
|
||||
@ -852,7 +852,7 @@ the servers used for a resolver using
|
||||
other resolvers:
|
||||
|
||||
```js
|
||||
const { Resolver } = require('dns').promises;
|
||||
const { Resolver } = require('node:dns').promises;
|
||||
const resolver = new Resolver();
|
||||
resolver.setServers(['4.4.4.4']);
|
||||
|
||||
@ -967,7 +967,7 @@ using `dnsPromises.lookup()`.
|
||||
Example usage:
|
||||
|
||||
```js
|
||||
const dns = require('dns');
|
||||
const dns = require('node:dns');
|
||||
const dnsPromises = dns.promises;
|
||||
const options = {
|
||||
family: 6,
|
||||
@ -1007,7 +1007,7 @@ On error, the `Promise` is rejected with an [`Error`][] object, where `err.code`
|
||||
is the error code.
|
||||
|
||||
```js
|
||||
const dnsPromises = require('dns').promises;
|
||||
const dnsPromises = require('node:dns').promises;
|
||||
dnsPromises.lookupService('127.0.0.1', 22).then((result) => {
|
||||
console.log(result.hostname, result.service);
|
||||
// Prints: localhost ssh
|
||||
|
||||
@ -66,7 +66,7 @@ For example, this is not a good idea:
|
||||
```js
|
||||
// XXX WARNING! BAD IDEA!
|
||||
|
||||
const d = require('domain').create();
|
||||
const d = require('node:domain').create();
|
||||
d.on('error', (er) => {
|
||||
// The error won't crash the process, but what it does is worse!
|
||||
// Though we've prevented abrupt process restarting, we are leaking
|
||||
@ -75,7 +75,7 @@ d.on('error', (er) => {
|
||||
console.log(`error, but oh well ${er.message}`);
|
||||
});
|
||||
d.run(() => {
|
||||
require('http').createServer((req, res) => {
|
||||
require('node:http').createServer((req, res) => {
|
||||
handleRequest(req, res);
|
||||
}).listen(PORT);
|
||||
});
|
||||
@ -88,7 +88,7 @@ appropriately, and handle errors with much greater safety.
|
||||
```js
|
||||
// Much better!
|
||||
|
||||
const cluster = require('cluster');
|
||||
const cluster = require('node:cluster');
|
||||
const PORT = +process.env.PORT || 1337;
|
||||
|
||||
if (cluster.isPrimary) {
|
||||
@ -117,12 +117,12 @@ if (cluster.isPrimary) {
|
||||
//
|
||||
// This is where we put our bugs!
|
||||
|
||||
const domain = require('domain');
|
||||
const domain = require('node:domain');
|
||||
|
||||
// See the cluster documentation for more details about using
|
||||
// worker processes to serve requests. How it works, caveats, etc.
|
||||
|
||||
const server = require('http').createServer((req, res) => {
|
||||
const server = require('node:http').createServer((req, res) => {
|
||||
const d = domain.create();
|
||||
d.on('error', (er) => {
|
||||
console.error(`error ${er.stack}`);
|
||||
@ -246,8 +246,8 @@ That is possible via explicit binding.
|
||||
|
||||
```js
|
||||
// Create a top-level domain for the server
|
||||
const domain = require('domain');
|
||||
const http = require('http');
|
||||
const domain = require('node:domain');
|
||||
const http = require('node:http');
|
||||
const serverDomain = domain.create();
|
||||
|
||||
serverDomain.run(() => {
|
||||
@ -416,8 +416,8 @@ the function.
|
||||
This is the most basic way to use a domain.
|
||||
|
||||
```js
|
||||
const domain = require('domain');
|
||||
const fs = require('fs');
|
||||
const domain = require('node:domain');
|
||||
const fs = require('node:fs');
|
||||
const d = domain.create();
|
||||
d.on('error', (er) => {
|
||||
console.error('Caught error!', er);
|
||||
|
||||
@ -141,9 +141,9 @@ int RunNodeInstance(MultiIsolatePlatform* platform,
|
||||
MaybeLocal<Value> loadenv_ret = node::LoadEnvironment(
|
||||
env,
|
||||
"const publicRequire ="
|
||||
" require('module').createRequire(process.cwd() + '/');"
|
||||
" require('node:module').createRequire(process.cwd() + '/');"
|
||||
"globalThis.require = publicRequire;"
|
||||
"require('vm').runInThisContext(process.argv[1]);");
|
||||
"require('node:vm').runInThisContext(process.argv[1]);");
|
||||
|
||||
if (loadenv_ret.IsEmpty()) // There has been a JS exception.
|
||||
return 1;
|
||||
|
||||
@ -15,7 +15,7 @@ errors:
|
||||
* User-specified errors triggered by application code.
|
||||
* `AssertionError`s are a special class of error that can be triggered when
|
||||
Node.js detects an exceptional logic violation that should never occur. These
|
||||
are raised typically by the `assert` module.
|
||||
are raised typically by the `node:assert` module.
|
||||
|
||||
All JavaScript and system errors raised by Node.js inherit from, or are
|
||||
instances of, the standard JavaScript {Error} class and are guaranteed
|
||||
@ -63,7 +63,7 @@ Errors that occur within _Asynchronous APIs_ may be reported in multiple ways:
|
||||
<!-- eslint-disable no-useless-return -->
|
||||
|
||||
```js
|
||||
const fs = require('fs');
|
||||
const fs = require('node:fs');
|
||||
fs.readFile('a file that does not exist', (err, data) => {
|
||||
if (err) {
|
||||
console.error('There was an error reading the file!', err);
|
||||
@ -77,7 +77,7 @@ Errors that occur within _Asynchronous APIs_ may be reported in multiple ways:
|
||||
[`EventEmitter`][], errors can be routed to that object's `'error'` event.
|
||||
|
||||
```js
|
||||
const net = require('net');
|
||||
const net = require('node:net');
|
||||
const connection = net.connect('localhost');
|
||||
|
||||
// Adding an 'error' event handler to a stream:
|
||||
@ -109,7 +109,7 @@ used appropriately or a handler has been registered for the
|
||||
[`'uncaughtException'`][] event.
|
||||
|
||||
```js
|
||||
const EventEmitter = require('events');
|
||||
const EventEmitter = require('node:events');
|
||||
const ee = new EventEmitter();
|
||||
|
||||
setImmediate(() => {
|
||||
@ -137,7 +137,7 @@ completes or an error is raised, the callback function is called with the
|
||||
the first argument will be passed as `null`.
|
||||
|
||||
```js
|
||||
const fs = require('fs');
|
||||
const fs = require('node:fs');
|
||||
|
||||
function errorFirstCallback(err, data) {
|
||||
if (err) {
|
||||
@ -157,7 +157,7 @@ use `throw` inside an error-first callback:
|
||||
|
||||
```js
|
||||
// THIS WILL NOT WORK:
|
||||
const fs = require('fs');
|
||||
const fs = require('node:fs');
|
||||
|
||||
try {
|
||||
fs.readFile('/some/file/that/does-not-exist', (err, data) => {
|
||||
@ -372,7 +372,7 @@ acceptable values for a function; whether that is a numeric range, or
|
||||
outside the set of options for a given function parameter.
|
||||
|
||||
```js
|
||||
require('net').connect(-1);
|
||||
require('node:net').connect(-1);
|
||||
// Throws "RangeError: "port" option should be >= 0 and < 65536: -1"
|
||||
```
|
||||
|
||||
@ -409,7 +409,7 @@ are almost always indicative of a broken program.
|
||||
|
||||
```js
|
||||
try {
|
||||
require('vm').runInThisContext('binary ! isNotOk');
|
||||
require('node:vm').runInThisContext('binary ! isNotOk');
|
||||
} catch (err) {
|
||||
// 'err' will be a SyntaxError.
|
||||
}
|
||||
@ -570,7 +570,7 @@ Indicates that a provided argument is not an allowable type. For example,
|
||||
passing a function to a parameter which expects a string would be a `TypeError`.
|
||||
|
||||
```js
|
||||
require('url').parse(() => { });
|
||||
require('node:url').parse(() => { });
|
||||
// Throws TypeError, since it expected a string.
|
||||
```
|
||||
|
||||
@ -638,11 +638,11 @@ order to be compatible with the web platform's `AbortError`.
|
||||
### `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 `assert` module when the
|
||||
`message` parameter in `assert.throws(block, message)` matches the error message
|
||||
thrown by `block` because that usage suggests that the user believes `message`
|
||||
is the expected message rather than the message the `AssertionError` will
|
||||
display if `block` does not throw.
|
||||
signature may be misunderstood. This is thrown by the `node:assert` module when
|
||||
the `message` parameter in `assert.throws(block, message)` matches the error
|
||||
message thrown by `block` because that usage suggests that the user believes
|
||||
`message` is the expected message rather than the message the `AssertionError`
|
||||
will display if `block` does not throw.
|
||||
|
||||
<a id="ERR_ARG_NOT_ITERABLE"></a>
|
||||
|
||||
@ -657,7 +657,7 @@ required, but not provided to a Node.js API.
|
||||
|
||||
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
|
||||
by the `assert` module.
|
||||
by the `node:assert` module.
|
||||
|
||||
<a id="ERR_ASYNC_CALLBACK"></a>
|
||||
|
||||
@ -818,14 +818,14 @@ key lies outside of the elliptic curve.
|
||||
### `ERR_CRYPTO_ENGINE_UNKNOWN`
|
||||
|
||||
An invalid crypto engine identifier was passed to
|
||||
[`require('crypto').setEngine()`][].
|
||||
[`require('node:crypto').setEngine()`][].
|
||||
|
||||
<a id="ERR_CRYPTO_FIPS_FORCED"></a>
|
||||
|
||||
### `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 `crypto` module.
|
||||
to enable or disable FIPS mode in the `node:crypto` module.
|
||||
|
||||
<a id="ERR_CRYPTO_FIPS_UNAVAILABLE"></a>
|
||||
|
||||
@ -1164,8 +1164,8 @@ ongoing asynchronous operations.
|
||||
|
||||
### `ERR_DOMAIN_CALLBACK_NOT_AVAILABLE`
|
||||
|
||||
The `domain` module was not usable since it could not establish the required
|
||||
error handling hooks, because
|
||||
The `node:domain` module was not usable since it could not establish the
|
||||
required error handling hooks, because
|
||||
[`process.setUncaughtExceptionCaptureCallback()`][] had been called at an
|
||||
earlier point in time.
|
||||
|
||||
@ -1174,10 +1174,10 @@ earlier point in time.
|
||||
### `ERR_DOMAIN_CANNOT_SET_UNCAUGHT_EXCEPTION_CAPTURE`
|
||||
|
||||
[`process.setUncaughtExceptionCaptureCallback()`][] could not be called
|
||||
because the `domain` module has been loaded at an earlier point in time.
|
||||
because the `node:domain` module has been loaded at an earlier point in time.
|
||||
|
||||
The stack trace is extended to include the point in time at which the
|
||||
`domain` module had been loaded.
|
||||
`node:domain` module had been loaded.
|
||||
|
||||
<a id="ERR_ENCODING_INVALID_ENCODED_DATA"></a>
|
||||
|
||||
@ -1750,7 +1750,7 @@ only be used with input via `--eval`, `--print` or `STDIN`.
|
||||
|
||||
### `ERR_INSPECTOR_ALREADY_ACTIVATED`
|
||||
|
||||
While using the `inspector` module, an attempt was made to activate the
|
||||
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()`
|
||||
before activating it on a different address.
|
||||
|
||||
@ -1758,21 +1758,21 @@ before activating it on a different address.
|
||||
|
||||
### `ERR_INSPECTOR_ALREADY_CONNECTED`
|
||||
|
||||
While using the `inspector` module, an attempt was made to connect when the
|
||||
While using the `node:inspector` module, an attempt was made to connect when the
|
||||
inspector was already connected.
|
||||
|
||||
<a id="ERR_INSPECTOR_CLOSED"></a>
|
||||
|
||||
### `ERR_INSPECTOR_CLOSED`
|
||||
|
||||
While using the `inspector` module, an attempt was made to use the inspector
|
||||
after the session had already closed.
|
||||
While using the `node:inspector` module, an attempt was made to use the
|
||||
inspector after the session had already closed.
|
||||
|
||||
<a id="ERR_INSPECTOR_COMMAND"></a>
|
||||
|
||||
### `ERR_INSPECTOR_COMMAND`
|
||||
|
||||
An error occurred while issuing a command via the `inspector` module.
|
||||
An error occurred while issuing a command via the `node:inspector` module.
|
||||
|
||||
<a id="ERR_INSPECTOR_NOT_ACTIVE"></a>
|
||||
|
||||
@ -1784,14 +1784,14 @@ The `inspector` is not active when `inspector.waitForDebugger()` is called.
|
||||
|
||||
### `ERR_INSPECTOR_NOT_AVAILABLE`
|
||||
|
||||
The `inspector` module is not available for use.
|
||||
The `node:inspector` module is not available for use.
|
||||
|
||||
<a id="ERR_INSPECTOR_NOT_CONNECTED"></a>
|
||||
|
||||
### `ERR_INSPECTOR_NOT_CONNECTED`
|
||||
|
||||
While using the `inspector` module, an attempt was made to use the inspector
|
||||
before it was connected.
|
||||
While using the `node:inspector` module, an attempt was made to use the
|
||||
inspector before it was connected.
|
||||
|
||||
<a id="ERR_INSPECTOR_NOT_WORKER"></a>
|
||||
|
||||
@ -2523,7 +2523,7 @@ Prevents an abort if a string decoder was set on the Socket or if the decoder
|
||||
is in `objectMode`.
|
||||
|
||||
```js
|
||||
const Socket = require('net').Socket;
|
||||
const Socket = require('node:net').Socket;
|
||||
const instance = new Socket();
|
||||
|
||||
instance.setEncoding('utf8');
|
||||
@ -2685,8 +2685,8 @@ category.
|
||||
|
||||
### `ERR_TRACE_EVENTS_UNAVAILABLE`
|
||||
|
||||
The `trace_events` module could not be loaded because Node.js was compiled with
|
||||
the `--without-v8-platform` flag.
|
||||
The `node:trace_events` module could not be loaded because Node.js was compiled
|
||||
with the `--without-v8-platform` flag.
|
||||
|
||||
<a id="ERR_TRANSFORM_ALREADY_TRANSFORMING"></a>
|
||||
|
||||
@ -3198,7 +3198,7 @@ added: v9.0.0
|
||||
removed: v10.0.0
|
||||
-->
|
||||
|
||||
The `repl` module was unable to parse data from the REPL history file.
|
||||
The `node:repl` module was unable to parse data from the REPL history file.
|
||||
|
||||
<a id="ERR_SOCKET_CANNOT_SEND"></a>
|
||||
|
||||
@ -3426,7 +3426,7 @@ The native call from `process.cpuUsage` could not be processed.
|
||||
[`process.send()`]: process.md#processsendmessage-sendhandle-options-callback
|
||||
[`process.setUncaughtExceptionCaptureCallback()`]: process.md#processsetuncaughtexceptioncapturecallbackfn
|
||||
[`readable._read()`]: stream.md#readable_readsize
|
||||
[`require('crypto').setEngine()`]: crypto.md#cryptosetengineengine-flags
|
||||
[`require('node:crypto').setEngine()`]: crypto.md#cryptosetengineengine-flags
|
||||
[`require()`]: modules.md#requireid
|
||||
[`server.close()`]: net.md#serverclosecallback
|
||||
[`server.listen()`]: net.md#serverlisten
|
||||
|
||||
@ -116,7 +116,7 @@ This section was moved to [Modules: Packages](packages.md).
|
||||
### Terminology
|
||||
|
||||
The _specifier_ of an `import` statement is the string after the `from` keyword,
|
||||
e.g. `'path'` in `import { sep } from 'path'`. Specifiers are also used in
|
||||
e.g. `'path'` in `import { sep } from 'node:path'`. Specifiers are also used in
|
||||
`export from` statements, and as the argument to an `import()` expression.
|
||||
|
||||
There are three types of specifiers:
|
||||
@ -260,12 +260,12 @@ exports. Named exports of builtin modules are updated only by calling
|
||||
[`module.syncBuiltinESMExports()`][].
|
||||
|
||||
```js
|
||||
import EventEmitter from 'events';
|
||||
import EventEmitter from 'node:events';
|
||||
const e = new EventEmitter();
|
||||
```
|
||||
|
||||
```js
|
||||
import { readFile } from 'fs';
|
||||
import { readFile } from 'node:fs';
|
||||
readFile('./foo.txt', (err, source) => {
|
||||
if (err) {
|
||||
console.error(err);
|
||||
@ -276,9 +276,9 @@ readFile('./foo.txt', (err, source) => {
|
||||
```
|
||||
|
||||
```js
|
||||
import fs, { readFileSync } from 'fs';
|
||||
import { syncBuiltinESMExports } from 'module';
|
||||
import { Buffer } from 'buffer';
|
||||
import fs, { readFileSync } from 'node:fs';
|
||||
import { syncBuiltinESMExports } from 'node:module';
|
||||
import { Buffer } from 'node:buffer';
|
||||
|
||||
fs.readFileSync = () => Buffer.from('Hello, ESM');
|
||||
syncBuiltinESMExports();
|
||||
@ -308,7 +308,7 @@ current module file.
|
||||
This enables useful patterns such as relative file loading:
|
||||
|
||||
```js
|
||||
import { readFileSync } from 'fs';
|
||||
import { readFileSync } from 'node:fs';
|
||||
const buffer = readFileSync(new URL('./data.proto', import.meta.url));
|
||||
```
|
||||
|
||||
@ -592,8 +592,8 @@ If a top level `await` expression never resolves, the `node` process will exit
|
||||
with a `13` [status code][].
|
||||
|
||||
```js
|
||||
import { spawn } from 'child_process';
|
||||
import { execPath } from 'process';
|
||||
import { spawn } from 'node:child_process';
|
||||
import { execPath } from 'node:process';
|
||||
|
||||
spawn(execPath, [
|
||||
'--input-type=module',
|
||||
@ -646,7 +646,7 @@ references to the local dependencies:
|
||||
|
||||
```mjs
|
||||
// file.mjs
|
||||
import worker_threads from 'worker_threads';
|
||||
import worker_threads from 'node:worker_threads';
|
||||
import { configure, resize } from 'https://example.com/imagelib.mjs';
|
||||
configure({ worker_threads });
|
||||
```
|
||||
@ -948,7 +948,7 @@ and there is no security.
|
||||
|
||||
```js
|
||||
// https-loader.mjs
|
||||
import { get } from 'https';
|
||||
import { get } from 'node:https';
|
||||
|
||||
export function resolve(specifier, context, defaultResolve) {
|
||||
const { parentURL = null } = context;
|
||||
@ -1118,7 +1118,7 @@ async function getPackageType(url) {
|
||||
import { scream } from './scream.coffee'
|
||||
console.log scream 'hello, world'
|
||||
|
||||
import { version } from 'process'
|
||||
import { version } from 'node:process'
|
||||
console.log "Brought to you by Node.js version #{version}"
|
||||
```
|
||||
|
||||
|
||||
@ -31,7 +31,7 @@ listener. The `eventEmitter.on()` method is used to register listeners, while
|
||||
the `eventEmitter.emit()` method is used to trigger the event.
|
||||
|
||||
```js
|
||||
const EventEmitter = require('events');
|
||||
const EventEmitter = require('node:events');
|
||||
|
||||
class MyEmitter extends EventEmitter {}
|
||||
|
||||
@ -144,7 +144,7 @@ myEmitter.emit('error', new Error('whoops!'));
|
||||
```
|
||||
|
||||
To guard against crashing the Node.js process the [`domain`][] module can be
|
||||
used. (Note, however, that the `domain` module is deprecated.)
|
||||
used. (Note, however, that the `node:domain` module is deprecated.)
|
||||
|
||||
As a best practice, listeners should always be added for the `'error'` events.
|
||||
|
||||
@ -161,7 +161,7 @@ It is possible to monitor `'error'` events without consuming the emitted error
|
||||
by installing a listener using the symbol `events.errorMonitor`.
|
||||
|
||||
```js
|
||||
const { EventEmitter, errorMonitor } = require('events');
|
||||
const { EventEmitter, errorMonitor } = require('node:events');
|
||||
|
||||
const myEmitter = new EventEmitter();
|
||||
myEmitter.on(errorMonitor, (err) => {
|
||||
@ -209,7 +209,7 @@ Setting `events.captureRejections = true` will change the default for all
|
||||
new instances of `EventEmitter`.
|
||||
|
||||
```js
|
||||
const events = require('events');
|
||||
const events = require('node:events');
|
||||
events.captureRejections = true;
|
||||
const ee1 = new events.EventEmitter();
|
||||
ee1.on('something', async (value) => {
|
||||
@ -235,10 +235,10 @@ changes:
|
||||
description: Added captureRejections option.
|
||||
-->
|
||||
|
||||
The `EventEmitter` class is defined and exposed by the `events` module:
|
||||
The `EventEmitter` class is defined and exposed by the `node:events` module:
|
||||
|
||||
```js
|
||||
const EventEmitter = require('events');
|
||||
const EventEmitter = require('node:events');
|
||||
```
|
||||
|
||||
All `EventEmitter`s emit the event `'newListener'` when new listeners are
|
||||
@ -338,7 +338,7 @@ to each.
|
||||
Returns `true` if the event had listeners, `false` otherwise.
|
||||
|
||||
```js
|
||||
const EventEmitter = require('events');
|
||||
const EventEmitter = require('node:events');
|
||||
const myEmitter = new EventEmitter();
|
||||
|
||||
// First listener
|
||||
@ -382,7 +382,7 @@ Returns an array listing the events for which the emitter has registered
|
||||
listeners. The values in the array are strings or `Symbol`s.
|
||||
|
||||
```js
|
||||
const EventEmitter = require('events');
|
||||
const EventEmitter = require('node:events');
|
||||
const myEE = new EventEmitter();
|
||||
myEE.on('foo', () => {});
|
||||
myEE.on('bar', () => {});
|
||||
@ -758,7 +758,7 @@ It is possible to use [`events.captureRejectionSymbol`][rejectionsymbol] in
|
||||
place of `Symbol.for('nodejs.rejection')`.
|
||||
|
||||
```js
|
||||
const { EventEmitter, captureRejectionSymbol } = require('events');
|
||||
const { EventEmitter, captureRejectionSymbol } = require('node:events');
|
||||
|
||||
class MyClass extends EventEmitter {
|
||||
constructor() {
|
||||
@ -854,7 +854,7 @@ For `EventTarget`s this is the only way to get the event listeners for the
|
||||
event target. This is useful for debugging and diagnostic purposes.
|
||||
|
||||
```js
|
||||
const { getEventListeners, EventEmitter } = require('events');
|
||||
const { getEventListeners, EventEmitter } = require('node:events');
|
||||
|
||||
{
|
||||
const ee = new EventEmitter();
|
||||
@ -898,7 +898,7 @@ This method is intentionally generic and works with the web platform
|
||||
`'error'` event semantics and does not listen to the `'error'` event.
|
||||
|
||||
```js
|
||||
const { once, EventEmitter } = require('events');
|
||||
const { once, EventEmitter } = require('node:events');
|
||||
|
||||
async function run() {
|
||||
const ee = new EventEmitter();
|
||||
@ -931,7 +931,7 @@ is used to wait for another event. If `events.once()` is used to wait for the
|
||||
special handling:
|
||||
|
||||
```js
|
||||
const { EventEmitter, once } = require('events');
|
||||
const { EventEmitter, once } = require('node:events');
|
||||
|
||||
const ee = new EventEmitter();
|
||||
|
||||
@ -947,7 +947,7 @@ ee.emit('error', new Error('boom'));
|
||||
An {AbortSignal} can be used to cancel waiting for the event:
|
||||
|
||||
```js
|
||||
const { EventEmitter, once } = require('events');
|
||||
const { EventEmitter, once } = require('node:events');
|
||||
|
||||
const ee = new EventEmitter();
|
||||
const ac = new AbortController();
|
||||
@ -980,7 +980,7 @@ queue, and because `EventEmitter` emits all events synchronously, it is possible
|
||||
for `events.once()` to miss an event.
|
||||
|
||||
```js
|
||||
const { EventEmitter, once } = require('events');
|
||||
const { EventEmitter, once } = require('node:events');
|
||||
|
||||
const myEE = new EventEmitter();
|
||||
|
||||
@ -1007,7 +1007,7 @@ of them, then it becomes possible to use `Promise.all()`, `Promise.race()`,
|
||||
or `Promise.allSettled()`:
|
||||
|
||||
```js
|
||||
const { EventEmitter, once } = require('events');
|
||||
const { EventEmitter, once } = require('node:events');
|
||||
|
||||
const myEE = new EventEmitter();
|
||||
|
||||
@ -1076,7 +1076,7 @@ A class method that returns the number of listeners for the given `eventName`
|
||||
registered on the given `emitter`.
|
||||
|
||||
```js
|
||||
const { EventEmitter, listenerCount } = require('events');
|
||||
const { EventEmitter, listenerCount } = require('node:events');
|
||||
const myEmitter = new EventEmitter();
|
||||
myEmitter.on('event', () => {});
|
||||
myEmitter.on('event', () => {});
|
||||
@ -1099,7 +1099,7 @@ added:
|
||||
* Returns: {AsyncIterator} that iterates `eventName` events emitted by the `emitter`
|
||||
|
||||
```js
|
||||
const { on, EventEmitter } = require('events');
|
||||
const { on, EventEmitter } = require('node:events');
|
||||
|
||||
(async () => {
|
||||
const ee = new EventEmitter();
|
||||
@ -1128,7 +1128,7 @@ composed of the emitted event arguments.
|
||||
An {AbortSignal} can be used to cancel waiting on events:
|
||||
|
||||
```js
|
||||
const { on, EventEmitter } = require('events');
|
||||
const { on, EventEmitter } = require('node:events');
|
||||
const ac = new AbortController();
|
||||
|
||||
(async () => {
|
||||
@ -1168,7 +1168,7 @@ added: v15.4.0
|
||||
const {
|
||||
setMaxListeners,
|
||||
EventEmitter
|
||||
} = require('events');
|
||||
} = require('node:events');
|
||||
|
||||
const target = new EventTarget();
|
||||
const emitter = new EventEmitter();
|
||||
@ -1189,9 +1189,9 @@ require manual async tracking. Specifically, all events emitted by instances
|
||||
of `events.EventEmitterAsyncResource` will run within its [async context][].
|
||||
|
||||
```js
|
||||
const { EventEmitterAsyncResource } = require('events');
|
||||
const { notStrictEqual, strictEqual } = require('assert');
|
||||
const { executionAsyncId } = require('async_hooks');
|
||||
const { EventEmitterAsyncResource } = require('node:events');
|
||||
const { notStrictEqual, strictEqual } = require('node:assert');
|
||||
const { executionAsyncId } = require('node:async_hooks');
|
||||
|
||||
// Async tracking tooling will identify this as 'Q'.
|
||||
const ee1 = new EventEmitterAsyncResource({ name: 'Q' });
|
||||
|
||||
204
doc/api/fs.md
204
doc/api/fs.md
@ -8,27 +8,27 @@
|
||||
|
||||
<!-- source_link=lib/fs.js -->
|
||||
|
||||
The `fs` module enables interacting with the file system in a
|
||||
The `node:fs` module enables interacting with the file system in a
|
||||
way modeled on standard POSIX functions.
|
||||
|
||||
To use the promise-based APIs:
|
||||
|
||||
```mjs
|
||||
import * as fs from 'fs/promises';
|
||||
import * as fs from 'node:fs/promises';
|
||||
```
|
||||
|
||||
```cjs
|
||||
const fs = require('fs/promises');
|
||||
const fs = require('node:fs/promises');
|
||||
```
|
||||
|
||||
To use the callback and sync APIs:
|
||||
|
||||
```mjs
|
||||
import * as fs from 'fs';
|
||||
import * as fs from 'node:fs';
|
||||
```
|
||||
|
||||
```cjs
|
||||
const fs = require('fs');
|
||||
const fs = require('node:fs');
|
||||
```
|
||||
|
||||
All file system operations have synchronous, callback, and promise-based
|
||||
@ -40,7 +40,7 @@ Promise-based operations return a promise that is fulfilled when the
|
||||
asynchronous operation is complete.
|
||||
|
||||
```mjs
|
||||
import { unlink } from 'fs/promises';
|
||||
import { unlink } from 'node:fs/promises';
|
||||
|
||||
try {
|
||||
await unlink('/tmp/hello');
|
||||
@ -51,7 +51,7 @@ try {
|
||||
```
|
||||
|
||||
```cjs
|
||||
const { unlink } = require('fs/promises');
|
||||
const { unlink } = require('node:fs/promises');
|
||||
|
||||
(async function(path) {
|
||||
try {
|
||||
@ -72,7 +72,7 @@ reserved for an exception. If the operation is completed successfully, then
|
||||
the first argument is `null` or `undefined`.
|
||||
|
||||
```mjs
|
||||
import { unlink } from 'fs';
|
||||
import { unlink } from 'node:fs';
|
||||
|
||||
unlink('/tmp/hello', (err) => {
|
||||
if (err) throw err;
|
||||
@ -81,7 +81,7 @@ unlink('/tmp/hello', (err) => {
|
||||
```
|
||||
|
||||
```cjs
|
||||
const { unlink } = require('fs');
|
||||
const { unlink } = require('node:fs');
|
||||
|
||||
unlink('/tmp/hello', (err) => {
|
||||
if (err) throw err;
|
||||
@ -89,7 +89,7 @@ unlink('/tmp/hello', (err) => {
|
||||
});
|
||||
```
|
||||
|
||||
The callback-based versions of the `fs` module APIs are preferable over
|
||||
The callback-based versions of the `node:fs` module APIs are preferable over
|
||||
the use of the promise APIs when maximal performance (both in terms of
|
||||
execution time and memory allocation) is required.
|
||||
|
||||
@ -100,7 +100,7 @@ execution until the operation is complete. Exceptions are thrown immediately
|
||||
and can be handled using `try…catch`, or can be allowed to bubble up.
|
||||
|
||||
```mjs
|
||||
import { unlinkSync } from 'fs';
|
||||
import { unlinkSync } from 'node:fs';
|
||||
|
||||
try {
|
||||
unlinkSync('/tmp/hello');
|
||||
@ -111,7 +111,7 @@ try {
|
||||
```
|
||||
|
||||
```cjs
|
||||
const { unlinkSync } = require('fs');
|
||||
const { unlinkSync } = require('node:fs');
|
||||
|
||||
try {
|
||||
unlinkSync('/tmp/hello');
|
||||
@ -128,7 +128,7 @@ added: v10.0.0
|
||||
changes:
|
||||
- version: v14.0.0
|
||||
pr-url: https://github.com/nodejs/node/pull/31553
|
||||
description: Exposed as `require('fs/promises')`.
|
||||
description: Exposed as `require('node:fs/promises')`.
|
||||
- version:
|
||||
- v11.14.0
|
||||
- v10.17.0
|
||||
@ -136,7 +136,7 @@ changes:
|
||||
description: This API is no longer experimental.
|
||||
- version: v10.1.0
|
||||
pr-url: https://github.com/nodejs/node/pull/20504
|
||||
description: The API is accessible via `require('fs').promises` only.
|
||||
description: The API is accessible via `require('node:fs').promises` only.
|
||||
-->
|
||||
|
||||
The `fs/promises` API provides asynchronous file system methods that return
|
||||
@ -237,7 +237,7 @@ Closes the file handle after waiting for any pending operation on the handle to
|
||||
complete.
|
||||
|
||||
```mjs
|
||||
import { open } from 'fs/promises';
|
||||
import { open } from 'node:fs/promises';
|
||||
|
||||
let filehandle;
|
||||
try {
|
||||
@ -282,7 +282,7 @@ By default, the stream will emit a `'close'` event after it has been
|
||||
destroyed. Set the `emitClose` option to `false` to change this behavior.
|
||||
|
||||
```mjs
|
||||
import { open } from 'fs/promises';
|
||||
import { open } from 'node:fs/promises';
|
||||
|
||||
const fd = await open('/dev/input/event0');
|
||||
// Create a stream from some character device.
|
||||
@ -308,7 +308,7 @@ automatically.
|
||||
An example to read the last 10 bytes of a file which is 100 bytes long:
|
||||
|
||||
```mjs
|
||||
import { open } from 'fs/promises';
|
||||
import { open } from 'node:fs/promises';
|
||||
|
||||
const fd = await open('sample.txt');
|
||||
fd.createReadStream({ start: 90, end: 99 });
|
||||
@ -448,7 +448,7 @@ await file.close();
|
||||
```cjs
|
||||
const {
|
||||
open,
|
||||
} = require('fs/promises');
|
||||
} = require('node:fs/promises');
|
||||
|
||||
(async () => {
|
||||
const file = await open('./some/file/to/read');
|
||||
@ -552,7 +552,7 @@ retained in the file.
|
||||
The following example retains only the first four bytes of the file:
|
||||
|
||||
```mjs
|
||||
import { open } from 'fs/promises';
|
||||
import { open } from 'node:fs/promises';
|
||||
|
||||
let filehandle = null;
|
||||
try {
|
||||
@ -743,8 +743,8 @@ with an {Error} object. The following example checks if the file
|
||||
`/etc/passwd` can be read and written by the current process.
|
||||
|
||||
```mjs
|
||||
import { access } from 'fs/promises';
|
||||
import { constants } from 'fs';
|
||||
import { access } from 'node:fs/promises';
|
||||
import { constants } from 'node:fs';
|
||||
|
||||
try {
|
||||
await access('/etc/passwd', constants.R_OK | constants.W_OK);
|
||||
@ -846,8 +846,8 @@ error occurs after the destination file has been opened for writing, an attempt
|
||||
will be made to remove the destination.
|
||||
|
||||
```mjs
|
||||
import { constants } from 'fs';
|
||||
import { copyFile } from 'fs/promises';
|
||||
import { constants } from 'node:fs';
|
||||
import { copyFile } from 'node:fs/promises';
|
||||
|
||||
try {
|
||||
await copyFile('source.txt', 'destination.txt');
|
||||
@ -1037,7 +1037,7 @@ The optional `options` argument can be a string specifying an encoding, or an
|
||||
object with an `encoding` property specifying the character encoding to use.
|
||||
|
||||
```mjs
|
||||
import { mkdtemp } from 'fs/promises';
|
||||
import { mkdtemp } from 'node:fs/promises';
|
||||
|
||||
try {
|
||||
await mkdtemp(path.join(os.tmpdir(), 'foo-'));
|
||||
@ -1050,7 +1050,7 @@ The `fsPromises.mkdtemp()` method will append the six randomly selected
|
||||
characters directly to the `prefix` string. For instance, given a directory
|
||||
`/tmp`, if the intention is to create a temporary directory _within_ `/tmp`, the
|
||||
`prefix` must end with a trailing platform-specific path separator
|
||||
(`require('path').sep`).
|
||||
(`require('node:path').sep`).
|
||||
|
||||
### `fsPromises.open(path, flags[, mode])`
|
||||
|
||||
@ -1110,7 +1110,7 @@ directory and subsequent read operations.
|
||||
Example using async iteration:
|
||||
|
||||
```mjs
|
||||
import { opendir } from 'fs/promises';
|
||||
import { opendir } from 'node:fs/promises';
|
||||
|
||||
try {
|
||||
const dir = await opendir('./');
|
||||
@ -1152,7 +1152,7 @@ If `options.withFileTypes` is set to `true`, the resolved array will contain
|
||||
{fs.Dirent} objects.
|
||||
|
||||
```mjs
|
||||
import { readdir } from 'fs/promises';
|
||||
import { readdir } from 'node:fs/promises';
|
||||
|
||||
try {
|
||||
const files = await readdir(path);
|
||||
@ -1199,7 +1199,7 @@ It is possible to abort an ongoing `readFile` using an {AbortSignal}. If a
|
||||
request is aborted the promise returned is rejected with an `AbortError`:
|
||||
|
||||
```mjs
|
||||
import { readFile } from 'fs/promises';
|
||||
import { readFile } from 'node:fs/promises';
|
||||
|
||||
try {
|
||||
const controller = new AbortController();
|
||||
@ -1474,7 +1474,7 @@ Returns an async iterator that watches for changes on `filename`, where `filenam
|
||||
is either a file or a directory.
|
||||
|
||||
```js
|
||||
const { watch } = require('fs/promises');
|
||||
const { watch } = require('node:fs/promises');
|
||||
|
||||
const ac = new AbortController();
|
||||
const { signal } = ac;
|
||||
@ -1554,8 +1554,8 @@ Cancelation is "best effort", and some amount of data is likely still
|
||||
to be written.
|
||||
|
||||
```mjs
|
||||
import { writeFile } from 'fs/promises';
|
||||
import { Buffer } from 'buffer';
|
||||
import { writeFile } from 'node:fs/promises';
|
||||
import { Buffer } from 'node:buffer';
|
||||
|
||||
try {
|
||||
const controller = new AbortController();
|
||||
@ -1629,7 +1629,7 @@ argument will be an `Error` object. The following examples check if
|
||||
`package.json` exists, and if it is readable or writable.
|
||||
|
||||
```mjs
|
||||
import { access, constants } from 'fs';
|
||||
import { access, constants } from 'node:fs';
|
||||
|
||||
const file = 'package.json';
|
||||
|
||||
@ -1663,7 +1663,7 @@ file directly and handle the error raised if the file is not accessible.
|
||||
**write (NOT RECOMMENDED)**
|
||||
|
||||
```mjs
|
||||
import { access, open, close } from 'fs';
|
||||
import { access, open, close } from 'node:fs';
|
||||
|
||||
access('myfile', (err) => {
|
||||
if (!err) {
|
||||
@ -1688,7 +1688,7 @@ access('myfile', (err) => {
|
||||
**write (RECOMMENDED)**
|
||||
|
||||
```mjs
|
||||
import { open, close } from 'fs';
|
||||
import { open, close } from 'node:fs';
|
||||
|
||||
open('myfile', 'wx', (err, fd) => {
|
||||
if (err) {
|
||||
@ -1713,7 +1713,7 @@ open('myfile', 'wx', (err, fd) => {
|
||||
**read (NOT RECOMMENDED)**
|
||||
|
||||
```mjs
|
||||
import { access, open, close } from 'fs';
|
||||
import { access, open, close } from 'node:fs';
|
||||
access('myfile', (err) => {
|
||||
if (err) {
|
||||
if (err.code === 'ENOENT') {
|
||||
@ -1741,7 +1741,7 @@ access('myfile', (err) => {
|
||||
**read (RECOMMENDED)**
|
||||
|
||||
```mjs
|
||||
import { open, close } from 'fs';
|
||||
import { open, close } from 'node:fs';
|
||||
|
||||
open('myfile', 'r', (err, fd) => {
|
||||
if (err) {
|
||||
@ -1818,7 +1818,7 @@ The `mode` option only affects the newly created file. See [`fs.open()`][]
|
||||
for more details.
|
||||
|
||||
```mjs
|
||||
import { appendFile } from 'fs';
|
||||
import { appendFile } from 'node:fs';
|
||||
|
||||
appendFile('message.txt', 'data to append', (err) => {
|
||||
if (err) throw err;
|
||||
@ -1829,7 +1829,7 @@ appendFile('message.txt', 'data to append', (err) => {
|
||||
If `options` is a string, then it specifies the encoding:
|
||||
|
||||
```mjs
|
||||
import { appendFile } from 'fs';
|
||||
import { appendFile } from 'node:fs';
|
||||
|
||||
appendFile('message.txt', 'data to append', 'utf8', callback);
|
||||
```
|
||||
@ -1839,7 +1839,7 @@ for appending (using `fs.open()` or `fs.openSync()`). The file descriptor will
|
||||
not be closed automatically.
|
||||
|
||||
```mjs
|
||||
import { open, close, appendFile } from 'fs';
|
||||
import { open, close, appendFile } from 'node:fs';
|
||||
|
||||
function closeFd(fd) {
|
||||
close(fd, (err) => {
|
||||
@ -1897,7 +1897,7 @@ possible exception are given to the completion callback.
|
||||
See the POSIX chmod(2) documentation for more detail.
|
||||
|
||||
```mjs
|
||||
import { chmod } from 'fs';
|
||||
import { chmod } from 'node:fs';
|
||||
|
||||
chmod('my_file.txt', 0o775, (err) => {
|
||||
if (err) throw err;
|
||||
@ -2069,7 +2069,7 @@ OR of two or more values (e.g.
|
||||
copy-on-write, then the operation will fail.
|
||||
|
||||
```mjs
|
||||
import { copyFile, constants } from 'fs';
|
||||
import { copyFile, constants } from 'node:fs';
|
||||
|
||||
function callback(err) {
|
||||
if (err) throw err;
|
||||
@ -2217,7 +2217,7 @@ an override for `read` is required. If no `fd` is provided, an override for
|
||||
also required.
|
||||
|
||||
```mjs
|
||||
import { createReadStream } from 'fs';
|
||||
import { createReadStream } from 'node:fs';
|
||||
|
||||
// Create a stream from some character device.
|
||||
const stream = createReadStream('/dev/input/event0');
|
||||
@ -2245,7 +2245,7 @@ file was created.
|
||||
An example to read the last 10 bytes of a file which is 100 bytes long:
|
||||
|
||||
```mjs
|
||||
import { createReadStream } from 'fs';
|
||||
import { createReadStream } from 'node:fs';
|
||||
|
||||
createReadStream('sample.txt', { start: 90, end: 99 });
|
||||
```
|
||||
@ -2364,7 +2364,7 @@ Test whether or not the given path exists by checking with the file system.
|
||||
Then call the `callback` argument with either true or false:
|
||||
|
||||
```mjs
|
||||
import { exists } from 'fs';
|
||||
import { exists } from 'node:fs';
|
||||
|
||||
exists('/etc/passwd', (e) => {
|
||||
console.log(e ? 'it exists' : 'no passwd!');
|
||||
@ -2386,7 +2386,7 @@ file directly and handle the error raised if the file does not exist.
|
||||
**write (NOT RECOMMENDED)**
|
||||
|
||||
```mjs
|
||||
import { exists, open, close } from 'fs';
|
||||
import { exists, open, close } from 'node:fs';
|
||||
|
||||
exists('myfile', (e) => {
|
||||
if (e) {
|
||||
@ -2410,7 +2410,7 @@ exists('myfile', (e) => {
|
||||
**write (RECOMMENDED)**
|
||||
|
||||
```mjs
|
||||
import { open, close } from 'fs';
|
||||
import { open, close } from 'node:fs';
|
||||
open('myfile', 'wx', (err, fd) => {
|
||||
if (err) {
|
||||
if (err.code === 'EEXIST') {
|
||||
@ -2434,7 +2434,7 @@ open('myfile', 'wx', (err, fd) => {
|
||||
**read (NOT RECOMMENDED)**
|
||||
|
||||
```mjs
|
||||
import { open, close, exists } from 'fs';
|
||||
import { open, close, exists } from 'node:fs';
|
||||
|
||||
exists('myfile', (e) => {
|
||||
if (e) {
|
||||
@ -2458,7 +2458,7 @@ exists('myfile', (e) => {
|
||||
**read (RECOMMENDED)**
|
||||
|
||||
```mjs
|
||||
import { open, close } from 'fs';
|
||||
import { open, close } from 'node:fs';
|
||||
|
||||
open('myfile', 'r', (err, fd) => {
|
||||
if (err) {
|
||||
@ -2680,7 +2680,7 @@ For example, the following program retains only the first four bytes of the
|
||||
file:
|
||||
|
||||
```mjs
|
||||
import { open, close, ftruncate } from 'fs';
|
||||
import { open, close, ftruncate } from 'node:fs';
|
||||
|
||||
function closeFd(fd) {
|
||||
close(fd, (err) => {
|
||||
@ -2972,7 +2972,7 @@ property indicating whether parent directories should be created. Calling
|
||||
when `recursive` is false.
|
||||
|
||||
```mjs
|
||||
import { mkdir } from 'fs';
|
||||
import { mkdir } from 'node:fs';
|
||||
|
||||
// Creates /tmp/a/apple, regardless of whether `/tmp` and /tmp/a exist.
|
||||
mkdir('/tmp/a/apple', { recursive: true }, (err) => {
|
||||
@ -2984,7 +2984,7 @@ On Windows, using `fs.mkdir()` on the root directory even with recursion will
|
||||
result in an error:
|
||||
|
||||
```mjs
|
||||
import { mkdir } from 'fs';
|
||||
import { mkdir } from 'node:fs';
|
||||
|
||||
mkdir('/', { recursive: true }, (err) => {
|
||||
// => [Error: EPERM: operation not permitted, mkdir 'C:\']
|
||||
@ -3043,7 +3043,7 @@ The optional `options` argument can be a string specifying an encoding, or an
|
||||
object with an `encoding` property specifying the character encoding to use.
|
||||
|
||||
```mjs
|
||||
import { mkdtemp } from 'fs';
|
||||
import { mkdtemp } from 'node:fs';
|
||||
|
||||
mkdtemp(path.join(os.tmpdir(), 'foo-'), (err, directory) => {
|
||||
if (err) throw err;
|
||||
@ -3056,11 +3056,11 @@ The `fs.mkdtemp()` method will append the six randomly selected characters
|
||||
directly to the `prefix` string. For instance, given a directory `/tmp`, if the
|
||||
intention is to create a temporary directory _within_ `/tmp`, the `prefix`
|
||||
must end with a trailing platform-specific path separator
|
||||
(`require('path').sep`).
|
||||
(`require('node:path').sep`).
|
||||
|
||||
```mjs
|
||||
import { tmpdir } from 'os';
|
||||
import { mkdtemp } from 'fs';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { mkdtemp } from 'node:fs';
|
||||
|
||||
// The parent directory for the new temporary directory
|
||||
const tmpDir = tmpdir();
|
||||
@ -3075,7 +3075,7 @@ mkdtemp(tmpDir, (err, directory) => {
|
||||
});
|
||||
|
||||
// This method is *CORRECT*:
|
||||
import { sep } from 'path';
|
||||
import { sep } from 'node:path';
|
||||
mkdtemp(`${tmpDir}${sep}`, (err, directory) => {
|
||||
if (err) throw err;
|
||||
console.log(directory);
|
||||
@ -3348,7 +3348,7 @@ changes:
|
||||
Asynchronously reads the entire contents of a file.
|
||||
|
||||
```mjs
|
||||
import { readFile } from 'fs';
|
||||
import { readFile } from 'node:fs';
|
||||
|
||||
readFile('/etc/passwd', (err, data) => {
|
||||
if (err) throw err;
|
||||
@ -3364,7 +3364,7 @@ If no encoding is specified, then the raw buffer is returned.
|
||||
If `options` is a string, then it specifies the encoding:
|
||||
|
||||
```mjs
|
||||
import { readFile } from 'fs';
|
||||
import { readFile } from 'node:fs';
|
||||
|
||||
readFile('/etc/passwd', 'utf8', callback);
|
||||
```
|
||||
@ -3375,7 +3375,7 @@ error will be returned. On FreeBSD, a representation of the directory's contents
|
||||
will be returned.
|
||||
|
||||
```mjs
|
||||
import { readFile } from 'fs';
|
||||
import { readFile } from 'node:fs';
|
||||
|
||||
// macOS, Linux, and Windows
|
||||
readFile('<directory>', (err, data) => {
|
||||
@ -3392,7 +3392,7 @@ It is possible to abort an ongoing request using an `AbortSignal`. If a
|
||||
request is aborted the callback is called with an `AbortError`:
|
||||
|
||||
```mjs
|
||||
import { readFile } from 'fs';
|
||||
import { readFile } from 'node:fs';
|
||||
|
||||
const controller = new AbortController();
|
||||
const signal = controller.signal;
|
||||
@ -3657,7 +3657,7 @@ given to the completion callback.
|
||||
See also: rename(2).
|
||||
|
||||
```mjs
|
||||
import { rename } from 'fs';
|
||||
import { rename } from 'node:fs';
|
||||
|
||||
rename('oldFile.txt', 'newFile.txt', (err) => {
|
||||
if (err) throw err;
|
||||
@ -3838,7 +3838,7 @@ For example, given the following directory structure:
|
||||
The next program will check for the stats of the given paths:
|
||||
|
||||
```mjs
|
||||
import { stat } from 'fs';
|
||||
import { stat } from 'node:fs';
|
||||
|
||||
const pathsToCheck = ['./txtDir', './txtDir/file.txt'];
|
||||
|
||||
@ -3939,7 +3939,7 @@ require the destination path to be absolute. When using `'junction'`, the
|
||||
Relative targets are relative to the link’s parent directory.
|
||||
|
||||
```mjs
|
||||
import { symlink } from 'fs';
|
||||
import { symlink } from 'node:fs';
|
||||
|
||||
symlink('./mew', './mewtwo', callback);
|
||||
```
|
||||
@ -3988,7 +3988,7 @@ given to the completion callback. A file descriptor can also be passed as the
|
||||
first argument. In this case, `fs.ftruncate()` is called.
|
||||
|
||||
```mjs
|
||||
import { truncate } from 'fs';
|
||||
import { truncate } from 'node:fs';
|
||||
// Assuming that 'path/file.txt' is a regular file.
|
||||
truncate('path/file.txt', (err) => {
|
||||
if (err) throw err;
|
||||
@ -3997,7 +3997,7 @@ truncate('path/file.txt', (err) => {
|
||||
```
|
||||
|
||||
```cjs
|
||||
const { truncate } = require('fs');
|
||||
const { truncate } = require('node:fs');
|
||||
// Assuming that 'path/file.txt' is a regular file.
|
||||
truncate('path/file.txt', (err) => {
|
||||
if (err) throw err;
|
||||
@ -4042,7 +4042,7 @@ Asynchronously removes a file or symbolic link. No arguments other than a
|
||||
possible exception are given to the completion callback.
|
||||
|
||||
```mjs
|
||||
import { unlink } from 'fs';
|
||||
import { unlink } from 'node:fs';
|
||||
// Assuming that 'path/file.txt' is a regular file.
|
||||
unlink('path/file.txt', (err) => {
|
||||
if (err) throw err;
|
||||
@ -4241,7 +4241,7 @@ guaranteed to be provided. Therefore, don't assume that `filename` argument is
|
||||
always provided in the callback, and have some fallback logic if it is `null`.
|
||||
|
||||
```mjs
|
||||
import { watch } from 'fs';
|
||||
import { watch } from 'node:fs';
|
||||
watch('somedir', (eventType, filename) => {
|
||||
console.log(`event type is: ${eventType}`);
|
||||
if (filename) {
|
||||
@ -4289,7 +4289,7 @@ The `listener` gets two arguments the current stat object and the previous
|
||||
stat object:
|
||||
|
||||
```mjs
|
||||
import { watchFile } from 'fs';
|
||||
import { watchFile } from 'node:fs';
|
||||
|
||||
watchFile('message.text', (curr, prev) => {
|
||||
console.log(`the current mtime is: ${curr.mtime}`);
|
||||
@ -4533,8 +4533,8 @@ The `mode` option only affects the newly created file. See [`fs.open()`][]
|
||||
for more details.
|
||||
|
||||
```mjs
|
||||
import { writeFile } from 'fs';
|
||||
import { Buffer } from 'buffer';
|
||||
import { writeFile } from 'node:fs';
|
||||
import { Buffer } from 'node:buffer';
|
||||
|
||||
const data = new Uint8Array(Buffer.from('Hello Node.js'));
|
||||
writeFile('message.txt', data, (err) => {
|
||||
@ -4546,7 +4546,7 @@ writeFile('message.txt', data, (err) => {
|
||||
If `options` is a string, then it specifies the encoding:
|
||||
|
||||
```mjs
|
||||
import { writeFile } from 'fs';
|
||||
import { writeFile } from 'node:fs';
|
||||
|
||||
writeFile('message.txt', 'Hello Node.js', 'utf8', callback);
|
||||
```
|
||||
@ -4564,8 +4564,8 @@ Cancelation is "best effort", and some amount of data is likely still
|
||||
to be written.
|
||||
|
||||
```mjs
|
||||
import { writeFile } from 'fs';
|
||||
import { Buffer } from 'buffer';
|
||||
import { writeFile } from 'node:fs';
|
||||
import { Buffer } from 'node:buffer';
|
||||
|
||||
const controller = new AbortController();
|
||||
const { signal } = controller;
|
||||
@ -4586,8 +4586,8 @@ When `file` is a file descriptor, the behavior is almost identical to directly
|
||||
calling `fs.write()` like:
|
||||
|
||||
```mjs
|
||||
import { write } from 'fs';
|
||||
import { Buffer } from 'buffer';
|
||||
import { write } from 'node:fs';
|
||||
import { Buffer } from 'node:buffer';
|
||||
|
||||
write(fd, Buffer.from(data, options.encoding), callback);
|
||||
```
|
||||
@ -4680,7 +4680,7 @@ If any of the accessibility checks fail, an `Error` will be thrown. Otherwise,
|
||||
the method will return `undefined`.
|
||||
|
||||
```mjs
|
||||
import { accessSync, constants } from 'fs';
|
||||
import { accessSync, constants } from 'node:fs';
|
||||
|
||||
try {
|
||||
accessSync('etc/passwd', constants.R_OK | constants.W_OK);
|
||||
@ -4717,7 +4717,7 @@ The `mode` option only affects the newly created file. See [`fs.open()`][]
|
||||
for more details.
|
||||
|
||||
```mjs
|
||||
import { appendFileSync } from 'fs';
|
||||
import { appendFileSync } from 'node:fs';
|
||||
|
||||
try {
|
||||
appendFileSync('message.txt', 'data to append');
|
||||
@ -4730,7 +4730,7 @@ try {
|
||||
If `options` is a string, then it specifies the encoding:
|
||||
|
||||
```mjs
|
||||
import { appendFileSync } from 'fs';
|
||||
import { appendFileSync } from 'node:fs';
|
||||
|
||||
appendFileSync('message.txt', 'data to append', 'utf8');
|
||||
```
|
||||
@ -4740,7 +4740,7 @@ for appending (using `fs.open()` or `fs.openSync()`). The file descriptor will
|
||||
not be closed automatically.
|
||||
|
||||
```mjs
|
||||
import { openSync, closeSync, appendFileSync } from 'fs';
|
||||
import { openSync, closeSync, appendFileSync } from 'node:fs';
|
||||
|
||||
let fd;
|
||||
|
||||
@ -4844,7 +4844,7 @@ OR of two or more values (e.g.
|
||||
copy-on-write, then the operation will fail.
|
||||
|
||||
```mjs
|
||||
import { copyFileSync, constants } from 'fs';
|
||||
import { copyFileSync, constants } from 'node:fs';
|
||||
|
||||
// destination.txt will be created or overwritten by default.
|
||||
copyFileSync('source.txt', 'destination.txt');
|
||||
@ -4915,7 +4915,7 @@ parameter to `fs.exists()` accepts parameters that are inconsistent with other
|
||||
Node.js callbacks. `fs.existsSync()` does not use a callback.
|
||||
|
||||
```mjs
|
||||
import { existsSync } from 'fs';
|
||||
import { existsSync } from 'node:fs';
|
||||
|
||||
if (existsSync('/etc/passwd'))
|
||||
console.log('The path exists.');
|
||||
@ -5303,7 +5303,7 @@ Similar to [`fs.readFile()`][], when the path is a directory, the behavior of
|
||||
`fs.readFileSync()` is platform-specific.
|
||||
|
||||
```mjs
|
||||
import { readFileSync } from 'fs';
|
||||
import { readFileSync } from 'node:fs';
|
||||
|
||||
// macOS, Linux, and Windows
|
||||
readFileSync('<directory>');
|
||||
@ -5823,7 +5823,7 @@ Created by [`fs.opendir()`][], [`fs.opendirSync()`][], or
|
||||
[`fsPromises.opendir()`][].
|
||||
|
||||
```mjs
|
||||
import { opendir } from 'fs/promises';
|
||||
import { opendir } from 'node:fs/promises';
|
||||
|
||||
try {
|
||||
const dir = await opendir('./');
|
||||
@ -6100,7 +6100,7 @@ support. If `filename` is provided, it will be provided as a {Buffer} if
|
||||
`filename` will be a UTF-8 string.
|
||||
|
||||
```mjs
|
||||
import { watch } from 'fs';
|
||||
import { watch } from 'node:fs';
|
||||
// Example when handled through fs.watch() listener
|
||||
watch('./tmp', { encoding: 'buffer' }, (eventType, filename) => {
|
||||
if (filename) {
|
||||
@ -6778,7 +6778,7 @@ To use more than one constant, use the bitwise OR `|` operator.
|
||||
Example:
|
||||
|
||||
```mjs
|
||||
import { open, constants } from 'fs';
|
||||
import { open, constants } from 'node:fs';
|
||||
|
||||
const {
|
||||
O_RDWR,
|
||||
@ -7076,7 +7076,7 @@ It is important to correctly order the operations by awaiting the results
|
||||
of one before invoking the other:
|
||||
|
||||
```mjs
|
||||
import { rename, stat } from 'fs/promises';
|
||||
import { rename, stat } from 'node:fs/promises';
|
||||
|
||||
const from = '/tmp/hello';
|
||||
const to = '/tmp/world';
|
||||
@ -7091,7 +7091,7 @@ try {
|
||||
```
|
||||
|
||||
```cjs
|
||||
const { rename, stat } = require('fs/promises');
|
||||
const { rename, stat } = require('node:fs/promises');
|
||||
|
||||
(async function(from, to) {
|
||||
try {
|
||||
@ -7108,7 +7108,7 @@ Or, when using the callback APIs, move the `fs.stat()` call into the callback
|
||||
of the `fs.rename()` operation:
|
||||
|
||||
```mjs
|
||||
import { rename, stat } from 'fs';
|
||||
import { rename, stat } from 'node:fs';
|
||||
|
||||
rename('/tmp/hello', '/tmp/world', (err) => {
|
||||
if (err) throw err;
|
||||
@ -7120,7 +7120,7 @@ rename('/tmp/hello', '/tmp/world', (err) => {
|
||||
```
|
||||
|
||||
```cjs
|
||||
const { rename, stat } = require('fs/promises');
|
||||
const { rename, stat } = require('node:fs/promises');
|
||||
|
||||
rename('/tmp/hello', '/tmp/world', (err) => {
|
||||
if (err) throw err;
|
||||
@ -7145,7 +7145,7 @@ to the current working directory as determined by calling `process.cwd()`.
|
||||
Example using an absolute path on POSIX:
|
||||
|
||||
```mjs
|
||||
import { open } from 'fs/promises';
|
||||
import { open } from 'node:fs/promises';
|
||||
|
||||
let fd;
|
||||
try {
|
||||
@ -7159,7 +7159,7 @@ try {
|
||||
Example using a relative path on POSIX (relative to `process.cwd()`):
|
||||
|
||||
```mjs
|
||||
import { open } from 'fs/promises';
|
||||
import { open } from 'node:fs/promises';
|
||||
|
||||
let fd;
|
||||
try {
|
||||
@ -7176,11 +7176,11 @@ try {
|
||||
added: v7.6.0
|
||||
-->
|
||||
|
||||
For most `fs` module functions, the `path` or `filename` argument may be passed
|
||||
as a {URL} object using the `file:` protocol.
|
||||
For most `node:fs` module functions, the `path` or `filename` argument may be
|
||||
passed as a {URL} object using the `file:` protocol.
|
||||
|
||||
```mjs
|
||||
import { readFileSync } from 'fs';
|
||||
import { readFileSync } from 'node:fs';
|
||||
|
||||
readFileSync(new URL('file:///tmp/hello'));
|
||||
```
|
||||
@ -7194,7 +7194,7 @@ On Windows, `file:` {URL}s with a host name convert to UNC paths, while `file:`
|
||||
with no host name and no drive letter will result in an error:
|
||||
|
||||
```mjs
|
||||
import { readFileSync } from 'fs';
|
||||
import { readFileSync } from 'node:fs';
|
||||
// On Windows :
|
||||
|
||||
// - WHATWG file URLs with hostname convert to UNC path
|
||||
@ -7218,7 +7218,7 @@ On all other platforms, `file:` {URL}s with a host name are unsupported and
|
||||
will result in an error:
|
||||
|
||||
```mjs
|
||||
import { readFileSync } from 'fs';
|
||||
import { readFileSync } from 'node:fs';
|
||||
// On other platforms:
|
||||
|
||||
// - WHATWG file URLs with hostname are unsupported
|
||||
@ -7235,7 +7235,7 @@ A `file:` {URL} having encoded slash characters will result in an error on all
|
||||
platforms:
|
||||
|
||||
```mjs
|
||||
import { readFileSync } from 'fs';
|
||||
import { readFileSync } from 'node:fs';
|
||||
|
||||
// On Windows
|
||||
readFileSync(new URL('file:///C:/p/a/t/h/%2F'));
|
||||
@ -7253,7 +7253,7 @@ readFileSync(new URL('file:///p/a/t/h/%2f'));
|
||||
On Windows, `file:` {URL}s having encoded backslash will result in an error:
|
||||
|
||||
```mjs
|
||||
import { readFileSync } from 'fs';
|
||||
import { readFileSync } from 'node:fs';
|
||||
|
||||
// On Windows
|
||||
readFileSync(new URL('file:///C:/path/%5C'));
|
||||
@ -7273,8 +7273,8 @@ be relative or absolute:
|
||||
Example using an absolute path on POSIX:
|
||||
|
||||
```mjs
|
||||
import { open } from 'fs/promises';
|
||||
import { Buffer } from 'buffer';
|
||||
import { open } from 'node:fs/promises';
|
||||
import { Buffer } from 'node:buffer';
|
||||
|
||||
let fd;
|
||||
try {
|
||||
@ -7314,7 +7314,7 @@ are completed. Failure to do so will result in a memory leak that will
|
||||
eventually cause an application to crash.
|
||||
|
||||
```mjs
|
||||
import { open, close, fstat } from 'fs';
|
||||
import { open, close, fstat } from 'node:fs';
|
||||
|
||||
function closeFd(fd) {
|
||||
close(fd, (err) => {
|
||||
@ -7348,7 +7348,7 @@ that resources are not leaked. However, it is still required that they are
|
||||
closed when operations are completed:
|
||||
|
||||
```mjs
|
||||
import { open } from 'fs/promises';
|
||||
import { open } from 'node:fs/promises';
|
||||
|
||||
let file;
|
||||
try {
|
||||
|
||||
@ -348,7 +348,7 @@ added: v17.6.0
|
||||
|
||||
A browser-compatible implementation of {Crypto}. This global is available
|
||||
only if the Node.js binary was compiled with including support for the
|
||||
`crypto` module.
|
||||
`node:crypto` module.
|
||||
|
||||
## `crypto`
|
||||
|
||||
@ -372,7 +372,7 @@ added: v17.6.0
|
||||
|
||||
A browser-compatible implementation of {CryptoKey}. This global is available
|
||||
only if the Node.js binary was compiled with including support for the
|
||||
`crypto` module.
|
||||
`node:crypto` module.
|
||||
|
||||
## Class: `DecompressionStream`
|
||||
|
||||
@ -693,7 +693,7 @@ added: v17.6.0
|
||||
|
||||
A browser-compatible implementation of {SubtleCrypto}. This global is available
|
||||
only if the Node.js binary was compiled with including support for the
|
||||
`crypto` module.
|
||||
`node:crypto` module.
|
||||
|
||||
## `DOMException`
|
||||
|
||||
|
||||
@ -6,7 +6,7 @@
|
||||
|
||||
<!-- source_link=lib/http.js -->
|
||||
|
||||
To use the HTTP server and client one must `require('http')`.
|
||||
To use the HTTP server and client one must `require('node:http')`.
|
||||
|
||||
The HTTP interfaces in Node.js are designed to support many features
|
||||
of the protocol which have been traditionally difficult to use.
|
||||
@ -188,7 +188,7 @@ of these values set to their respective defaults.
|
||||
To configure any of them, a custom [`http.Agent`][] instance must be created.
|
||||
|
||||
```js
|
||||
const http = require('http');
|
||||
const http = require('node:http');
|
||||
const keepAliveAgent = new http.Agent({ keepAlive: true });
|
||||
options.agent = keepAliveAgent;
|
||||
http.request(options, onResponseCallback);
|
||||
@ -468,9 +468,9 @@ type other than {net.Socket}.
|
||||
A client and server pair demonstrating how to listen for the `'connect'` event:
|
||||
|
||||
```js
|
||||
const http = require('http');
|
||||
const net = require('net');
|
||||
const { URL } = require('url');
|
||||
const http = require('node:http');
|
||||
const net = require('node:net');
|
||||
const { URL } = require('node:url');
|
||||
|
||||
// Create an HTTP tunneling proxy
|
||||
const proxy = http.createServer((req, res) => {
|
||||
@ -564,7 +564,7 @@ HTTP version, status code, status message, key-value headers object,
|
||||
and array with the raw header names followed by their respective values.
|
||||
|
||||
```js
|
||||
const http = require('http');
|
||||
const http = require('node:http');
|
||||
|
||||
const options = {
|
||||
host: '127.0.0.1',
|
||||
@ -642,7 +642,7 @@ type other than {net.Socket}.
|
||||
A client server pair demonstrating how to listen for the `'upgrade'` event.
|
||||
|
||||
```js
|
||||
const http = require('http');
|
||||
const http = require('node:http');
|
||||
|
||||
// Create an HTTP server
|
||||
const server = http.createServer((req, res) => {
|
||||
@ -1010,7 +1010,7 @@ might be reused. But if server closes connection at unfortunate time, client
|
||||
may run into a 'ECONNRESET' error.
|
||||
|
||||
```js
|
||||
const http = require('http');
|
||||
const http = require('node:http');
|
||||
|
||||
// Server has a 5 seconds keep-alive timeout by default
|
||||
http
|
||||
@ -1034,7 +1034,7 @@ By marking a request whether it reused socket or not, we can do
|
||||
automatic error retry base on it.
|
||||
|
||||
```js
|
||||
const http = require('http');
|
||||
const http = require('node:http');
|
||||
const agent = new http.Agent({ keepAlive: true });
|
||||
|
||||
function retriableRequest() {
|
||||
@ -1144,7 +1144,7 @@ this property. In particular, the socket will not emit `'readable'` events
|
||||
because of how the protocol parser attaches to the socket.
|
||||
|
||||
```js
|
||||
const http = require('http');
|
||||
const http = require('node:http');
|
||||
const options = {
|
||||
host: 'www.google.com',
|
||||
};
|
||||
@ -1311,7 +1311,7 @@ written data it is immediately destroyed.
|
||||
`socket` is the [`net.Socket`][] object that the error originated from.
|
||||
|
||||
```js
|
||||
const http = require('http');
|
||||
const http = require('node:http');
|
||||
|
||||
const server = http.createServer((req, res) => {
|
||||
res.end();
|
||||
@ -1957,7 +1957,7 @@ because of how the protocol parser attaches to the socket. After
|
||||
`response.end()`, the property is nulled.
|
||||
|
||||
```js
|
||||
const http = require('http');
|
||||
const http = require('node:http');
|
||||
const server = http.createServer((req, res) => {
|
||||
const ip = res.socket.remoteAddress;
|
||||
const port = res.socket.remotePort;
|
||||
@ -2058,7 +2058,7 @@ it will switch to implicit header mode and flush the implicit headers.
|
||||
This sends a chunk of the response body. This method may
|
||||
be called multiple times to provide successive parts of the body.
|
||||
|
||||
In the `http` module, the response body is omitted when the
|
||||
In the `node:http` module, the response body is omitted when the
|
||||
request is a HEAD request. Similarly, the `204` and `304` responses
|
||||
_must not_ include a message body.
|
||||
|
||||
@ -3020,7 +3020,7 @@ The `requestListener` is a function which is automatically
|
||||
added to the [`'request'`][] event.
|
||||
|
||||
```cjs
|
||||
const http = require('http');
|
||||
const http = require('node:http');
|
||||
|
||||
// Create a local server to receive data from
|
||||
const server = http.createServer((req, res) => {
|
||||
@ -3034,7 +3034,7 @@ server.listen(8000);
|
||||
```
|
||||
|
||||
```cjs
|
||||
const http = require('http');
|
||||
const http = require('node:http');
|
||||
|
||||
// Create a local server to receive data from
|
||||
const server = http.createServer();
|
||||
@ -3272,7 +3272,7 @@ class. The `ClientRequest` instance is a writable stream. If one needs to
|
||||
upload a file with a POST request, then write to the `ClientRequest` object.
|
||||
|
||||
```js
|
||||
const http = require('http');
|
||||
const http = require('node:http');
|
||||
|
||||
const postData = JSON.stringify({
|
||||
'msg': 'Hello World!'
|
||||
@ -3471,7 +3471,7 @@ Examples:
|
||||
Example:
|
||||
|
||||
```js
|
||||
const { validateHeaderName } = require('http');
|
||||
const { validateHeaderName } = require('node:http');
|
||||
|
||||
try {
|
||||
validateHeaderName('');
|
||||
@ -3505,7 +3505,7 @@ or response. The HTTP module will automatically validate such headers.
|
||||
Examples:
|
||||
|
||||
```js
|
||||
const { validateHeaderValue } = require('http');
|
||||
const { validateHeaderValue } = require('node:http');
|
||||
|
||||
try {
|
||||
validateHeaderValue('x-my-header', undefined);
|
||||
|
||||
116
doc/api/http2.md
116
doc/api/http2.md
@ -23,25 +23,25 @@ changes:
|
||||
|
||||
<!-- source_link=lib/http2.js -->
|
||||
|
||||
The `http2` module provides an implementation of the [HTTP/2][] protocol. It
|
||||
can be accessed using:
|
||||
The `node:http2` module provides an implementation of the [HTTP/2][] protocol.
|
||||
It can be accessed using:
|
||||
|
||||
```js
|
||||
const http2 = require('http2');
|
||||
const http2 = require('node:http2');
|
||||
```
|
||||
|
||||
## Determining if crypto support is unavailable
|
||||
|
||||
It is possible for Node.js to be built without including support for the
|
||||
`crypto` module. In such cases, attempting to `import` from `http2` or
|
||||
calling `require('http2')` will result in an error being thrown.
|
||||
`node:crypto` module. In such cases, attempting to `import` from `node:http2` or
|
||||
calling `require('node:http2')` will result in an error being thrown.
|
||||
|
||||
When using CommonJS, the error thrown can be caught using try/catch:
|
||||
|
||||
```cjs
|
||||
let http2;
|
||||
try {
|
||||
http2 = require('http2');
|
||||
http2 = require('node:http2');
|
||||
} catch (err) {
|
||||
console.log('http2 support is disabled!');
|
||||
}
|
||||
@ -59,7 +59,7 @@ of Node.js where crypto support is not enabled, consider using the
|
||||
```mjs
|
||||
let http2;
|
||||
try {
|
||||
http2 = await import('http2');
|
||||
http2 = await import('node:http2');
|
||||
} catch (err) {
|
||||
console.log('http2 support is disabled!');
|
||||
}
|
||||
@ -85,8 +85,8 @@ Since there are no browsers known that support
|
||||
with browser clients.
|
||||
|
||||
```js
|
||||
const http2 = require('http2');
|
||||
const fs = require('fs');
|
||||
const http2 = require('node:http2');
|
||||
const fs = require('node:fs');
|
||||
|
||||
const server = http2.createSecureServer({
|
||||
key: fs.readFileSync('localhost-privkey.pem'),
|
||||
@ -118,8 +118,8 @@ openssl req -x509 -newkey rsa:2048 -nodes -sha256 -subj '/CN=localhost' \
|
||||
The following illustrates an HTTP/2 client:
|
||||
|
||||
```js
|
||||
const http2 = require('http2');
|
||||
const fs = require('fs');
|
||||
const http2 = require('node:http2');
|
||||
const fs = require('node:fs');
|
||||
const client = http2.connect('https://localhost:8443', {
|
||||
ca: fs.readFileSync('localhost-cert.pem')
|
||||
});
|
||||
@ -320,7 +320,7 @@ added: v8.4.0
|
||||
The `'stream'` event is emitted when a new `Http2Stream` is created.
|
||||
|
||||
```js
|
||||
const http2 = require('http2');
|
||||
const http2 = require('node:http2');
|
||||
session.on('stream', (stream, headers, flags) => {
|
||||
const method = headers[':method'];
|
||||
const path = headers[':path'];
|
||||
@ -340,7 +340,7 @@ and would instead register a handler for the `'stream'` event emitted by the
|
||||
`http2.createSecureServer()`, respectively, as in the example below:
|
||||
|
||||
```js
|
||||
const http2 = require('http2');
|
||||
const http2 = require('node:http2');
|
||||
|
||||
// Create an unencrypted HTTP/2 server
|
||||
const server = http2.createServer();
|
||||
@ -607,7 +607,7 @@ The `windowSize` is the total window size to set, not
|
||||
the delta.
|
||||
|
||||
```js
|
||||
const http2 = require('http2');
|
||||
const http2 = require('node:http2');
|
||||
|
||||
const server = http2.createServer();
|
||||
const expectedWindowSize = 2 ** 20;
|
||||
@ -763,7 +763,7 @@ added: v9.4.0
|
||||
Submits an `ALTSVC` frame (as defined by [RFC 7838][]) to the connected client.
|
||||
|
||||
```js
|
||||
const http2 = require('http2');
|
||||
const http2 = require('node:http2');
|
||||
|
||||
const server = http2.createServer();
|
||||
server.on('session', (session) => {
|
||||
@ -829,7 +829,7 @@ to advertise the set of origins for which the server is capable of providing
|
||||
authoritative responses.
|
||||
|
||||
```js
|
||||
const http2 = require('http2');
|
||||
const http2 = require('node:http2');
|
||||
const options = getSecureOptionsSomehow();
|
||||
const server = http2.createSecureServer(options);
|
||||
server.on('stream', (stream) => {
|
||||
@ -856,7 +856,7 @@ Alternatively, the `origins` option may be used when creating a new HTTP/2
|
||||
server using the `http2.createSecureServer()` method:
|
||||
|
||||
```js
|
||||
const http2 = require('http2');
|
||||
const http2 = require('node:http2');
|
||||
const options = getSecureOptionsSomehow();
|
||||
options.origins = ['https://example.com', 'https://example.org'];
|
||||
const server = http2.createSecureServer(options);
|
||||
@ -890,7 +890,7 @@ ID. If no `origin` is provided in the `ALTSVC` frame, `origin` will
|
||||
be an empty string.
|
||||
|
||||
```js
|
||||
const http2 = require('http2');
|
||||
const http2 = require('node:http2');
|
||||
const client = http2.connect('https://example.org');
|
||||
|
||||
client.on('altsvc', (alt, origin, streamId) => {
|
||||
@ -914,7 +914,7 @@ the client. The event is emitted with an array of `origin` strings. The
|
||||
origins.
|
||||
|
||||
```js
|
||||
const http2 = require('http2');
|
||||
const http2 = require('node:http2');
|
||||
const client = http2.connect('https://example.org');
|
||||
|
||||
client.on('origin', (origins) => {
|
||||
@ -967,7 +967,7 @@ This method is only available if `http2session.type` is equal to
|
||||
`http2.constants.NGHTTP2_SESSION_CLIENT`.
|
||||
|
||||
```js
|
||||
const http2 = require('http2');
|
||||
const http2 = require('node:http2');
|
||||
const clientSession = http2.connect('https://localhost:1234');
|
||||
const {
|
||||
HTTP2_HEADER_PATH,
|
||||
@ -1387,7 +1387,7 @@ changes:
|
||||
* `callback` {Function}
|
||||
|
||||
```js
|
||||
const http2 = require('http2');
|
||||
const http2 = require('node:http2');
|
||||
const client = http2.connect('http://example.org:8000');
|
||||
const { NGHTTP2_CANCEL } = http2.constants;
|
||||
const req = client.request({ ':path': '/' });
|
||||
@ -1436,7 +1436,7 @@ in order to keep the `Http2Stream` open after the final `DATA` frame so that
|
||||
trailers can be sent.
|
||||
|
||||
```js
|
||||
const http2 = require('http2');
|
||||
const http2 = require('node:http2');
|
||||
const server = http2.createServer();
|
||||
server.on('stream', (stream) => {
|
||||
stream.respond(undefined, { waitForTrailers: true });
|
||||
@ -1518,7 +1518,7 @@ invoked with two arguments: an `Object` containing the received
|
||||
[HTTP/2 Headers Object][], and flags associated with the headers.
|
||||
|
||||
```js
|
||||
const http2 = require('http2');
|
||||
const http2 = require('node:http2');
|
||||
const client = http2.connect('https://localhost');
|
||||
const req = client.request({ ':path': '/' });
|
||||
req.on('response', (headers, flags) => {
|
||||
@ -1604,7 +1604,7 @@ instance created for the push stream passed as the second argument, or an
|
||||
`Error` passed as the first argument.
|
||||
|
||||
```js
|
||||
const http2 = require('http2');
|
||||
const http2 = require('node:http2');
|
||||
const server = http2.createServer();
|
||||
server.on('stream', (stream) => {
|
||||
stream.respond({ ':status': 200 });
|
||||
@ -1644,7 +1644,7 @@ changes:
|
||||
`'wantTrailers'` event after the final `DATA` frame has been sent.
|
||||
|
||||
```js
|
||||
const http2 = require('http2');
|
||||
const http2 = require('node:http2');
|
||||
const server = http2.createServer();
|
||||
server.on('stream', (stream) => {
|
||||
stream.respond({ ':status': 200 });
|
||||
@ -1663,7 +1663,7 @@ close when the final `DATA` frame is transmitted. User code must call either
|
||||
`Http2Stream`.
|
||||
|
||||
```js
|
||||
const http2 = require('http2');
|
||||
const http2 = require('node:http2');
|
||||
const server = http2.createServer();
|
||||
server.on('stream', (stream) => {
|
||||
stream.respond({ ':status': 200 }, { waitForTrailers: true });
|
||||
@ -1711,8 +1711,8 @@ When used, the `Http2Stream` object's `Duplex` interface will be closed
|
||||
automatically.
|
||||
|
||||
```js
|
||||
const http2 = require('http2');
|
||||
const fs = require('fs');
|
||||
const http2 = require('node:http2');
|
||||
const fs = require('node:fs');
|
||||
|
||||
const server = http2.createServer();
|
||||
server.on('stream', (stream) => {
|
||||
@ -1756,8 +1756,8 @@ close when the final `DATA` frame is transmitted. User code _must_ call either
|
||||
`Http2Stream`.
|
||||
|
||||
```js
|
||||
const http2 = require('http2');
|
||||
const fs = require('fs');
|
||||
const http2 = require('node:http2');
|
||||
const fs = require('node:fs');
|
||||
|
||||
const server = http2.createServer();
|
||||
server.on('stream', (stream) => {
|
||||
@ -1823,7 +1823,7 @@ the stream will be destroyed.
|
||||
Example using a file path:
|
||||
|
||||
```js
|
||||
const http2 = require('http2');
|
||||
const http2 = require('node:http2');
|
||||
const server = http2.createServer();
|
||||
server.on('stream', (stream) => {
|
||||
function statCheck(stat, headers) {
|
||||
@ -1858,7 +1858,7 @@ results to determine if the file has been modified to return an appropriate
|
||||
`304` response:
|
||||
|
||||
```js
|
||||
const http2 = require('http2');
|
||||
const http2 = require('node:http2');
|
||||
const server = http2.createServer();
|
||||
server.on('stream', (stream) => {
|
||||
function statCheck(stat, headers) {
|
||||
@ -1893,7 +1893,7 @@ close when the final `DATA` frame is transmitted. User code must call either
|
||||
`Http2Stream`.
|
||||
|
||||
```js
|
||||
const http2 = require('http2');
|
||||
const http2 = require('node:http2');
|
||||
const server = http2.createServer();
|
||||
server.on('stream', (stream) => {
|
||||
stream.respondWithFile('/some/file',
|
||||
@ -1914,8 +1914,8 @@ added: v8.4.0
|
||||
* Extends: {net.Server}
|
||||
|
||||
Instances of `Http2Server` are created using the `http2.createServer()`
|
||||
function. The `Http2Server` class is not exported directly by the `http2`
|
||||
module.
|
||||
function. The `Http2Server` class is not exported directly by the
|
||||
`node:http2` module.
|
||||
|
||||
#### Event: `'checkContinue'`
|
||||
|
||||
@ -2003,7 +2003,7 @@ an `Http2Session` associated with the server.
|
||||
See also [`Http2Session`'s `'stream'` event][].
|
||||
|
||||
```js
|
||||
const http2 = require('http2');
|
||||
const http2 = require('node:http2');
|
||||
const {
|
||||
HTTP2_HEADER_METHOD,
|
||||
HTTP2_HEADER_PATH,
|
||||
@ -2130,7 +2130,7 @@ added: v8.4.0
|
||||
|
||||
Instances of `Http2SecureServer` are created using the
|
||||
`http2.createSecureServer()` function. The `Http2SecureServer` class is not
|
||||
exported directly by the `http2` module.
|
||||
exported directly by the `node:http2` module.
|
||||
|
||||
#### Event: `'checkContinue'`
|
||||
|
||||
@ -2218,7 +2218,7 @@ an `Http2Session` associated with the server.
|
||||
See also [`Http2Session`'s `'stream'` event][].
|
||||
|
||||
```js
|
||||
const http2 = require('http2');
|
||||
const http2 = require('node:http2');
|
||||
const {
|
||||
HTTP2_HEADER_METHOD,
|
||||
HTTP2_HEADER_PATH,
|
||||
@ -2481,7 +2481,7 @@ Since there are no browsers known that support
|
||||
with browser clients.
|
||||
|
||||
```js
|
||||
const http2 = require('http2');
|
||||
const http2 = require('node:http2');
|
||||
|
||||
// Create an unencrypted HTTP/2 server.
|
||||
// Since there are no browsers known that support
|
||||
@ -2619,8 +2619,8 @@ Returns a `tls.Server` instance that creates and manages `Http2Session`
|
||||
instances.
|
||||
|
||||
```js
|
||||
const http2 = require('http2');
|
||||
const fs = require('fs');
|
||||
const http2 = require('node:http2');
|
||||
const fs = require('node:fs');
|
||||
|
||||
const options = {
|
||||
key: fs.readFileSync('server-key.pem'),
|
||||
@ -2747,7 +2747,7 @@ changes:
|
||||
Returns a `ClientHttp2Session` instance.
|
||||
|
||||
```js
|
||||
const http2 = require('http2');
|
||||
const http2 = require('node:http2');
|
||||
const client = http2.connect('https://localhost:1234');
|
||||
|
||||
/* Use the client */
|
||||
@ -2809,7 +2809,7 @@ HTTP/2 settings as specified in the [HTTP/2][] specification. This is intended
|
||||
for use with the `HTTP2-Settings` header field.
|
||||
|
||||
```js
|
||||
const http2 = require('http2');
|
||||
const http2 = require('node:http2');
|
||||
|
||||
const packed = http2.getPackedSettings({ enablePush: false });
|
||||
|
||||
@ -2883,7 +2883,7 @@ For incoming headers:
|
||||
* For all other headers, the values are joined together with ', '.
|
||||
|
||||
```js
|
||||
const http2 = require('http2');
|
||||
const http2 = require('node:http2');
|
||||
const server = http2.createServer();
|
||||
server.on('stream', (stream, headers) => {
|
||||
console.log(headers[':path']);
|
||||
@ -2970,7 +2970,7 @@ All additional properties on the settings object are ignored.
|
||||
### Error handling
|
||||
|
||||
There are several types of error conditions that may arise when using the
|
||||
`http2` module:
|
||||
`node:http2` module:
|
||||
|
||||
Validation errors occur when an incorrect argument, option, or setting value is
|
||||
passed in. These will always be reported by a synchronous `throw`.
|
||||
@ -3016,7 +3016,7 @@ To receive pushed streams on the client, set a listener for the `'stream'`
|
||||
event on the `ClientHttp2Session`:
|
||||
|
||||
```js
|
||||
const http2 = require('http2');
|
||||
const http2 = require('node:http2');
|
||||
|
||||
const client = http2.connect('http://localhost');
|
||||
|
||||
@ -3038,7 +3038,7 @@ for TCP/IP connections.
|
||||
A simple TCP Server:
|
||||
|
||||
```js
|
||||
const net = require('net');
|
||||
const net = require('node:net');
|
||||
|
||||
const server = net.createServer((socket) => {
|
||||
let name = '';
|
||||
@ -3053,9 +3053,9 @@ server.listen(8000);
|
||||
An HTTP/2 CONNECT proxy:
|
||||
|
||||
```js
|
||||
const http2 = require('http2');
|
||||
const http2 = require('node:http2');
|
||||
const { NGHTTP2_REFUSED_STREAM } = http2.constants;
|
||||
const net = require('net');
|
||||
const net = require('node:net');
|
||||
|
||||
const proxy = http2.createServer();
|
||||
proxy.on('stream', (stream, headers) => {
|
||||
@ -3083,7 +3083,7 @@ proxy.listen(8001);
|
||||
An HTTP/2 CONNECT client:
|
||||
|
||||
```js
|
||||
const http2 = require('http2');
|
||||
const http2 = require('node:http2');
|
||||
|
||||
const client = http2.connect('http://localhost:8001');
|
||||
|
||||
@ -3117,7 +3117,7 @@ The use of the Extended CONNECT Protocol is enabled by HTTP/2 servers by using
|
||||
the `enableConnectProtocol` setting:
|
||||
|
||||
```js
|
||||
const http2 = require('http2');
|
||||
const http2 = require('node:http2');
|
||||
const settings = { enableConnectProtocol: true };
|
||||
const server = http2.createServer({ settings });
|
||||
```
|
||||
@ -3127,7 +3127,7 @@ the extended CONNECT may be used, it may send `CONNECT` requests that use the
|
||||
`':protocol'` HTTP/2 pseudo-header:
|
||||
|
||||
```js
|
||||
const http2 = require('http2');
|
||||
const http2 = require('node:http2');
|
||||
const client = http2.connect('http://localhost:8080');
|
||||
client.on('remoteSettings', (settings) => {
|
||||
if (settings.enableConnectProtocol) {
|
||||
@ -3150,7 +3150,7 @@ The following example creates an HTTP/2 server using the compatibility
|
||||
API:
|
||||
|
||||
```js
|
||||
const http2 = require('http2');
|
||||
const http2 = require('node:http2');
|
||||
const server = http2.createServer((req, res) => {
|
||||
res.setHeader('Content-Type', 'text/html');
|
||||
res.setHeader('X-Foo', 'bar');
|
||||
@ -3179,8 +3179,8 @@ features of HTTP/2.
|
||||
The following example creates a server that supports both protocols:
|
||||
|
||||
```js
|
||||
const { createSecureServer } = require('http2');
|
||||
const { readFileSync } = require('fs');
|
||||
const { createSecureServer } = require('node:http2');
|
||||
const { readFileSync } = require('node:fs');
|
||||
|
||||
const cert = readFileSync('./cert.pem');
|
||||
const key = readFileSync('./key.pem');
|
||||
@ -3861,7 +3861,7 @@ more information.
|
||||
All other interactions will be routed directly to the socket.
|
||||
|
||||
```js
|
||||
const http2 = require('http2');
|
||||
const http2 = require('node:http2');
|
||||
const server = http2.createServer((req, res) => {
|
||||
const ip = req.socket.remoteAddress;
|
||||
const port = req.socket.remotePort;
|
||||
@ -3938,7 +3938,7 @@ it will switch to implicit header mode and flush the implicit headers.
|
||||
This sends a chunk of the response body. This method may
|
||||
be called multiple times to provide successive parts of the body.
|
||||
|
||||
In the `http` module, the response body is omitted when the
|
||||
In the `node:http` module, the response body is omitted when the
|
||||
request is a HEAD request. Similarly, the `204` and `304` responses
|
||||
_must not_ include a message body.
|
||||
|
||||
@ -4042,7 +4042,7 @@ The [Performance Observer][] API can be used to collect basic performance
|
||||
metrics for each `Http2Session` and `Http2Stream` instance.
|
||||
|
||||
```js
|
||||
const { PerformanceObserver } = require('perf_hooks');
|
||||
const { PerformanceObserver } = require('node:perf_hooks');
|
||||
|
||||
const obs = new PerformanceObserver((items) => {
|
||||
const entry = items.getEntries()[0];
|
||||
|
||||
@ -12,8 +12,8 @@ separate module.
|
||||
## Determining if crypto support is unavailable
|
||||
|
||||
It is possible for Node.js to be built without including support for the
|
||||
`crypto` module. In such cases, attempting to `import` from `https` or
|
||||
calling `require('https')` will result in an error being thrown.
|
||||
`node:crypto` module. In such cases, attempting to `import` from `https` or
|
||||
calling `require('node:https')` will result in an error being thrown.
|
||||
|
||||
When using CommonJS, the error thrown can be caught using try/catch:
|
||||
|
||||
@ -22,7 +22,7 @@ When using CommonJS, the error thrown can be caught using try/catch:
|
||||
```cjs
|
||||
let https;
|
||||
try {
|
||||
https = require('https');
|
||||
https = require('node:https');
|
||||
} catch (err) {
|
||||
console.log('https support is disabled!');
|
||||
}
|
||||
@ -40,7 +40,7 @@ of Node.js where crypto support is not enabled, consider using the
|
||||
```mjs
|
||||
let https;
|
||||
try {
|
||||
https = await import('https');
|
||||
https = await import('node:https');
|
||||
} catch (err) {
|
||||
console.log('https support is disabled!');
|
||||
}
|
||||
@ -215,8 +215,8 @@ added: v0.3.4
|
||||
|
||||
```js
|
||||
// curl -k https://localhost:8000/
|
||||
const https = require('https');
|
||||
const fs = require('fs');
|
||||
const https = require('node:https');
|
||||
const fs = require('node:fs');
|
||||
|
||||
const options = {
|
||||
key: fs.readFileSync('test/fixtures/keys/agent2-key.pem'),
|
||||
@ -232,8 +232,8 @@ https.createServer(options, (req, res) => {
|
||||
Or
|
||||
|
||||
```js
|
||||
const https = require('https');
|
||||
const fs = require('fs');
|
||||
const https = require('node:https');
|
||||
const fs = require('node:fs');
|
||||
|
||||
const options = {
|
||||
pfx: fs.readFileSync('test/fixtures/test_cert.pfx'),
|
||||
@ -274,7 +274,7 @@ string, it is automatically parsed with [`new URL()`][]. If it is a [`URL`][]
|
||||
object, it will be automatically converted to an ordinary `options` object.
|
||||
|
||||
```js
|
||||
const https = require('https');
|
||||
const https = require('node:https');
|
||||
|
||||
https.get('https://encrypted.google.com/', (res) => {
|
||||
console.log('statusCode:', res.statusCode);
|
||||
@ -353,7 +353,7 @@ class. The `ClientRequest` instance is a writable stream. If one needs to
|
||||
upload a file with a POST request, then write to the `ClientRequest` object.
|
||||
|
||||
```js
|
||||
const https = require('https');
|
||||
const https = require('node:https');
|
||||
|
||||
const options = {
|
||||
hostname: 'encrypted.google.com',
|
||||
@ -427,9 +427,9 @@ Example pinning on certificate fingerprint, or the public key (similar to
|
||||
`pin-sha256`):
|
||||
|
||||
```js
|
||||
const tls = require('tls');
|
||||
const https = require('https');
|
||||
const crypto = require('crypto');
|
||||
const tls = require('node:tls');
|
||||
const https = require('node:https');
|
||||
const crypto = require('node:crypto');
|
||||
|
||||
function sha256(s) {
|
||||
return crypto.createHash('sha256').update(s).digest('base64');
|
||||
|
||||
@ -39,7 +39,7 @@
|
||||
* [Internationalization](intl.md)
|
||||
* [Modules: CommonJS modules](modules.md)
|
||||
* [Modules: ECMAScript modules](esm.md)
|
||||
* [Modules: `module` API](module.md)
|
||||
* [Modules: `node:module` API](module.md)
|
||||
* [Modules: Packages](packages.md)
|
||||
* [Net](net.md)
|
||||
* [OS](os.md)
|
||||
|
||||
@ -6,12 +6,13 @@
|
||||
|
||||
<!-- source_link=lib/inspector.js -->
|
||||
|
||||
The `inspector` module provides an API for interacting with the V8 inspector.
|
||||
The `node:inspector` module provides an API for interacting with the V8
|
||||
inspector.
|
||||
|
||||
It can be accessed using:
|
||||
|
||||
```js
|
||||
const inspector = require('inspector');
|
||||
const inspector = require('node:inspector');
|
||||
```
|
||||
|
||||
## `inspector.close()`
|
||||
@ -23,7 +24,7 @@ Deactivate the inspector. Blocks until there are no active connections.
|
||||
* {Object} An object to send messages to the remote inspector console.
|
||||
|
||||
```js
|
||||
require('inspector').console.log('a message');
|
||||
require('node:inspector').console.log('a message');
|
||||
```
|
||||
|
||||
The inspector console does not have API parity with Node.js
|
||||
@ -209,8 +210,8 @@ protocol.
|
||||
Here's an example showing how to use the [CPU Profiler][]:
|
||||
|
||||
```js
|
||||
const inspector = require('inspector');
|
||||
const fs = require('fs');
|
||||
const inspector = require('node:inspector');
|
||||
const fs = require('node:fs');
|
||||
const session = new inspector.Session();
|
||||
session.connect();
|
||||
|
||||
@ -234,8 +235,8 @@ session.post('Profiler.enable', () => {
|
||||
Here's an example showing how to use the [Heap Profiler][]:
|
||||
|
||||
```js
|
||||
const inspector = require('inspector');
|
||||
const fs = require('fs');
|
||||
const inspector = require('node:inspector');
|
||||
const fs = require('node:fs');
|
||||
const session = new inspector.Session();
|
||||
|
||||
const fd = fs.openSync('profile.heapsnapshot', 'w');
|
||||
|
||||
@ -18,9 +18,9 @@ programs. Some of them are:
|
||||
* Locale-sensitive methods like [`String.prototype.localeCompare()`][] and
|
||||
[`Date.prototype.toLocaleString()`][]
|
||||
* The [WHATWG URL parser][]'s [internationalized domain names][] (IDNs) support
|
||||
* [`require('buffer').transcode()`][]
|
||||
* [`require('node:buffer').transcode()`][]
|
||||
* More accurate [REPL][] line editing
|
||||
* [`require('util').TextDecoder`][]
|
||||
* [`require('node:util').TextDecoder`][]
|
||||
* [`RegExp` Unicode Property Escapes][]
|
||||
|
||||
Node.js and the underlying V8 engine use
|
||||
@ -44,21 +44,21 @@ in [BUILDING.md][].
|
||||
An overview of available Node.js and JavaScript features for each `configure`
|
||||
option:
|
||||
|
||||
| Feature | `none` | `system-icu` | `small-icu` | `full-icu` |
|
||||
| --------------------------------------- | --------------------------------- | ---------------------------- | ---------------------- | ---------- |
|
||||
| [`String.prototype.normalize()`][] | none (function is no-op) | full | full | full |
|
||||
| `String.prototype.to*Case()` | full | full | full | full |
|
||||
| [`Intl`][] | none (object does not exist) | partial/full (depends on OS) | partial (English-only) | full |
|
||||
| [`String.prototype.localeCompare()`][] | partial (not locale-aware) | full | full | full |
|
||||
| `String.prototype.toLocale*Case()` | partial (not locale-aware) | full | full | full |
|
||||
| [`Number.prototype.toLocaleString()`][] | partial (not locale-aware) | partial/full (depends on OS) | partial (English-only) | full |
|
||||
| `Date.prototype.toLocale*String()` | partial (not locale-aware) | partial/full (depends on OS) | partial (English-only) | full |
|
||||
| [Legacy URL Parser][] | partial (no IDN support) | full | full | full |
|
||||
| [WHATWG URL Parser][] | partial (no IDN support) | full | full | full |
|
||||
| [`require('buffer').transcode()`][] | none (function does not exist) | full | full | full |
|
||||
| [REPL][] | partial (inaccurate line editing) | full | full | full |
|
||||
| [`require('util').TextDecoder`][] | partial (basic encodings support) | partial/full (depends on OS) | partial (Unicode-only) | full |
|
||||
| [`RegExp` Unicode Property Escapes][] | none (invalid `RegExp` error) | full | full | full |
|
||||
| Feature | `none` | `system-icu` | `small-icu` | `full-icu` |
|
||||
| ---------------------------------------- | --------------------------------- | ---------------------------- | ---------------------- | ---------- |
|
||||
| [`String.prototype.normalize()`][] | none (function is no-op) | full | full | full |
|
||||
| `String.prototype.to*Case()` | full | full | full | full |
|
||||
| [`Intl`][] | none (object does not exist) | partial/full (depends on OS) | partial (English-only) | full |
|
||||
| [`String.prototype.localeCompare()`][] | partial (not locale-aware) | full | full | full |
|
||||
| `String.prototype.toLocale*Case()` | partial (not locale-aware) | full | full | full |
|
||||
| [`Number.prototype.toLocaleString()`][] | partial (not locale-aware) | partial/full (depends on OS) | partial (English-only) | full |
|
||||
| `Date.prototype.toLocale*String()` | partial (not locale-aware) | partial/full (depends on OS) | partial (English-only) | full |
|
||||
| [Legacy URL Parser][] | partial (no IDN support) | full | full | full |
|
||||
| [WHATWG URL Parser][] | partial (no IDN support) | full | full | full |
|
||||
| [`require('node:buffer').transcode()`][] | none (function does not exist) | full | full | full |
|
||||
| [REPL][] | partial (inaccurate line editing) | full | full | full |
|
||||
| [`require('node:util').TextDecoder`][] | partial (basic encodings support) | partial/full (depends on OS) | partial (Unicode-only) | full |
|
||||
| [`RegExp` Unicode Property Escapes][] | none (invalid `RegExp` error) | full | full | full |
|
||||
|
||||
The "(not locale-aware)" designation denotes that the function carries out its
|
||||
operation just like the non-`Locale` version of the function, if one
|
||||
@ -211,8 +211,8 @@ to be helpful:
|
||||
[`String.prototype.normalize()`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/normalize
|
||||
[`String.prototype.toLowerCase()`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/toLowerCase
|
||||
[`String.prototype.toUpperCase()`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/toUpperCase
|
||||
[`require('buffer').transcode()`]: buffer.md#buffertranscodesource-fromenc-toenc
|
||||
[`require('util').TextDecoder`]: util.md#class-utiltextdecoder
|
||||
[`require('node:buffer').transcode()`]: buffer.md#buffertranscodesource-fromenc-toenc
|
||||
[`require('node:util').TextDecoder`]: util.md#class-utiltextdecoder
|
||||
[btest402]: https://github.com/srl295/btest402
|
||||
[full-icu]: https://www.npmjs.com/package/full-icu
|
||||
[internationalized domain names]: https://en.wikipedia.org/wiki/Internationalized_domain_name
|
||||
|
||||
@ -1,4 +1,4 @@
|
||||
# Modules: `module` API
|
||||
# Modules: `node:module` API
|
||||
|
||||
<!--introduced_in=v12.20.0-->
|
||||
|
||||
@ -12,7 +12,7 @@ added: v0.3.7
|
||||
|
||||
Provides general utility methods when interacting with instances of
|
||||
`Module`, the [`module`][] variable often seen in [CommonJS][] modules. Accessed
|
||||
via `import 'module'` or `require('module')`.
|
||||
via `import 'node:module'` or `require('node:module')`.
|
||||
|
||||
### `module.builtinModules`
|
||||
|
||||
@ -34,13 +34,13 @@ by the [module wrapper][]. To access it, require the `Module` module:
|
||||
```mjs
|
||||
// module.mjs
|
||||
// In an ECMAScript module
|
||||
import { builtinModules as builtin } from 'module';
|
||||
import { builtinModules as builtin } from 'node:module';
|
||||
```
|
||||
|
||||
```cjs
|
||||
// module.cjs
|
||||
// In a CommonJS module
|
||||
const builtin = require('module').builtinModules;
|
||||
const builtin = require('node:module').builtinModules;
|
||||
```
|
||||
|
||||
### `module.createRequire(filename)`
|
||||
@ -55,7 +55,7 @@ added: v12.2.0
|
||||
* Returns: {require} Require function
|
||||
|
||||
```mjs
|
||||
import { createRequire } from 'module';
|
||||
import { createRequire } from 'node:module';
|
||||
const require = createRequire(import.meta.url);
|
||||
|
||||
// sibling-module.js is a CommonJS module.
|
||||
@ -73,9 +73,9 @@ builtin [ES Modules][] to match the properties of the [CommonJS][] exports. It
|
||||
does not add or remove exported names from the [ES Modules][].
|
||||
|
||||
```js
|
||||
const fs = require('fs');
|
||||
const assert = require('assert');
|
||||
const { syncBuiltinESMExports } = require('module');
|
||||
const fs = require('node:fs');
|
||||
const assert = require('node:assert');
|
||||
const { syncBuiltinESMExports } = require('node:module');
|
||||
|
||||
fs.readFile = newAPI;
|
||||
|
||||
@ -89,7 +89,7 @@ fs.newAPI = newAPI;
|
||||
|
||||
syncBuiltinESMExports();
|
||||
|
||||
import('fs').then((esmFS) => {
|
||||
import('node:fs').then((esmFS) => {
|
||||
// It syncs the existing readFile property with the new value
|
||||
assert.strictEqual(esmFS.readFile, newAPI);
|
||||
// readFileSync has been deleted from the required fs
|
||||
@ -122,13 +122,13 @@ To enable source map parsing, Node.js must be run with the flag
|
||||
```mjs
|
||||
// module.mjs
|
||||
// In an ECMAScript module
|
||||
import { findSourceMap, SourceMap } from 'module';
|
||||
import { findSourceMap, SourceMap } from 'node:module';
|
||||
```
|
||||
|
||||
```cjs
|
||||
// module.cjs
|
||||
// In a CommonJS module
|
||||
const { findSourceMap, SourceMap } = require('module');
|
||||
const { findSourceMap, SourceMap } = require('node:module');
|
||||
```
|
||||
|
||||
<!-- Anchors to make sure old links find a target -->
|
||||
|
||||
@ -690,7 +690,7 @@ const myLocalModule = require('./path/myLocalModule');
|
||||
const jsonData = require('./path/filename.json');
|
||||
|
||||
// Importing a module from node_modules or Node.js built-in module:
|
||||
const crypto = require('crypto');
|
||||
const crypto = require('node:crypto');
|
||||
```
|
||||
|
||||
#### `require.cache`
|
||||
@ -714,13 +714,13 @@ Use with care!
|
||||
<!-- eslint-disable node-core/no-duplicate-requires -->
|
||||
|
||||
```js
|
||||
const assert = require('assert');
|
||||
const realFs = require('fs');
|
||||
const assert = require('node:assert');
|
||||
const realFs = require('node:fs');
|
||||
|
||||
const fakeFs = {};
|
||||
require.cache.fs = { exports: fakeFs };
|
||||
|
||||
assert.strictEqual(require('fs'), fakeFs);
|
||||
assert.strictEqual(require('node:fs'), fakeFs);
|
||||
assert.strictEqual(require('node:fs'), realFs);
|
||||
```
|
||||
|
||||
@ -873,7 +873,7 @@ which is probably not what is desired.
|
||||
For example, suppose we were making a module called `a.js`:
|
||||
|
||||
```js
|
||||
const EventEmitter = require('events');
|
||||
const EventEmitter = require('node:events');
|
||||
|
||||
module.exports = new EventEmitter();
|
||||
|
||||
|
||||
@ -8,19 +8,19 @@
|
||||
|
||||
<!-- source_link=lib/net.js -->
|
||||
|
||||
The `net` module provides an asynchronous network API for creating stream-based
|
||||
The `node:net` module provides an asynchronous network API for creating stream-based
|
||||
TCP or [IPC][] servers ([`net.createServer()`][]) and clients
|
||||
([`net.createConnection()`][]).
|
||||
|
||||
It can be accessed using:
|
||||
|
||||
```js
|
||||
const net = require('net');
|
||||
const net = require('node:net');
|
||||
```
|
||||
|
||||
## IPC support
|
||||
|
||||
The `net` module supports IPC with named pipes on Windows, and Unix domain
|
||||
The `node:net` module supports IPC with named pipes on Windows, and Unix domain
|
||||
sockets on other operating systems.
|
||||
|
||||
### Identifying paths for IPC connections
|
||||
@ -892,7 +892,7 @@ For both types, available `options` include:
|
||||
Following is an example of a client using the `onread` option:
|
||||
|
||||
```js
|
||||
const net = require('net');
|
||||
const net = require('node:net');
|
||||
net.connect({
|
||||
port: 80,
|
||||
onread: {
|
||||
@ -1348,7 +1348,7 @@ Following is an example of a client of the echo server described
|
||||
in the [`net.createServer()`][] section:
|
||||
|
||||
```js
|
||||
const net = require('net');
|
||||
const net = require('node:net');
|
||||
const client = net.createConnection({ port: 8124 }, () => {
|
||||
// 'connect' listener.
|
||||
console.log('connected to server!');
|
||||
@ -1464,7 +1464,7 @@ Here is an example of a TCP echo server which listens for connections
|
||||
on port 8124:
|
||||
|
||||
```js
|
||||
const net = require('net');
|
||||
const net = require('node:net');
|
||||
const server = net.createServer((c) => {
|
||||
// 'connection' listener.
|
||||
console.log('client connected');
|
||||
|
||||
@ -6,11 +6,11 @@
|
||||
|
||||
<!-- source_link=lib/os.js -->
|
||||
|
||||
The `os` module provides operating system-related utility methods and
|
||||
The `node:os` module provides operating system-related utility methods and
|
||||
properties. It can be accessed using:
|
||||
|
||||
```js
|
||||
const os = require('os');
|
||||
const os = require('node:os');
|
||||
```
|
||||
|
||||
## `os.EOL`
|
||||
|
||||
@ -198,9 +198,9 @@ Strings passed in as an argument to `--eval` (or `-e`), or piped to `node` via
|
||||
is set.
|
||||
|
||||
```bash
|
||||
node --input-type=module --eval "import { sep } from 'path'; console.log(sep);"
|
||||
node --input-type=module --eval "import { sep } from 'node:path'; console.log(sep);"
|
||||
|
||||
echo "import { sep } from 'path'; console.log(sep);" | node --input-type=module
|
||||
echo "import { sep } from 'node:path'; console.log(sep);" | node --input-type=module
|
||||
```
|
||||
|
||||
For completeness there is also `--input-type=commonjs`, for explicitly running
|
||||
|
||||
@ -6,19 +6,19 @@
|
||||
|
||||
<!-- source_link=lib/path.js -->
|
||||
|
||||
The `path` module provides utilities for working with file and directory paths.
|
||||
It can be accessed using:
|
||||
The `node:path` module provides utilities for working with file and directory
|
||||
paths. It can be accessed using:
|
||||
|
||||
```js
|
||||
const path = require('path');
|
||||
const path = require('node:path');
|
||||
```
|
||||
|
||||
## Windows vs. POSIX
|
||||
|
||||
The default operation of the `path` module varies based on the operating system
|
||||
on which a Node.js application is running. Specifically, when running on a
|
||||
Windows operating system, the `path` module will assume that Windows-style
|
||||
paths are being used.
|
||||
The default operation of the `node:path` module varies based on the operating
|
||||
system on which a Node.js application is running. Specifically, when running on
|
||||
a Windows operating system, the `node:path` module will assume that
|
||||
Windows-style paths are being used.
|
||||
|
||||
So using `path.basename()` might yield different results on POSIX and Windows:
|
||||
|
||||
@ -447,7 +447,7 @@ added: v0.11.15
|
||||
changes:
|
||||
- version: v15.3.0
|
||||
pr-url: https://github.com/nodejs/node/pull/34962
|
||||
description: Exposed as `require('path/posix')`.
|
||||
description: Exposed as `require('node:path/posix')`.
|
||||
-->
|
||||
|
||||
* {Object}
|
||||
@ -455,7 +455,7 @@ changes:
|
||||
The `path.posix` property provides access to POSIX specific implementations
|
||||
of the `path` methods.
|
||||
|
||||
The API is accessible via `require('path').posix` or `require('path/posix')`.
|
||||
The API is accessible via `require('node:path').posix` or `require('node:path/posix')`.
|
||||
|
||||
## `path.relative(from, to)`
|
||||
|
||||
@ -592,7 +592,7 @@ added: v0.11.15
|
||||
changes:
|
||||
- version: v15.3.0
|
||||
pr-url: https://github.com/nodejs/node/pull/34962
|
||||
description: Exposed as `require('path/win32')`.
|
||||
description: Exposed as `require('node:path/win32')`.
|
||||
-->
|
||||
|
||||
* {Object}
|
||||
@ -600,7 +600,7 @@ changes:
|
||||
The `path.win32` property provides access to Windows-specific implementations
|
||||
of the `path` methods.
|
||||
|
||||
The API is accessible via `require('path').win32` or `require('path/win32')`.
|
||||
The API is accessible via `require('node:path').win32` or `require('node:path/win32')`.
|
||||
|
||||
[MSDN-Rel-Path]: https://docs.microsoft.com/en-us/windows/desktop/FileIO/naming-a-file#fully-qualified-vs-relative-paths
|
||||
[`TypeError`]: errors.md#class-typeerror
|
||||
|
||||
@ -17,7 +17,7 @@ Node.js supports the following [Web Performance APIs][]:
|
||||
* [User Timing][]
|
||||
|
||||
```js
|
||||
const { PerformanceObserver, performance } = require('perf_hooks');
|
||||
const { PerformanceObserver, performance } = require('node:perf_hooks');
|
||||
|
||||
const obs = new PerformanceObserver((items) => {
|
||||
console.log(items.getEntries()[0].duration);
|
||||
@ -111,8 +111,8 @@ of how a mostly idle process will have a high ELU.
|
||||
|
||||
```js
|
||||
'use strict';
|
||||
const { eventLoopUtilization } = require('perf_hooks').performance;
|
||||
const { spawnSync } = require('child_process');
|
||||
const { eventLoopUtilization } = require('node:perf_hooks').performance;
|
||||
const { spawnSync } = require('node:child_process');
|
||||
|
||||
setImmediate(() => {
|
||||
const elu = eventLoopUtilization();
|
||||
@ -312,7 +312,7 @@ event type in order for the timing details to be accessed.
|
||||
const {
|
||||
performance,
|
||||
PerformanceObserver
|
||||
} = require('perf_hooks');
|
||||
} = require('node:perf_hooks');
|
||||
|
||||
function someFunction() {
|
||||
console.log('hello world');
|
||||
@ -678,7 +678,7 @@ changes:
|
||||
const {
|
||||
performance,
|
||||
PerformanceObserver
|
||||
} = require('perf_hooks');
|
||||
} = require('node:perf_hooks');
|
||||
|
||||
const obs = new PerformanceObserver((list, observer) => {
|
||||
console.log(list.getEntries());
|
||||
@ -744,7 +744,7 @@ or `options.type`:
|
||||
const {
|
||||
performance,
|
||||
PerformanceObserver
|
||||
} = require('perf_hooks');
|
||||
} = require('node:perf_hooks');
|
||||
|
||||
const obs = new PerformanceObserver((list, observer) => {
|
||||
// Called once asynchronously. `list` contains three items.
|
||||
@ -780,7 +780,7 @@ with respect to `performanceEntry.startTime`.
|
||||
const {
|
||||
performance,
|
||||
PerformanceObserver
|
||||
} = require('perf_hooks');
|
||||
} = require('node:perf_hooks');
|
||||
|
||||
const obs = new PerformanceObserver((perfObserverList, observer) => {
|
||||
console.log(perfObserverList.getEntries());
|
||||
@ -830,7 +830,7 @@ equal to `name`, and optionally, whose `performanceEntry.entryType` is equal to
|
||||
const {
|
||||
performance,
|
||||
PerformanceObserver
|
||||
} = require('perf_hooks');
|
||||
} = require('node:perf_hooks');
|
||||
|
||||
const obs = new PerformanceObserver((perfObserverList, observer) => {
|
||||
console.log(perfObserverList.getEntriesByName('meow'));
|
||||
@ -886,7 +886,7 @@ is equal to `type`.
|
||||
const {
|
||||
performance,
|
||||
PerformanceObserver
|
||||
} = require('perf_hooks');
|
||||
} = require('node:perf_hooks');
|
||||
|
||||
const obs = new PerformanceObserver((perfObserverList, observer) => {
|
||||
console.log(perfObserverList.getEntriesByType('mark'));
|
||||
@ -959,7 +959,7 @@ of the timer, and those delays are specifically what this API is intended to
|
||||
detect.
|
||||
|
||||
```js
|
||||
const { monitorEventLoopDelay } = require('perf_hooks');
|
||||
const { monitorEventLoopDelay } = require('node:perf_hooks');
|
||||
const h = monitorEventLoopDelay({ resolution: 20 });
|
||||
h.enable();
|
||||
// Do something.
|
||||
@ -1228,11 +1228,11 @@ to execute the callback).
|
||||
|
||||
```js
|
||||
'use strict';
|
||||
const async_hooks = require('async_hooks');
|
||||
const async_hooks = require('node:async_hooks');
|
||||
const {
|
||||
performance,
|
||||
PerformanceObserver
|
||||
} = require('perf_hooks');
|
||||
} = require('node:perf_hooks');
|
||||
|
||||
const set = new Set();
|
||||
const hook = async_hooks.createHook({
|
||||
@ -1277,8 +1277,8 @@ dependencies:
|
||||
const {
|
||||
performance,
|
||||
PerformanceObserver
|
||||
} = require('perf_hooks');
|
||||
const mod = require('module');
|
||||
} = require('node:perf_hooks');
|
||||
const mod = require('node:module');
|
||||
|
||||
// Monkey patch the require function
|
||||
mod.Module.prototype.require =
|
||||
@ -1310,8 +1310,8 @@ the request and sending the response:
|
||||
|
||||
```js
|
||||
'use strict';
|
||||
const { PerformanceObserver } = require('perf_hooks');
|
||||
const http = require('http');
|
||||
const { PerformanceObserver } = require('node:perf_hooks');
|
||||
const http = require('node:http');
|
||||
|
||||
const obs = new PerformanceObserver((items) => {
|
||||
items.getEntries().forEach((item) => {
|
||||
@ -1334,8 +1334,8 @@ http.createServer((req, res) => {
|
||||
|
||||
```js
|
||||
'use strict';
|
||||
const { PerformanceObserver } = require('perf_hooks');
|
||||
const net = require('net');
|
||||
const { PerformanceObserver } = require('node:perf_hooks');
|
||||
const net = require('node:net');
|
||||
const obs = new PerformanceObserver((items) => {
|
||||
items.getEntries().forEach((item) => {
|
||||
console.log(item);
|
||||
@ -1354,8 +1354,8 @@ net.createServer((socket) => {
|
||||
|
||||
```js
|
||||
'use strict';
|
||||
const { PerformanceObserver } = require('perf_hooks');
|
||||
const dns = require('dns');
|
||||
const { PerformanceObserver } = require('node:perf_hooks');
|
||||
const dns = require('node:dns');
|
||||
const obs = new PerformanceObserver((items) => {
|
||||
items.getEntries().forEach((item) => {
|
||||
console.log(item);
|
||||
|
||||
@ -350,7 +350,7 @@ The following example, would allow access to `fs` for all `data:` resources:
|
||||
```json
|
||||
{
|
||||
"resources": {
|
||||
"data:text/javascript,import('fs');": {
|
||||
"data:text/javascript,import('node:fs');": {
|
||||
"cascade": true,
|
||||
"integrity": true
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@ -8,11 +8,11 @@
|
||||
|
||||
<!-- source_link=lib/querystring.js -->
|
||||
|
||||
The `querystring` module provides utilities for parsing and formatting URL
|
||||
The `node:querystring` module provides utilities for parsing and formatting URL
|
||||
query strings. It can be accessed using:
|
||||
|
||||
```js
|
||||
const querystring = require('querystring');
|
||||
const querystring = require('node:querystring');
|
||||
```
|
||||
|
||||
The `querystring` API is considered Legacy. While it is still maintained,
|
||||
|
||||
@ -6,8 +6,8 @@
|
||||
|
||||
<!-- source_link=lib/readline.js -->
|
||||
|
||||
The `readline` module provides an interface for reading data from a [Readable][]
|
||||
stream (such as [`process.stdin`][]) one line at a time.
|
||||
The `node:readline` module provides an interface for reading data from a
|
||||
[Readable][] stream (such as [`process.stdin`][]) one line at a time.
|
||||
|
||||
To use the promise-based APIs:
|
||||
|
||||
@ -16,7 +16,7 @@ import * as readline from 'node:readline/promises';
|
||||
```
|
||||
|
||||
```cjs
|
||||
const readline = require('readline/promises');
|
||||
const readline = require('node:readline/promises');
|
||||
```
|
||||
|
||||
To use the callback and sync APIs:
|
||||
@ -26,10 +26,11 @@ import * as readline from 'node:readline';
|
||||
```
|
||||
|
||||
```cjs
|
||||
const readline = require('readline');
|
||||
const readline = require('node:readline');
|
||||
```
|
||||
|
||||
The following simple example illustrates the basic use of the `readline` module.
|
||||
The following simple example illustrates the basic use of the `node:readline`
|
||||
module.
|
||||
|
||||
```mjs
|
||||
import * as readline from 'node:readline/promises';
|
||||
@ -45,8 +46,8 @@ rl.close();
|
||||
```
|
||||
|
||||
```cjs
|
||||
const readline = require('readline');
|
||||
const { stdin: input, stdout: output } = require('process');
|
||||
const readline = require('node:readline');
|
||||
const { stdin: input, stdout: output } = require('node:process');
|
||||
|
||||
const rl = readline.createInterface({ input, output });
|
||||
|
||||
@ -758,7 +759,7 @@ The `readlinePromises.createInterface()` method creates a new `readlinePromises.
|
||||
instance.
|
||||
|
||||
```js
|
||||
const readlinePromises = require('readline/promises');
|
||||
const readlinePromises = require('node:readline/promises');
|
||||
const rl = readlinePromises.createInterface({
|
||||
input: process.stdin,
|
||||
output: process.stdout
|
||||
@ -1015,7 +1016,7 @@ The `readline.createInterface()` method creates a new `readline.Interface`
|
||||
instance.
|
||||
|
||||
```js
|
||||
const readline = require('readline');
|
||||
const readline = require('node:readline');
|
||||
const rl = readline.createInterface({
|
||||
input: process.stdin,
|
||||
output: process.stdout
|
||||
@ -1153,7 +1154,7 @@ The following example illustrates the use of `readline.Interface` class to
|
||||
implement a small command-line interface:
|
||||
|
||||
```js
|
||||
const readline = require('readline');
|
||||
const readline = require('node:readline');
|
||||
const rl = readline.createInterface({
|
||||
input: process.stdin,
|
||||
output: process.stdout,
|
||||
@ -1185,8 +1186,8 @@ time. The easiest way to do so is leveraging the [`fs.ReadStream`][] API as
|
||||
well as a `for await...of` loop:
|
||||
|
||||
```js
|
||||
const fs = require('fs');
|
||||
const readline = require('readline');
|
||||
const fs = require('node:fs');
|
||||
const readline = require('node:readline');
|
||||
|
||||
async function processLineByLine() {
|
||||
const fileStream = fs.createReadStream('input.txt');
|
||||
@ -1210,8 +1211,8 @@ processLineByLine();
|
||||
Alternatively, one could use the [`'line'`][] event:
|
||||
|
||||
```js
|
||||
const fs = require('fs');
|
||||
const readline = require('readline');
|
||||
const fs = require('node:fs');
|
||||
const readline = require('node:readline');
|
||||
|
||||
const rl = readline.createInterface({
|
||||
input: fs.createReadStream('sample.txt'),
|
||||
@ -1227,9 +1228,9 @@ Currently, `for await...of` loop can be a bit slower. If `async` / `await`
|
||||
flow and speed are both essential, a mixed approach can be applied:
|
||||
|
||||
```js
|
||||
const { once } = require('events');
|
||||
const { createReadStream } = require('fs');
|
||||
const { createInterface } = require('readline');
|
||||
const { once } = require('node:events');
|
||||
const { createReadStream } = require('node:fs');
|
||||
const { createInterface } = require('node:readline');
|
||||
|
||||
(async function processLineByLine() {
|
||||
try {
|
||||
|
||||
@ -6,17 +6,17 @@
|
||||
|
||||
<!-- source_link=lib/repl.js -->
|
||||
|
||||
The `repl` module provides a Read-Eval-Print-Loop (REPL) implementation that
|
||||
is available both as a standalone program or includible in other applications.
|
||||
It can be accessed using:
|
||||
The `node:repl` module provides a Read-Eval-Print-Loop (REPL) implementation
|
||||
that is available both as a standalone program or includible in other
|
||||
applications. It can be accessed using:
|
||||
|
||||
```js
|
||||
const repl = require('repl');
|
||||
const repl = require('node:repl');
|
||||
```
|
||||
|
||||
## Design and features
|
||||
|
||||
The `repl` module exports the [`repl.REPLServer`][] class. While running,
|
||||
The `node:repl` module exports the [`repl.REPLServer`][] class. While running,
|
||||
instances of [`repl.REPLServer`][] will accept individual lines of user input,
|
||||
evaluate those according to a user-defined evaluation function, then output the
|
||||
result. Input and output may be from `stdin` and `stdout`, respectively, or may
|
||||
@ -107,7 +107,7 @@ scope. It is possible to expose a variable to the REPL explicitly by assigning
|
||||
it to the `context` object associated with each `REPLServer`:
|
||||
|
||||
```js
|
||||
const repl = require('repl');
|
||||
const repl = require('node:repl');
|
||||
const msg = 'message';
|
||||
|
||||
repl.start('> ').context.m = msg;
|
||||
@ -125,7 +125,7 @@ Context properties are not read-only by default. To specify read-only globals,
|
||||
context properties must be defined using `Object.defineProperty()`:
|
||||
|
||||
```js
|
||||
const repl = require('repl');
|
||||
const repl = require('node:repl');
|
||||
const msg = 'message';
|
||||
|
||||
const r = repl.start('> ');
|
||||
@ -141,7 +141,7 @@ Object.defineProperty(r.context, 'm', {
|
||||
The default evaluator will automatically load Node.js core modules into the
|
||||
REPL environment when used. For instance, unless otherwise declared as a
|
||||
global or scoped variable, the input `fs` will be evaluated on-demand as
|
||||
`global.fs = require('fs')`.
|
||||
`global.fs = require('node:fs')`.
|
||||
|
||||
```console
|
||||
> fs.createReadStream('./some/file');
|
||||
@ -284,7 +284,7 @@ The following illustrates a hypothetical example of a REPL that performs
|
||||
translation of text from one language to another:
|
||||
|
||||
```js
|
||||
const repl = require('repl');
|
||||
const repl = require('node:repl');
|
||||
const { Translator } = require('translator');
|
||||
|
||||
const myTranslator = new Translator('en', 'fr');
|
||||
@ -355,7 +355,7 @@ function for the `writer` option on construction. The following example, for
|
||||
instance, simply converts any input text to upper case:
|
||||
|
||||
```js
|
||||
const repl = require('repl');
|
||||
const repl = require('node:repl');
|
||||
|
||||
const r = repl.start({ prompt: '> ', eval: myEval, writer: myWriter });
|
||||
|
||||
@ -381,7 +381,7 @@ Instances of `repl.REPLServer` are created using the [`repl.start()`][] method
|
||||
or directly using the JavaScript `new` keyword.
|
||||
|
||||
```js
|
||||
const repl = require('repl');
|
||||
const repl = require('node:repl');
|
||||
|
||||
const options = { useColors: true };
|
||||
|
||||
@ -425,7 +425,7 @@ This can be used primarily to re-initialize REPL context to some pre-defined
|
||||
state:
|
||||
|
||||
```js
|
||||
const repl = require('repl');
|
||||
const repl = require('node:repl');
|
||||
|
||||
function initializeContext(context) {
|
||||
context.m = 'test';
|
||||
@ -476,7 +476,7 @@ properties:
|
||||
The following example shows two new commands added to the REPL instance:
|
||||
|
||||
```js
|
||||
const repl = require('repl');
|
||||
const repl = require('node:repl');
|
||||
|
||||
const replServer = repl.start({ prompt: '> ' });
|
||||
replServer.defineCommand('sayhello', {
|
||||
@ -654,7 +654,7 @@ The `repl.start()` method creates and starts a [`repl.REPLServer`][] instance.
|
||||
If `options` is a string, then it specifies the input prompt:
|
||||
|
||||
```js
|
||||
const repl = require('repl');
|
||||
const repl = require('node:repl');
|
||||
|
||||
// a Unix style prompt
|
||||
repl.start('$ ');
|
||||
@ -662,9 +662,9 @@ repl.start('$ ');
|
||||
|
||||
## The Node.js REPL
|
||||
|
||||
Node.js itself uses the `repl` module to provide its own interactive interface
|
||||
for executing JavaScript. This can be used by executing the Node.js binary
|
||||
without passing any arguments (or by passing the `-i` argument):
|
||||
Node.js itself uses the `node:repl` module to provide its own interactive
|
||||
interface for executing JavaScript. This can be used by executing the Node.js
|
||||
binary without passing any arguments (or by passing the `-i` argument):
|
||||
|
||||
```console
|
||||
$ node
|
||||
@ -726,8 +726,8 @@ The following example, for instance, provides separate REPLs on `stdin`, a Unix
|
||||
socket, and a TCP socket:
|
||||
|
||||
```js
|
||||
const net = require('net');
|
||||
const repl = require('repl');
|
||||
const net = require('node:net');
|
||||
const repl = require('node:repl');
|
||||
let connections = 0;
|
||||
|
||||
repl.start({
|
||||
|
||||
@ -7,7 +7,7 @@
|
||||
<!-- source_link=lib/stream.js -->
|
||||
|
||||
A stream is an abstract interface for working with streaming data in Node.js.
|
||||
The `stream` module provides an API for implementing the stream interface.
|
||||
The `node:stream` module provides an API for implementing the stream interface.
|
||||
|
||||
There are many stream objects provided by Node.js. For instance, a
|
||||
[request to an HTTP server][http-incoming-message] and [`process.stdout`][]
|
||||
@ -16,14 +16,14 @@ are both stream instances.
|
||||
Streams can be readable, writable, or both. All streams are instances of
|
||||
[`EventEmitter`][].
|
||||
|
||||
To access the `stream` module:
|
||||
To access the `node:stream` module:
|
||||
|
||||
```js
|
||||
const stream = require('stream');
|
||||
const stream = require('node:stream');
|
||||
```
|
||||
|
||||
The `stream` module is useful for creating new types of stream instances. It is
|
||||
usually not necessary to use the `stream` module to consume streams.
|
||||
The `node:stream` module is useful for creating new types of stream instances.
|
||||
It is usually not necessary to use the `node:stream` module to consume streams.
|
||||
|
||||
## Organization of this document
|
||||
|
||||
@ -56,8 +56,8 @@ added: v15.0.0
|
||||
|
||||
The `stream/promises` API provides an alternative set of asynchronous utility
|
||||
functions for streams that return `Promise` objects rather than using
|
||||
callbacks. The API is accessible via `require('stream/promises')`
|
||||
or `require('stream').promises`.
|
||||
callbacks. The API is accessible via `require('node:stream/promises')`
|
||||
or `require('node:stream').promises`.
|
||||
|
||||
### Object mode
|
||||
|
||||
@ -134,7 +134,7 @@ manner. The following is an example of using streams in a Node.js application
|
||||
that implements an HTTP server:
|
||||
|
||||
```js
|
||||
const http = require('http');
|
||||
const http = require('node:http');
|
||||
|
||||
const server = http.createServer((req, res) => {
|
||||
// `req` is an http.IncomingMessage, which is a readable stream.
|
||||
@ -190,7 +190,7 @@ various ways to communicate the current state of the stream.
|
||||
|
||||
Applications that are either writing data to or consuming data from a stream
|
||||
are not required to implement the stream interfaces directly and will generally
|
||||
have no reason to call `require('stream')`.
|
||||
have no reason to call `require('node:stream')`.
|
||||
|
||||
Developers wishing to implement new types of streams should refer to the
|
||||
section [API for stream implementers][].
|
||||
@ -422,7 +422,7 @@ Use `end()` instead of destroy if data should flush before close, or wait for
|
||||
the `'drain'` event before destroying the stream.
|
||||
|
||||
```cjs
|
||||
const { Writable } = require('stream');
|
||||
const { Writable } = require('node:stream');
|
||||
|
||||
const myStream = new Writable();
|
||||
|
||||
@ -432,7 +432,7 @@ myStream.on('error', (fooErr) => console.error(fooErr.message)); // foo error
|
||||
```
|
||||
|
||||
```cjs
|
||||
const { Writable } = require('stream');
|
||||
const { Writable } = require('node:stream');
|
||||
|
||||
const myStream = new Writable();
|
||||
|
||||
@ -441,7 +441,7 @@ myStream.on('error', function wontHappen() {});
|
||||
```
|
||||
|
||||
```cjs
|
||||
const { Writable } = require('stream');
|
||||
const { Writable } = require('node:stream');
|
||||
|
||||
const myStream = new Writable();
|
||||
myStream.destroy();
|
||||
@ -477,7 +477,7 @@ added: v8.0.0
|
||||
Is `true` after [`writable.destroy()`][writable-destroy] has been called.
|
||||
|
||||
```cjs
|
||||
const { Writable } = require('stream');
|
||||
const { Writable } = require('node:stream');
|
||||
|
||||
const myStream = new Writable();
|
||||
|
||||
@ -523,7 +523,7 @@ Calling the [`stream.write()`][stream-write] method after calling
|
||||
|
||||
```js
|
||||
// Write 'hello, ' and then end with 'world!'.
|
||||
const fs = require('fs');
|
||||
const fs = require('node:fs');
|
||||
const file = fs.createWriteStream('example.txt');
|
||||
file.write('hello, ');
|
||||
file.end('world!');
|
||||
@ -871,7 +871,7 @@ data. While in this state, attaching a listener for the `'data'` event
|
||||
will not switch `readable.readableFlowing` to `true`.
|
||||
|
||||
```js
|
||||
const { PassThrough, Writable } = require('stream');
|
||||
const { PassThrough, Writable } = require('node:stream');
|
||||
const pass = new PassThrough();
|
||||
const writable = new Writable();
|
||||
|
||||
@ -1041,7 +1041,7 @@ event. This is also true if there never was any data to be read. For instance,
|
||||
in the following example, `foo.txt` is an empty file:
|
||||
|
||||
```js
|
||||
const fs = require('fs');
|
||||
const fs = require('node:fs');
|
||||
const rr = fs.createReadStream('foo.txt');
|
||||
rr.on('readable', () => {
|
||||
console.log(`readable: ${rr.read()}`);
|
||||
@ -1200,7 +1200,7 @@ The following example pipes all of the data from the `readable` into a file
|
||||
named `file.txt`:
|
||||
|
||||
```js
|
||||
const fs = require('fs');
|
||||
const fs = require('node:fs');
|
||||
const readable = getReadableStreamSomehow();
|
||||
const writable = fs.createWriteStream('file.txt');
|
||||
// All the data from readable goes into 'file.txt'.
|
||||
@ -1214,7 +1214,7 @@ The `readable.pipe()` method returns a reference to the _destination_ stream
|
||||
making it possible to set up chains of piped streams:
|
||||
|
||||
```js
|
||||
const fs = require('fs');
|
||||
const fs = require('node:fs');
|
||||
const r = fs.createReadStream('file.txt');
|
||||
const z = zlib.createGzip();
|
||||
const w = fs.createWriteStream('file.txt.gz');
|
||||
@ -1518,7 +1518,7 @@ If the `destination` is specified, but no pipe is set up for it, then
|
||||
the method does nothing.
|
||||
|
||||
```js
|
||||
const fs = require('fs');
|
||||
const fs = require('node:fs');
|
||||
const readable = getReadableStreamSomehow();
|
||||
const writable = fs.createWriteStream('file.txt');
|
||||
// All the data from readable goes into 'file.txt',
|
||||
@ -1570,7 +1570,7 @@ section for more information.
|
||||
// Pull off a header delimited by \n\n.
|
||||
// Use unshift() if we get too much.
|
||||
// Call the callback with (error, header, stream).
|
||||
const { StringDecoder } = require('string_decoder');
|
||||
const { StringDecoder } = require('node:string_decoder');
|
||||
function parseHeader(stream, callback) {
|
||||
stream.on('error', callback);
|
||||
stream.on('readable', onReadable);
|
||||
@ -1620,8 +1620,9 @@ added: v0.9.4
|
||||
* `stream` {Stream} An "old style" readable stream
|
||||
* Returns: {this}
|
||||
|
||||
Prior to Node.js 0.10, streams did not implement the entire `stream` module API
|
||||
as it is currently defined. (See [Compatibility][] for more information.)
|
||||
Prior to Node.js 0.10, streams did not implement the entire `node:stream`
|
||||
module API as it is currently defined. (See [Compatibility][] for more
|
||||
information.)
|
||||
|
||||
When using an older Node.js library that emits [`'data'`][] events and has a
|
||||
[`stream.pause()`][stream-pause] method that is advisory only, the
|
||||
@ -1634,7 +1635,7 @@ libraries.
|
||||
|
||||
```js
|
||||
const { OldReader } = require('./old-api-module.js');
|
||||
const { Readable } = require('stream');
|
||||
const { Readable } = require('node:stream');
|
||||
const oreader = new OldReader();
|
||||
const myReader = new Readable().wrap(oreader);
|
||||
|
||||
@ -1656,7 +1657,7 @@ changes:
|
||||
* Returns: {AsyncIterator} to fully consume the stream.
|
||||
|
||||
```js
|
||||
const fs = require('fs');
|
||||
const fs = require('node:fs');
|
||||
|
||||
async function print(readable) {
|
||||
readable.setEncoding('utf8');
|
||||
@ -1697,7 +1698,7 @@ destruction of the stream if the `for await...of` loop is exited by `return`,
|
||||
emitted an error during iteration.
|
||||
|
||||
```js
|
||||
const { Readable } = require('stream');
|
||||
const { Readable } = require('node:stream');
|
||||
|
||||
async function printIterator(readable) {
|
||||
for await (const chunk of readable.iterator({ destroyOnReturn: false })) {
|
||||
@ -1759,8 +1760,8 @@ for every chunk in the stream. If the `fn` function returns a promise - that
|
||||
promise will be `await`ed before being passed to the result stream.
|
||||
|
||||
```mjs
|
||||
import { Readable } from 'stream';
|
||||
import { Resolver } from 'dns/promises';
|
||||
import { Readable } from 'node:stream';
|
||||
import { Resolver } from 'node:dns/promises';
|
||||
|
||||
// With a synchronous mapper.
|
||||
for await (const chunk of Readable.from([1, 2, 3, 4]).map((x) => x * 2)) {
|
||||
@ -1806,8 +1807,8 @@ passed to the result stream. If the `fn` function returns a promise - that
|
||||
promise will be `await`ed.
|
||||
|
||||
```mjs
|
||||
import { Readable } from 'stream';
|
||||
import { Resolver } from 'dns/promises';
|
||||
import { Readable } from 'node:stream';
|
||||
import { Resolver } from 'node:dns/promises';
|
||||
|
||||
// With a synchronous predicate.
|
||||
for await (const chunk of Readable.from([1, 2, 3, 4]).filter((x) => x > 2)) {
|
||||
@ -1864,8 +1865,8 @@ uses the [`readable`][] event in the underlying machinary and can limit the
|
||||
number of concurrent `fn` calls.
|
||||
|
||||
```mjs
|
||||
import { Readable } from 'stream';
|
||||
import { Resolver } from 'dns/promises';
|
||||
import { Readable } from 'node:stream';
|
||||
import { Resolver } from 'node:dns/promises';
|
||||
|
||||
// With a synchronous predicate.
|
||||
for await (const chunk of Readable.from([1, 2, 3, 4]).filter((x) => x > 2)) {
|
||||
@ -1909,8 +1910,8 @@ streams. It's intended for interoperability and convenience, not as the primary
|
||||
way to consume streams.
|
||||
|
||||
```mjs
|
||||
import { Readable } from 'stream';
|
||||
import { Resolver } from 'dns/promises';
|
||||
import { Readable } from 'node:stream';
|
||||
import { Resolver } from 'node:dns/promises';
|
||||
|
||||
await Readable.from([1, 2, 3, 4]).toArray(); // [1, 2, 3, 4]
|
||||
|
||||
@ -1955,8 +1956,8 @@ calls on the chunks return a truthy value, the promise is fulfilled with
|
||||
`false`.
|
||||
|
||||
```mjs
|
||||
import { Readable } from 'stream';
|
||||
import { stat } from 'fs/promises';
|
||||
import { Readable } from 'node:stream';
|
||||
import { stat } from 'node:fs/promises';
|
||||
|
||||
// With a synchronous predicate.
|
||||
await Readable.from([1, 2, 3, 4]).some((x) => x > 2); // true
|
||||
@ -2004,8 +2005,8 @@ fulfilled with value for which `fn` returned a truthy value. If all of the
|
||||
`undefined`.
|
||||
|
||||
```mjs
|
||||
import { Readable } from 'stream';
|
||||
import { stat } from 'fs/promises';
|
||||
import { Readable } from 'node:stream';
|
||||
import { stat } from 'node:fs/promises';
|
||||
|
||||
// With a synchronous predicate.
|
||||
await Readable.from([1, 2, 3, 4]).find((x) => x > 2); // 3
|
||||
@ -2053,8 +2054,8 @@ destroyed and the promise is fulfilled with `false`. If all of the `fn` calls
|
||||
on the chunks return a truthy value, the promise is fulfilled with `true`.
|
||||
|
||||
```mjs
|
||||
import { Readable } from 'stream';
|
||||
import { stat } from 'fs/promises';
|
||||
import { Readable } from 'node:stream';
|
||||
import { stat } from 'node:fs/promises';
|
||||
|
||||
// With a synchronous predicate.
|
||||
await Readable.from([1, 2, 3, 4]).every((x) => x > 2); // false
|
||||
@ -2103,8 +2104,8 @@ It is possible to return a stream or another iterable or async iterable from
|
||||
stream.
|
||||
|
||||
```mjs
|
||||
import { Readable } from 'stream';
|
||||
import { createReadStream } from 'fs';
|
||||
import { Readable } from 'node:stream';
|
||||
import { createReadStream } from 'node:fs';
|
||||
|
||||
// With a synchronous mapper.
|
||||
for await (const chunk of Readable.from([1, 2, 3, 4]).flatMap((x) => [x, x])) {
|
||||
@ -2140,7 +2141,7 @@ added: v17.5.0
|
||||
This method returns a new stream with the first `limit` chunks dropped.
|
||||
|
||||
```mjs
|
||||
import { Readable } from 'stream';
|
||||
import { Readable } from 'node:stream';
|
||||
|
||||
await Readable.from([1, 2, 3, 4]).drop(2).toArray(); // [3, 4]
|
||||
```
|
||||
@ -2162,7 +2163,7 @@ added: v17.5.0
|
||||
This method returns a new stream with the first `limit` chunks.
|
||||
|
||||
```mjs
|
||||
import { Readable } from 'stream';
|
||||
import { Readable } from 'node:stream';
|
||||
|
||||
await Readable.from([1, 2, 3, 4]).take(2).toArray(); // [1, 2]
|
||||
```
|
||||
@ -2185,7 +2186,7 @@ with a counter in the form `[index, chunk]`. The first index value is 0 and it
|
||||
increases by 1 for each chunk produced.
|
||||
|
||||
```mjs
|
||||
import { Readable } from 'stream';
|
||||
import { Readable } from 'node:stream';
|
||||
|
||||
const pairs = await Readable.from(['a', 'b', 'c']).asIndexedPairs().toArray();
|
||||
console.log(pairs); // [[0, 'a'], [1, 'b'], [2, 'c']]
|
||||
@ -2226,7 +2227,7 @@ initial value. If the stream is empty, the promise is rejected with a
|
||||
`TypeError` with the `ERR_INVALID_ARGS` code property.
|
||||
|
||||
```mjs
|
||||
import { Readable } from 'stream';
|
||||
import { Readable } from 'node:stream';
|
||||
|
||||
const ten = await Readable.from([1, 2, 3, 4]).reduce((previous, data) => {
|
||||
return previous + data;
|
||||
@ -2361,7 +2362,7 @@ A function to get notified when a stream is no longer readable, writable
|
||||
or has experienced an error or a premature close event.
|
||||
|
||||
```js
|
||||
const { finished } = require('stream');
|
||||
const { finished } = require('node:stream');
|
||||
|
||||
const rs = fs.createReadStream('archive.tar');
|
||||
|
||||
@ -2383,7 +2384,7 @@ or `'finish'`.
|
||||
The `finished` API provides promise version:
|
||||
|
||||
```js
|
||||
const { finished } = require('stream/promises');
|
||||
const { finished } = require('node:stream/promises');
|
||||
|
||||
const rs = fs.createReadStream('archive.tar');
|
||||
|
||||
@ -2451,9 +2452,9 @@ A module method to pipe between streams and generators forwarding errors and
|
||||
properly cleaning up and provide a callback when the pipeline is complete.
|
||||
|
||||
```js
|
||||
const { pipeline } = require('stream');
|
||||
const fs = require('fs');
|
||||
const zlib = require('zlib');
|
||||
const { pipeline } = require('node:stream');
|
||||
const fs = require('node:fs');
|
||||
const zlib = require('node:zlib');
|
||||
|
||||
// Use the pipeline API to easily pipe a series of streams
|
||||
// together and get notified when the pipeline is fully done.
|
||||
@ -2481,7 +2482,7 @@ receive an options argument as the last parameter with a
|
||||
`AbortError`.
|
||||
|
||||
```js
|
||||
const { pipeline } = require('stream/promises');
|
||||
const { pipeline } = require('node:stream/promises');
|
||||
|
||||
async function run() {
|
||||
await pipeline(
|
||||
@ -2499,7 +2500,7 @@ To use an `AbortSignal`, pass it inside an options object,
|
||||
as the last argument:
|
||||
|
||||
```js
|
||||
const { pipeline } = require('stream/promises');
|
||||
const { pipeline } = require('node:stream/promises');
|
||||
|
||||
async function run() {
|
||||
const ac = new AbortController();
|
||||
@ -2520,8 +2521,8 @@ run().catch(console.error); // AbortError
|
||||
The `pipeline` API also supports async generators:
|
||||
|
||||
```js
|
||||
const { pipeline } = require('stream/promises');
|
||||
const fs = require('fs');
|
||||
const { pipeline } = require('node:stream/promises');
|
||||
const fs = require('node:fs');
|
||||
|
||||
async function run() {
|
||||
await pipeline(
|
||||
@ -2545,8 +2546,8 @@ Especially in the case where the async generator is the source for the
|
||||
pipeline (i.e. first argument) or the pipeline will never complete.
|
||||
|
||||
```js
|
||||
const { pipeline } = require('stream/promises');
|
||||
const fs = require('fs');
|
||||
const { pipeline } = require('node:stream/promises');
|
||||
const fs = require('node:fs');
|
||||
|
||||
async function run() {
|
||||
await pipeline(
|
||||
@ -2579,9 +2580,9 @@ once it would destroy the socket without sending the expected response.
|
||||
See the example below:
|
||||
|
||||
```js
|
||||
const fs = require('fs');
|
||||
const http = require('http');
|
||||
const { pipeline } = require('stream');
|
||||
const fs = require('node:fs');
|
||||
const http = require('node:http');
|
||||
const { pipeline } = require('node:stream');
|
||||
|
||||
const server = http.createServer((req, res) => {
|
||||
const fileStream = fs.createReadStream('./fileNotExist.txt');
|
||||
@ -2621,7 +2622,7 @@ If passed a `Function` it must be a factory method taking a `source`
|
||||
`Iterable`.
|
||||
|
||||
```mjs
|
||||
import { compose, Transform } from 'stream';
|
||||
import { compose, Transform } from 'node:stream';
|
||||
|
||||
const removeSpaces = new Transform({
|
||||
transform(chunk, encoding, callback) {
|
||||
@ -2655,8 +2656,8 @@ functions into streams.
|
||||
either `null` or `undefined`.
|
||||
|
||||
```mjs
|
||||
import { compose } from 'stream';
|
||||
import { finished } from 'stream/promises';
|
||||
import { compose } from 'node:stream';
|
||||
import { finished } from 'node:stream/promises';
|
||||
|
||||
// Convert AsyncIterable into readable Duplex.
|
||||
const s1 = compose(async function*() {
|
||||
@ -2704,7 +2705,7 @@ added:
|
||||
A utility method for creating readable streams out of iterators.
|
||||
|
||||
```js
|
||||
const { Readable } = require('stream');
|
||||
const { Readable } = require('node:stream');
|
||||
|
||||
async function * generate() {
|
||||
yield 'hello';
|
||||
@ -2898,7 +2899,7 @@ Calling `abort` on the `AbortController` corresponding to the passed
|
||||
on the stream.
|
||||
|
||||
```js
|
||||
const fs = require('fs');
|
||||
const fs = require('node:fs');
|
||||
|
||||
const controller = new AbortController();
|
||||
const read = addAbortSignal(
|
||||
@ -2937,7 +2938,7 @@ const stream = addAbortSignal(
|
||||
|
||||
<!--type=misc-->
|
||||
|
||||
The `stream` module API has been designed to make it possible to easily
|
||||
The `node:stream` module API has been designed to make it possible to easily
|
||||
implement streams using JavaScript's prototypal inheritance model.
|
||||
|
||||
First, a stream developer would declare a new JavaScript class that extends one
|
||||
@ -2948,7 +2949,7 @@ parent class constructor:
|
||||
<!-- eslint-disable no-useless-constructor -->
|
||||
|
||||
```js
|
||||
const { Writable } = require('stream');
|
||||
const { Writable } = require('node:stream');
|
||||
|
||||
class MyWritable extends Writable {
|
||||
constructor({ highWaterMark, ...options }) {
|
||||
@ -2999,7 +3000,7 @@ inheritance. This can be accomplished by directly creating instances of the
|
||||
objects and passing appropriate methods as constructor options.
|
||||
|
||||
```js
|
||||
const { Writable } = require('stream');
|
||||
const { Writable } = require('node:stream');
|
||||
|
||||
const myWritable = new Writable({
|
||||
construct(callback) {
|
||||
@ -3081,7 +3082,7 @@ changes:
|
||||
<!-- eslint-disable no-useless-constructor -->
|
||||
|
||||
```js
|
||||
const { Writable } = require('stream');
|
||||
const { Writable } = require('node:stream');
|
||||
|
||||
class MyWritable extends Writable {
|
||||
constructor(options) {
|
||||
@ -3095,8 +3096,8 @@ class MyWritable extends Writable {
|
||||
Or, when using pre-ES6 style constructors:
|
||||
|
||||
```js
|
||||
const { Writable } = require('stream');
|
||||
const util = require('util');
|
||||
const { Writable } = require('node:stream');
|
||||
const util = require('node:util');
|
||||
|
||||
function MyWritable(options) {
|
||||
if (!(this instanceof MyWritable))
|
||||
@ -3109,7 +3110,7 @@ util.inherits(MyWritable, Writable);
|
||||
Or, using the simplified constructor approach:
|
||||
|
||||
```js
|
||||
const { Writable } = require('stream');
|
||||
const { Writable } = require('node:stream');
|
||||
|
||||
const myWritable = new Writable({
|
||||
write(chunk, encoding, callback) {
|
||||
@ -3126,7 +3127,7 @@ Calling `abort` on the `AbortController` corresponding to the passed
|
||||
on the writeable stream.
|
||||
|
||||
```js
|
||||
const { Writable } = require('stream');
|
||||
const { Writable } = require('node:stream');
|
||||
|
||||
const controller = new AbortController();
|
||||
const myWritable = new Writable({
|
||||
@ -3161,8 +3162,8 @@ has returned, delaying any `_write()`, `_final()` and `_destroy()` calls until
|
||||
initialize resources before the stream can be used.
|
||||
|
||||
```js
|
||||
const { Writable } = require('stream');
|
||||
const fs = require('fs');
|
||||
const { Writable } = require('node:stream');
|
||||
const fs = require('node:fs');
|
||||
|
||||
class WriteStream extends Writable {
|
||||
constructor(filename) {
|
||||
@ -3318,7 +3319,7 @@ If a `Readable` stream pipes into a `Writable` stream when `Writable` emits an
|
||||
error, the `Readable` stream will be unpiped.
|
||||
|
||||
```js
|
||||
const { Writable } = require('stream');
|
||||
const { Writable } = require('node:stream');
|
||||
|
||||
const myWritable = new Writable({
|
||||
write(chunk, encoding, callback) {
|
||||
@ -3339,7 +3340,7 @@ is not of any real particular usefulness, the example illustrates each of the
|
||||
required elements of a custom [`Writable`][] stream instance:
|
||||
|
||||
```js
|
||||
const { Writable } = require('stream');
|
||||
const { Writable } = require('node:stream');
|
||||
|
||||
class MyWritable extends Writable {
|
||||
_write(chunk, encoding, callback) {
|
||||
@ -3360,8 +3361,8 @@ characters encoding, such as UTF-8. The following example shows how to decode
|
||||
multi-byte strings using `StringDecoder` and [`Writable`][].
|
||||
|
||||
```js
|
||||
const { Writable } = require('stream');
|
||||
const { StringDecoder } = require('string_decoder');
|
||||
const { Writable } = require('node:stream');
|
||||
const { StringDecoder } = require('node:string_decoder');
|
||||
|
||||
class StringWritable extends Writable {
|
||||
constructor(options) {
|
||||
@ -3441,7 +3442,7 @@ changes:
|
||||
<!-- eslint-disable no-useless-constructor -->
|
||||
|
||||
```js
|
||||
const { Readable } = require('stream');
|
||||
const { Readable } = require('node:stream');
|
||||
|
||||
class MyReadable extends Readable {
|
||||
constructor(options) {
|
||||
@ -3455,8 +3456,8 @@ class MyReadable extends Readable {
|
||||
Or, when using pre-ES6 style constructors:
|
||||
|
||||
```js
|
||||
const { Readable } = require('stream');
|
||||
const util = require('util');
|
||||
const { Readable } = require('node:stream');
|
||||
const util = require('node:util');
|
||||
|
||||
function MyReadable(options) {
|
||||
if (!(this instanceof MyReadable))
|
||||
@ -3469,7 +3470,7 @@ util.inherits(MyReadable, Readable);
|
||||
Or, using the simplified constructor approach:
|
||||
|
||||
```js
|
||||
const { Readable } = require('stream');
|
||||
const { Readable } = require('node:stream');
|
||||
|
||||
const myReadable = new Readable({
|
||||
read(size) {
|
||||
@ -3483,7 +3484,7 @@ Calling `abort` on the `AbortController` corresponding to the passed
|
||||
on the readable created.
|
||||
|
||||
```js
|
||||
const { Readable } = require('stream');
|
||||
const { Readable } = require('node:stream');
|
||||
const controller = new AbortController();
|
||||
const read = new Readable({
|
||||
read(size) {
|
||||
@ -3514,8 +3515,8 @@ called. This is useful to initialize state or asynchronously initialize
|
||||
resources before the stream can be used.
|
||||
|
||||
```js
|
||||
const { Readable } = require('stream');
|
||||
const fs = require('fs');
|
||||
const { Readable } = require('node:stream');
|
||||
const fs = require('node:fs');
|
||||
|
||||
class ReadStream extends Readable {
|
||||
constructor(filename) {
|
||||
@ -3687,7 +3688,7 @@ Throwing an `Error` from within [`readable._read()`][] or manually emitting an
|
||||
`'error'` event results in undefined behavior.
|
||||
|
||||
```js
|
||||
const { Readable } = require('stream');
|
||||
const { Readable } = require('node:stream');
|
||||
|
||||
const myReadable = new Readable({
|
||||
read(size) {
|
||||
@ -3709,7 +3710,7 @@ 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.
|
||||
|
||||
```js
|
||||
const { Readable } = require('stream');
|
||||
const { Readable } = require('node:stream');
|
||||
|
||||
class Counter extends Readable {
|
||||
constructor(opt) {
|
||||
@ -3780,7 +3781,7 @@ changes:
|
||||
<!-- eslint-disable no-useless-constructor -->
|
||||
|
||||
```js
|
||||
const { Duplex } = require('stream');
|
||||
const { Duplex } = require('node:stream');
|
||||
|
||||
class MyDuplex extends Duplex {
|
||||
constructor(options) {
|
||||
@ -3793,8 +3794,8 @@ class MyDuplex extends Duplex {
|
||||
Or, when using pre-ES6 style constructors:
|
||||
|
||||
```js
|
||||
const { Duplex } = require('stream');
|
||||
const util = require('util');
|
||||
const { Duplex } = require('node:stream');
|
||||
const util = require('node:util');
|
||||
|
||||
function MyDuplex(options) {
|
||||
if (!(this instanceof MyDuplex))
|
||||
@ -3807,7 +3808,7 @@ util.inherits(MyDuplex, Duplex);
|
||||
Or, using the simplified constructor approach:
|
||||
|
||||
```js
|
||||
const { Duplex } = require('stream');
|
||||
const { Duplex } = require('node:stream');
|
||||
|
||||
const myDuplex = new Duplex({
|
||||
read(size) {
|
||||
@ -3822,8 +3823,8 @@ const myDuplex = new Duplex({
|
||||
When using pipeline:
|
||||
|
||||
```js
|
||||
const { Transform, pipeline } = require('stream');
|
||||
const fs = require('fs');
|
||||
const { Transform, pipeline } = require('node:stream');
|
||||
const fs = require('node:fs');
|
||||
|
||||
pipeline(
|
||||
fs.createReadStream('object.json')
|
||||
@ -3871,7 +3872,7 @@ incoming written data via the [`Writable`][] interface that is read back out
|
||||
via the [`Readable`][] interface.
|
||||
|
||||
```js
|
||||
const { Duplex } = require('stream');
|
||||
const { Duplex } = require('node:stream');
|
||||
const kSource = Symbol('source');
|
||||
|
||||
class MyDuplex extends Duplex {
|
||||
@ -3912,7 +3913,7 @@ that accepts JavaScript numbers that are converted to hexadecimal strings on
|
||||
the `Readable` side.
|
||||
|
||||
```js
|
||||
const { Transform } = require('stream');
|
||||
const { Transform } = require('node:stream');
|
||||
|
||||
// All Transform streams are also Duplex Streams.
|
||||
const myTransform = new Transform({
|
||||
@ -3977,7 +3978,7 @@ output on the `Readable` side is not consumed.
|
||||
<!-- eslint-disable no-useless-constructor -->
|
||||
|
||||
```js
|
||||
const { Transform } = require('stream');
|
||||
const { Transform } = require('node:stream');
|
||||
|
||||
class MyTransform extends Transform {
|
||||
constructor(options) {
|
||||
@ -3990,8 +3991,8 @@ class MyTransform extends Transform {
|
||||
Or, when using pre-ES6 style constructors:
|
||||
|
||||
```js
|
||||
const { Transform } = require('stream');
|
||||
const util = require('util');
|
||||
const { Transform } = require('node:stream');
|
||||
const util = require('node:util');
|
||||
|
||||
function MyTransform(options) {
|
||||
if (!(this instanceof MyTransform))
|
||||
@ -4004,7 +4005,7 @@ util.inherits(MyTransform, Transform);
|
||||
Or, using the simplified constructor approach:
|
||||
|
||||
```js
|
||||
const { Transform } = require('stream');
|
||||
const { Transform } = require('node:stream');
|
||||
|
||||
const myTransform = new Transform({
|
||||
transform(chunk, encoding, callback) {
|
||||
@ -4148,7 +4149,7 @@ A Node.js readable stream can be created from an asynchronous generator using
|
||||
the `Readable.from()` utility method:
|
||||
|
||||
```js
|
||||
const { Readable } = require('stream');
|
||||
const { Readable } = require('node:stream');
|
||||
|
||||
const ac = new AbortController();
|
||||
const signal = ac.signal;
|
||||
@ -4177,9 +4178,9 @@ handling of backpressure and errors. [`stream.pipeline()`][] abstracts away
|
||||
the handling of backpressure and backpressure-related errors:
|
||||
|
||||
```js
|
||||
const fs = require('fs');
|
||||
const { pipeline } = require('stream');
|
||||
const { pipeline: pipelinePromise } = require('stream/promises');
|
||||
const fs = require('node:fs');
|
||||
const { pipeline } = require('node:stream');
|
||||
const { pipeline: pipelinePromise } = require('node:stream/promises');
|
||||
|
||||
const writable = fs.createWriteStream('./file');
|
||||
|
||||
|
||||
@ -6,18 +6,18 @@
|
||||
|
||||
<!-- source_link=lib/string_decoder.js -->
|
||||
|
||||
The `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
|
||||
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
|
||||
characters. It can be accessed using:
|
||||
|
||||
```js
|
||||
const { StringDecoder } = require('string_decoder');
|
||||
const { StringDecoder } = require('node:string_decoder');
|
||||
```
|
||||
|
||||
The following example shows the basic use of the `StringDecoder` class.
|
||||
|
||||
```js
|
||||
const { StringDecoder } = require('string_decoder');
|
||||
const { StringDecoder } = require('node:string_decoder');
|
||||
const decoder = new StringDecoder('utf8');
|
||||
|
||||
const cent = Buffer.from([0xC2, 0xA2]);
|
||||
@ -36,7 +36,7 @@ In the following example, the three UTF-8 encoded bytes of the European Euro
|
||||
symbol (`€`) are written over three separate operations:
|
||||
|
||||
```js
|
||||
const { StringDecoder } = require('string_decoder');
|
||||
const { StringDecoder } = require('node:string_decoder');
|
||||
const decoder = new StringDecoder('utf8');
|
||||
|
||||
decoder.write(Buffer.from([0xE2]));
|
||||
|
||||
@ -55,7 +55,7 @@ Open `hello-world.js` in any preferred text editor and
|
||||
paste in the following content:
|
||||
|
||||
```js
|
||||
const http = require('http');
|
||||
const http = require('node:http');
|
||||
|
||||
const hostname = '127.0.0.1';
|
||||
const port = 3000;
|
||||
|
||||
@ -8,7 +8,7 @@
|
||||
|
||||
The `timer` module exposes a global API for scheduling functions to
|
||||
be called at some future period of time. Because the timer functions are
|
||||
globals, there is no need to call `require('timers')` to use the API.
|
||||
globals, there is no need to call `require('node:timers')` to use the API.
|
||||
|
||||
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
|
||||
@ -269,7 +269,7 @@ returned Promises will be rejected with an `'AbortError'`.
|
||||
For `setImmediate()`:
|
||||
|
||||
```js
|
||||
const { setImmediate: setImmediatePromise } = require('timers/promises');
|
||||
const { setImmediate: setImmediatePromise } = require('node:timers/promises');
|
||||
|
||||
const ac = new AbortController();
|
||||
const signal = ac.signal;
|
||||
@ -287,7 +287,7 @@ ac.abort();
|
||||
For `setTimeout()`:
|
||||
|
||||
```js
|
||||
const { setTimeout: setTimeoutPromise } = require('timers/promises');
|
||||
const { setTimeout: setTimeoutPromise } = require('node:timers/promises');
|
||||
|
||||
const ac = new AbortController();
|
||||
const signal = ac.signal;
|
||||
@ -347,7 +347,7 @@ changes:
|
||||
|
||||
The `timers/promises` API provides an alternative set of timer functions
|
||||
that return `Promise` objects. The API is accessible via
|
||||
`require('timers/promises')`.
|
||||
`require('node:timers/promises')`.
|
||||
|
||||
```mjs
|
||||
import {
|
||||
@ -362,7 +362,7 @@ const {
|
||||
setTimeout,
|
||||
setImmediate,
|
||||
setInterval,
|
||||
} = require('timers/promises');
|
||||
} = require('node:timers/promises');
|
||||
```
|
||||
|
||||
### `timersPromises.setTimeout([delay[, value[, options]]])`
|
||||
@ -394,7 +394,7 @@ console.log(res); // Prints 'result'
|
||||
```cjs
|
||||
const {
|
||||
setTimeout,
|
||||
} = require('timers/promises');
|
||||
} = require('node:timers/promises');
|
||||
|
||||
setTimeout(100, 'result').then((res) => {
|
||||
console.log(res); // Prints 'result'
|
||||
@ -428,7 +428,7 @@ console.log(res); // Prints 'result'
|
||||
```cjs
|
||||
const {
|
||||
setImmediate,
|
||||
} = require('timers/promises');
|
||||
} = require('node:timers/promises');
|
||||
|
||||
setImmediate('result').then((res) => {
|
||||
console.log(res); // Prints 'result'
|
||||
@ -472,7 +472,7 @@ console.log(Date.now());
|
||||
```cjs
|
||||
const {
|
||||
setInterval,
|
||||
} = require('timers/promises');
|
||||
} = require('node:timers/promises');
|
||||
const interval = 100;
|
||||
|
||||
(async function() {
|
||||
@ -511,7 +511,7 @@ to calling `timersPromises.setTimeout(delay, undefined, options)` except that
|
||||
the `ref` option is not supported.
|
||||
|
||||
```mjs
|
||||
import { scheduler } from 'timers/promises';
|
||||
import { scheduler } from 'node:timers/promises';
|
||||
|
||||
await scheduler.wait(1000); // Wait one second before continuing
|
||||
```
|
||||
|
||||
@ -6,19 +6,19 @@
|
||||
|
||||
<!-- source_link=lib/tls.js -->
|
||||
|
||||
The `tls` module provides an implementation of the Transport Layer Security
|
||||
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.
|
||||
The module can be accessed using:
|
||||
|
||||
```js
|
||||
const tls = require('tls');
|
||||
const tls = require('node:tls');
|
||||
```
|
||||
|
||||
## Determining if crypto support is unavailable
|
||||
|
||||
It is possible for Node.js to be built without including support for the
|
||||
`crypto` module. In such cases, attempting to `import` from `tls` or
|
||||
calling `require('tls')` will result in an error being thrown.
|
||||
`node:crypto` module. In such cases, attempting to `import` from `tls` or
|
||||
calling `require('node:tls')` will result in an error being thrown.
|
||||
|
||||
When using CommonJS, the error thrown can be caught using try/catch:
|
||||
|
||||
@ -27,7 +27,7 @@ When using CommonJS, the error thrown can be caught using try/catch:
|
||||
```cjs
|
||||
let tls;
|
||||
try {
|
||||
tls = require('tls');
|
||||
tls = require('node:tls');
|
||||
} catch (err) {
|
||||
console.log('tls support is disabled!');
|
||||
}
|
||||
@ -45,7 +45,7 @@ of Node.js where crypto support is not enabled, consider using the
|
||||
```mjs
|
||||
let tls;
|
||||
try {
|
||||
tls = await import('tls');
|
||||
tls = await import('node:tls');
|
||||
} catch (err) {
|
||||
console.log('tls support is disabled!');
|
||||
}
|
||||
@ -127,10 +127,10 @@ the character "E" appended to the traditional abbreviations):
|
||||
* [ECDHE][]: An ephemeral version of the Elliptic Curve Diffie-Hellman
|
||||
key-agreement protocol.
|
||||
|
||||
To use perfect forward secrecy using `DHE` with the `tls` module, it is required
|
||||
to generate Diffie-Hellman parameters and specify them with the `dhparam`
|
||||
option to [`tls.createSecureContext()`][]. The following illustrates the use of
|
||||
the OpenSSL command-line interface to generate such parameters:
|
||||
To use perfect forward secrecy using `DHE` with the `node:tls` module, it is
|
||||
required to generate Diffie-Hellman parameters and specify them with the
|
||||
`dhparam` option to [`tls.createSecureContext()`][]. The following illustrates
|
||||
the use of the OpenSSL command-line interface to generate such parameters:
|
||||
|
||||
```bash
|
||||
openssl dhparam -outform PEM -out dhparam.pem 2048
|
||||
@ -279,7 +279,7 @@ on disk, and they should be regenerated regularly.
|
||||
|
||||
If clients advertise support for tickets, the server will send them. The
|
||||
server can disable tickets by supplying
|
||||
`require('constants').SSL_OP_NO_TICKET` in `secureOptions`.
|
||||
`require('node:constants').SSL_OP_NO_TICKET` in `secureOptions`.
|
||||
|
||||
Both session identifiers and session tickets timeout, causing the server to
|
||||
create new sessions. The timeout can be configured with the `sessionTimeout`
|
||||
@ -1692,8 +1692,8 @@ The following illustrates a client for the echo server example from
|
||||
|
||||
```js
|
||||
// Assumes an echo server that is listening on port 8000.
|
||||
const tls = require('tls');
|
||||
const fs = require('fs');
|
||||
const tls = require('node:tls');
|
||||
const fs = require('node:fs');
|
||||
|
||||
const options = {
|
||||
// Necessary only if the server requires client certificate authentication.
|
||||
@ -2093,14 +2093,14 @@ changes:
|
||||
Creates a new [`tls.Server`][]. The `secureConnectionListener`, if provided, is
|
||||
automatically set as a listener for the [`'secureConnection'`][] event.
|
||||
|
||||
The `ticketKeys` options is automatically shared between `cluster` module
|
||||
The `ticketKeys` options is automatically shared between `node:cluster` module
|
||||
workers.
|
||||
|
||||
The following illustrates a simple echo server:
|
||||
|
||||
```js
|
||||
const tls = require('tls');
|
||||
const fs = require('fs');
|
||||
const tls = require('node:tls');
|
||||
const fs = require('node:fs');
|
||||
|
||||
const options = {
|
||||
key: fs.readFileSync('server-key.pem'),
|
||||
|
||||
@ -6,11 +6,11 @@
|
||||
|
||||
<!-- source_link=lib/trace_events.js -->
|
||||
|
||||
The `trace_events` module provides a mechanism to centralize tracing information
|
||||
generated by V8, Node.js core, and userspace code.
|
||||
The `node:trace_events` module provides a mechanism to centralize tracing
|
||||
information generated by V8, Node.js core, and userspace code.
|
||||
|
||||
Tracing can be enabled with the `--trace-event-categories` command-line flag
|
||||
or by using the `trace_events` module. The `--trace-event-categories` flag
|
||||
or by using the `node:trace_events` module. The `--trace-event-categories` flag
|
||||
accepts a list of comma-separated category names.
|
||||
|
||||
The available categories are:
|
||||
@ -32,7 +32,7 @@ The available categories are:
|
||||
measurements.
|
||||
* `node.promises.rejections`: Enables capture of trace data tracking the number
|
||||
of unhandled Promise rejections and handled-after-rejections.
|
||||
* `node.vm.script`: Enables capture of trace data for the `vm` module's
|
||||
* `node.vm.script`: Enables capture of trace data for the `node:vm` module's
|
||||
`runInNewContext()`, `runInContext()`, and `runInThisContext()` methods.
|
||||
* `v8`: The [V8][] events are GC, compiling, and execution related.
|
||||
|
||||
@ -55,10 +55,10 @@ node --trace-events-enabled
|
||||
node --trace-event-categories v8,node,node.async_hooks
|
||||
```
|
||||
|
||||
Alternatively, trace events may be enabled using the `trace_events` module:
|
||||
Alternatively, trace events may be enabled using the `node:trace_events` module:
|
||||
|
||||
```js
|
||||
const trace_events = require('trace_events');
|
||||
const trace_events = require('node:trace_events');
|
||||
const tracing = trace_events.createTracing({ categories: ['node.perf'] });
|
||||
tracing.enable(); // Enable trace event capture for the 'node.perf' category
|
||||
|
||||
@ -98,7 +98,7 @@ unlike `process.hrtime()` which returns nanoseconds.
|
||||
|
||||
The features from this module are not available in [`Worker`][] threads.
|
||||
|
||||
## The `trace_events` module
|
||||
## The `node:trace_events` module
|
||||
|
||||
<!-- YAML
|
||||
added: v10.0.0
|
||||
@ -142,7 +142,7 @@ Only trace event categories _not_ covered by other enabled `Tracing` objects
|
||||
and _not_ specified by the `--trace-event-categories` flag will be disabled.
|
||||
|
||||
```js
|
||||
const trace_events = require('trace_events');
|
||||
const trace_events = require('node:trace_events');
|
||||
const t1 = trace_events.createTracing({ categories: ['node', 'v8'] });
|
||||
const t2 = trace_events.createTracing({ categories: ['node.perf', 'node'] });
|
||||
t1.enable();
|
||||
@ -189,7 +189,7 @@ added: v10.0.0
|
||||
Creates and returns a `Tracing` object for the given set of `categories`.
|
||||
|
||||
```js
|
||||
const trace_events = require('trace_events');
|
||||
const trace_events = require('node:trace_events');
|
||||
const categories = ['node.perf', 'node.async_hooks'];
|
||||
const tracing = trace_events.createTracing({ categories });
|
||||
tracing.enable();
|
||||
@ -215,7 +215,7 @@ Given the file `test.js` below, the command
|
||||
`'node.async_hooks,node.perf'` to the console.
|
||||
|
||||
```js
|
||||
const trace_events = require('trace_events');
|
||||
const trace_events = require('node:trace_events');
|
||||
const t1 = trace_events.createTracing({ categories: ['node.async_hooks'] });
|
||||
const t2 = trace_events.createTracing({ categories: ['node.perf'] });
|
||||
const t3 = trace_events.createTracing({ categories: ['v8'] });
|
||||
|
||||
@ -6,12 +6,12 @@
|
||||
|
||||
<!-- source_link=lib/tty.js -->
|
||||
|
||||
The `tty` module provides the `tty.ReadStream` and `tty.WriteStream` classes.
|
||||
In most cases, it will not be necessary or possible to use this module directly.
|
||||
However, it can be accessed using:
|
||||
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
|
||||
directly. However, it can be accessed using:
|
||||
|
||||
```js
|
||||
const tty = require('tty');
|
||||
const tty = require('node:tty');
|
||||
```
|
||||
|
||||
When Node.js detects that it is being run with a text terminal ("TTY")
|
||||
|
||||
@ -6,15 +6,15 @@
|
||||
|
||||
<!-- source_link=lib/url.js -->
|
||||
|
||||
The `url` module provides utilities for URL resolution and parsing. It can be
|
||||
accessed using:
|
||||
The `node:url` module provides utilities for URL resolution and parsing. It can
|
||||
be accessed using:
|
||||
|
||||
```mjs
|
||||
import url from 'url';
|
||||
import url from 'node:url';
|
||||
```
|
||||
|
||||
```cjs
|
||||
const url = require('url');
|
||||
const url = require('node:url');
|
||||
```
|
||||
|
||||
## URL strings and URL objects
|
||||
@ -23,8 +23,8 @@ A URL string is a structured string containing multiple meaningful components.
|
||||
When parsed, a URL object is returned containing properties for each of these
|
||||
components.
|
||||
|
||||
The `url` module provides two APIs for working with URLs: a legacy API that is
|
||||
Node.js specific, and a newer API that implements the same
|
||||
The `node:url` module provides two APIs for working with URLs: a legacy API that
|
||||
is Node.js specific, and a newer API that implements the same
|
||||
[WHATWG URL Standard][] used by web browsers.
|
||||
|
||||
A comparison between the WHATWG and Legacy APIs is provided below. Above the URL
|
||||
@ -66,13 +66,13 @@ const myURL =
|
||||
Parsing the URL string using the Legacy API:
|
||||
|
||||
```mjs
|
||||
import url from 'url';
|
||||
import url from 'node:url';
|
||||
const myURL =
|
||||
url.parse('https://user:pass@sub.example.com:8080/p/a/t/h?query=string#hash');
|
||||
```
|
||||
|
||||
```cjs
|
||||
const url = require('url');
|
||||
const url = require('node:url');
|
||||
const myURL =
|
||||
url.parse('https://user:pass@sub.example.com:8080/p/a/t/h?query=string#hash');
|
||||
```
|
||||
@ -147,12 +147,12 @@ The URL constructor is accessible as a property on the global object.
|
||||
It can also be imported from the built-in url module:
|
||||
|
||||
```mjs
|
||||
import { URL } from 'url';
|
||||
import { URL } from 'node:url';
|
||||
console.log(URL === globalThis.URL); // Prints 'true'.
|
||||
```
|
||||
|
||||
```cjs
|
||||
console.log(URL === require('url').URL); // Prints 'true'.
|
||||
console.log(URL === require('node:url').URL); // Prints 'true'.
|
||||
```
|
||||
|
||||
A `TypeError` will be thrown if the `input` or `base` are not valid URLs. Note
|
||||
@ -630,7 +630,7 @@ object and can be used to retrieve the `Blob` later.
|
||||
const {
|
||||
Blob,
|
||||
resolveObjectURL,
|
||||
} = require('buffer');
|
||||
} = require('node:buffer');
|
||||
|
||||
const blob = new Blob(['hello']);
|
||||
const id = URL.createObjectURL(blob);
|
||||
@ -1014,7 +1014,7 @@ This feature is only available if the `node` executable was compiled with
|
||||
[ICU][] enabled. If not, the domain names are passed through unchanged.
|
||||
|
||||
```mjs
|
||||
import url from 'url';
|
||||
import url from 'node:url';
|
||||
|
||||
console.log(url.domainToASCII('español.com'));
|
||||
// Prints xn--espaol-zwa.com
|
||||
@ -1025,7 +1025,7 @@ console.log(url.domainToASCII('xn--iñvalid.com'));
|
||||
```
|
||||
|
||||
```cjs
|
||||
const url = require('url');
|
||||
const url = require('node:url');
|
||||
|
||||
console.log(url.domainToASCII('español.com'));
|
||||
// Prints xn--espaol-zwa.com
|
||||
@ -1055,7 +1055,7 @@ This feature is only available if the `node` executable was compiled with
|
||||
[ICU][] enabled. If not, the domain names are passed through unchanged.
|
||||
|
||||
```mjs
|
||||
import url from 'url';
|
||||
import url from 'node:url';
|
||||
|
||||
console.log(url.domainToUnicode('xn--espaol-zwa.com'));
|
||||
// Prints español.com
|
||||
@ -1066,7 +1066,7 @@ console.log(url.domainToUnicode('xn--iñvalid.com'));
|
||||
```
|
||||
|
||||
```cjs
|
||||
const url = require('url');
|
||||
const url = require('node:url');
|
||||
|
||||
console.log(url.domainToUnicode('xn--espaol-zwa.com'));
|
||||
// Prints español.com
|
||||
@ -1089,7 +1089,7 @@ This function ensures the correct decodings of percent-encoded characters as
|
||||
well as ensuring a cross-platform valid absolute path string.
|
||||
|
||||
```mjs
|
||||
import { fileURLToPath } from 'url';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
const __filename = fileURLToPath(import.meta.url);
|
||||
|
||||
@ -1107,7 +1107,7 @@ fileURLToPath('file:///hello world'); // Correct: /hello world (POSIX)
|
||||
```
|
||||
|
||||
```cjs
|
||||
const { fileURLToPath } = require('url');
|
||||
const { fileURLToPath } = require('node:url');
|
||||
new URL('file:///C:/path/').pathname; // Incorrect: /C:/path/
|
||||
fileURLToPath('file:///C:/path/'); // Correct: C:\path\ (Windows)
|
||||
|
||||
@ -1149,7 +1149,7 @@ any way. The `url.format(URL[, options])` method allows for basic customization
|
||||
of the output.
|
||||
|
||||
```mjs
|
||||
import url from 'url';
|
||||
import url from 'node:url';
|
||||
const myURL = new URL('https://a:b@測試?abc#foo');
|
||||
|
||||
console.log(myURL.href);
|
||||
@ -1163,7 +1163,7 @@ console.log(url.format(myURL, { fragment: false, unicode: true, auth: false }));
|
||||
```
|
||||
|
||||
```cjs
|
||||
const url = require('url');
|
||||
const url = require('node:url');
|
||||
const myURL = new URL('https://a:b@測試?abc#foo');
|
||||
|
||||
console.log(myURL.href);
|
||||
@ -1189,7 +1189,7 @@ This function ensures that `path` is resolved absolutely, and that the URL
|
||||
control characters are correctly encoded when converting into a File URL.
|
||||
|
||||
```mjs
|
||||
import { pathToFileURL } from 'url';
|
||||
import { pathToFileURL } from 'node:url';
|
||||
|
||||
new URL('/foo#1', 'file:'); // Incorrect: file:///foo#1
|
||||
pathToFileURL('/foo#1'); // Correct: file:///foo%231 (POSIX)
|
||||
@ -1199,7 +1199,7 @@ pathToFileURL('/some/path%.c'); // Correct: file:///some/path%25.c (POSI
|
||||
```
|
||||
|
||||
```cjs
|
||||
const { pathToFileURL } = require('url');
|
||||
const { pathToFileURL } = require('node:url');
|
||||
new URL(__filename); // Incorrect: throws (POSIX)
|
||||
new URL(__filename); // Incorrect: C:\... (Windows)
|
||||
pathToFileURL(__filename); // Correct: file:///... (POSIX)
|
||||
@ -1241,7 +1241,7 @@ This utility function converts a URL object into an ordinary options object as
|
||||
expected by the [`http.request()`][] and [`https.request()`][] APIs.
|
||||
|
||||
```mjs
|
||||
import { urlToHttpOptions } from 'url';
|
||||
import { urlToHttpOptions } from 'node:url';
|
||||
const myURL = new URL('https://a:b@測試?abc#foo');
|
||||
|
||||
console.log(urlToHttpOptions(myURL));
|
||||
@ -1260,7 +1260,7 @@ console.log(urlToHttpOptions(myURL));
|
||||
```
|
||||
|
||||
```cjs
|
||||
const { urlToHttpOptions } = require('url');
|
||||
const { urlToHttpOptions } = require('node:url');
|
||||
const myURL = new URL('https://a:b@測試?abc#foo');
|
||||
|
||||
console.log(urlToHttpOptions(myUrl));
|
||||
@ -1310,7 +1310,8 @@ changes:
|
||||
|
||||
> Stability: 3 - Legacy: Use the WHATWG URL API instead.
|
||||
|
||||
The legacy `urlObject` (`require('url').Url` or `import { Url } from 'url'`) is
|
||||
The legacy `urlObject` (`require('node:url').Url` or
|
||||
`import { Url } from 'node:url'`) is
|
||||
created and returned by the `url.parse()` function.
|
||||
|
||||
#### `urlObject.auth`
|
||||
@ -1446,7 +1447,7 @@ The `url.format()` method returns a formatted URL string derived from
|
||||
`urlObject`.
|
||||
|
||||
```js
|
||||
const url = require('url');
|
||||
const url = require('node:url');
|
||||
url.format({
|
||||
protocol: 'https',
|
||||
hostname: 'example.com',
|
||||
@ -1609,7 +1610,7 @@ The `url.resolve()` method resolves a target URL relative to a base URL in a
|
||||
manner similar to that of a web browser resolving an anchor tag.
|
||||
|
||||
```js
|
||||
const url = require('url');
|
||||
const url = require('node:url');
|
||||
url.resolve('/one/two/three', 'four'); // '/one/two/four'
|
||||
url.resolve('http://example.com/', '/one'); // 'http://example.com/one'
|
||||
url.resolve('http://example.com/one', '/two'); // 'http://example.com/two'
|
||||
|
||||
@ -6,12 +6,12 @@
|
||||
|
||||
<!-- source_link=lib/util.js -->
|
||||
|
||||
The `util` module supports the needs of Node.js internal APIs. Many of the
|
||||
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
|
||||
it:
|
||||
|
||||
```js
|
||||
const util = require('util');
|
||||
const util = require('node:util');
|
||||
```
|
||||
|
||||
## `util.callbackify(original)`
|
||||
@ -30,7 +30,7 @@ first argument will be the rejection reason (or `null` if the `Promise`
|
||||
resolved), and the second argument will be the resolved value.
|
||||
|
||||
```js
|
||||
const util = require('util');
|
||||
const util = require('node:util');
|
||||
|
||||
async function fn() {
|
||||
return 'hello world';
|
||||
@ -90,7 +90,7 @@ environment variable, then the returned function operates similar to
|
||||
[`console.error()`][]. If not, then the returned function is a no-op.
|
||||
|
||||
```js
|
||||
const util = require('util');
|
||||
const util = require('node:util');
|
||||
const debuglog = util.debuglog('foo');
|
||||
|
||||
debuglog('hello from foo [%d]', 123);
|
||||
@ -109,7 +109,7 @@ environment variable set, then it will not print anything.
|
||||
The `section` supports wildcard also:
|
||||
|
||||
```js
|
||||
const util = require('util');
|
||||
const util = require('node:util');
|
||||
const debuglog = util.debuglog('foo-bar');
|
||||
|
||||
debuglog('hi there, it\'s foo-bar [%d]', 2333);
|
||||
@ -130,7 +130,7 @@ with a different function that doesn't have any initialization or
|
||||
unnecessary wrapping.
|
||||
|
||||
```js
|
||||
const util = require('util');
|
||||
const util = require('node:util');
|
||||
let debuglog = util.debuglog('internals', (debug) => {
|
||||
// Replace with a logging function that optimizes out
|
||||
// testing if the section is enabled
|
||||
@ -153,7 +153,7 @@ then the returned value will be `true`. If not, then the returned value will be
|
||||
`false`.
|
||||
|
||||
```js
|
||||
const util = require('util');
|
||||
const util = require('node:util');
|
||||
const enabled = util.debuglog('foo').enabled;
|
||||
if (enabled) {
|
||||
console.log('hello from foo [%d]', 123);
|
||||
@ -197,7 +197,7 @@ The `util.deprecate()` method wraps `fn` (which may be a function or class) in
|
||||
such a way that it is marked as deprecated.
|
||||
|
||||
```js
|
||||
const util = require('util');
|
||||
const util = require('node:util');
|
||||
|
||||
exports.obsoleteFunction = util.deprecate(() => {
|
||||
// Do something here.
|
||||
@ -214,7 +214,7 @@ If the same optional `code` is supplied in multiple calls to `util.deprecate()`,
|
||||
the warning will be emitted only once for that `code`.
|
||||
|
||||
```js
|
||||
const util = require('util');
|
||||
const util = require('node:util');
|
||||
|
||||
const fn1 = util.deprecate(someFunction, someMessage, 'DEP0001');
|
||||
const fn2 = util.deprecate(someOtherFunction, someOtherMessage, 'DEP0001');
|
||||
@ -435,8 +435,8 @@ As an additional convenience, `superConstructor` will be accessible
|
||||
through the `constructor.super_` property.
|
||||
|
||||
```js
|
||||
const util = require('util');
|
||||
const EventEmitter = require('events');
|
||||
const util = require('node:util');
|
||||
const EventEmitter = require('node:events');
|
||||
|
||||
function MyStream() {
|
||||
EventEmitter.call(this);
|
||||
@ -462,7 +462,7 @@ stream.write('It works!'); // Received data: "It works!"
|
||||
ES6 example using `class` and `extends`:
|
||||
|
||||
```js
|
||||
const EventEmitter = require('events');
|
||||
const EventEmitter = require('node:events');
|
||||
|
||||
class MyStream extends EventEmitter {
|
||||
write(data) {
|
||||
@ -642,7 +642,7 @@ util.inspect(baz); // '[foo] {}'
|
||||
Circular references point to their anchor by using a reference index:
|
||||
|
||||
```js
|
||||
const { inspect } = require('util');
|
||||
const { inspect } = require('node:util');
|
||||
|
||||
const obj = {};
|
||||
obj.a = [obj];
|
||||
@ -660,7 +660,7 @@ console.log(inspect(obj));
|
||||
The following example inspects all properties of the `util` object:
|
||||
|
||||
```js
|
||||
const util = require('util');
|
||||
const util = require('node:util');
|
||||
|
||||
console.log(util.inspect(util, { showHidden: true, depth: null }));
|
||||
```
|
||||
@ -668,7 +668,7 @@ console.log(util.inspect(util, { showHidden: true, depth: null }));
|
||||
The following example highlights the effect of the `compact` option:
|
||||
|
||||
```js
|
||||
const util = require('util');
|
||||
const util = require('node:util');
|
||||
|
||||
const o = {
|
||||
a: [1, 2, [[
|
||||
@ -724,7 +724,7 @@ guarantee which entries are displayed. That means retrieving the same
|
||||
with no remaining strong references may be garbage collected at any time.
|
||||
|
||||
```js
|
||||
const { inspect } = require('util');
|
||||
const { inspect } = require('node:util');
|
||||
|
||||
const obj = { a: 1 };
|
||||
const obj2 = { b: 2 };
|
||||
@ -738,8 +738,8 @@ The `sorted` option ensures that an object's property insertion order does not
|
||||
impact the result of `util.inspect()`.
|
||||
|
||||
```js
|
||||
const { inspect } = require('util');
|
||||
const assert = require('assert');
|
||||
const { inspect } = require('node:util');
|
||||
const assert = require('node:assert');
|
||||
|
||||
const o1 = {
|
||||
b: [2, 3, 1],
|
||||
@ -766,7 +766,7 @@ The `numericSeparator` option adds an underscore every three digits to all
|
||||
numbers.
|
||||
|
||||
```js
|
||||
const { inspect } = require('util');
|
||||
const { inspect } = require('node:util');
|
||||
|
||||
const thousand = 1_000;
|
||||
const million = 1_000_000;
|
||||
@ -892,7 +892,7 @@ which `util.inspect()` will invoke and use the result of when inspecting
|
||||
the object.
|
||||
|
||||
```js
|
||||
const util = require('util');
|
||||
const util = require('node:util');
|
||||
|
||||
class Box {
|
||||
constructor(value) {
|
||||
@ -927,7 +927,7 @@ a string but may return a value of any type that will be formatted accordingly
|
||||
by `util.inspect()`.
|
||||
|
||||
```js
|
||||
const util = require('util');
|
||||
const util = require('node:util');
|
||||
|
||||
const obj = { foo: 'this will not show up in the inspect() output' };
|
||||
obj[util.inspect.custom] = (depth) => {
|
||||
@ -996,7 +996,7 @@ object containing one or more valid [`util.inspect()`][] options. Setting
|
||||
option properties directly is also supported.
|
||||
|
||||
```js
|
||||
const util = require('util');
|
||||
const util = require('node:util');
|
||||
const arr = Array(101).fill(0);
|
||||
|
||||
console.log(arr); // Logs the truncated array
|
||||
@ -1034,8 +1034,8 @@ an `(err, value) => ...` callback as the last argument, and returns a version
|
||||
that returns promises.
|
||||
|
||||
```js
|
||||
const util = require('util');
|
||||
const fs = require('fs');
|
||||
const util = require('node:util');
|
||||
const fs = require('node:fs');
|
||||
|
||||
const stat = util.promisify(fs.stat);
|
||||
stat('.').then((stats) => {
|
||||
@ -1048,8 +1048,8 @@ stat('.').then((stats) => {
|
||||
Or, equivalently using `async function`s:
|
||||
|
||||
```js
|
||||
const util = require('util');
|
||||
const fs = require('fs');
|
||||
const util = require('node:util');
|
||||
const fs = require('node:fs');
|
||||
|
||||
const stat = util.promisify(fs.stat);
|
||||
|
||||
@ -1072,7 +1072,7 @@ Using `promisify()` on class methods or other methods that use `this` may not
|
||||
work as expected unless handled specially:
|
||||
|
||||
```js
|
||||
const util = require('util');
|
||||
const util = require('node:util');
|
||||
|
||||
class Foo {
|
||||
constructor() {
|
||||
@ -1102,7 +1102,7 @@ Using the `util.promisify.custom` symbol one can override the return value of
|
||||
[`util.promisify()`][]:
|
||||
|
||||
```js
|
||||
const util = require('util');
|
||||
const util = require('node:util');
|
||||
|
||||
function doSomething(foo, callback) {
|
||||
// ...
|
||||
@ -1397,7 +1397,7 @@ added: v10.0.0
|
||||
changes:
|
||||
- version: v15.3.0
|
||||
pr-url: https://github.com/nodejs/node/pull/34055
|
||||
description: Exposed as `require('util/types')`.
|
||||
description: Exposed as `require('node:util/types')`.
|
||||
-->
|
||||
|
||||
`util.types` provides type checks for different kinds of built-in objects.
|
||||
@ -1409,7 +1409,7 @@ The result generally does not make any guarantees about what kinds of
|
||||
properties or behavior a value exposes in JavaScript. They are primarily
|
||||
useful for addon developers who prefer to do type checking in JavaScript.
|
||||
|
||||
The API is accessible via `require('util').types` or `require('util/types')`.
|
||||
The API is accessible via `require('node:util').types` or `require('node:util/types')`.
|
||||
|
||||
### `util.types.isAnyArrayBuffer(value)`
|
||||
|
||||
@ -2210,7 +2210,7 @@ Alias for [`Array.isArray()`][].
|
||||
Returns `true` if the given `object` is an `Array`. Otherwise, returns `false`.
|
||||
|
||||
```js
|
||||
const util = require('util');
|
||||
const util = require('node:util');
|
||||
|
||||
util.isArray([]);
|
||||
// Returns: true
|
||||
@ -2235,7 +2235,7 @@ deprecated: v4.0.0
|
||||
Returns `true` if the given `object` is a `Boolean`. Otherwise, returns `false`.
|
||||
|
||||
```js
|
||||
const util = require('util');
|
||||
const util = require('node:util');
|
||||
|
||||
util.isBoolean(1);
|
||||
// Returns: false
|
||||
@ -2260,7 +2260,7 @@ deprecated: v4.0.0
|
||||
Returns `true` if the given `object` is a `Buffer`. Otherwise, returns `false`.
|
||||
|
||||
```js
|
||||
const util = require('util');
|
||||
const util = require('node:util');
|
||||
|
||||
util.isBuffer({ length: 0 });
|
||||
// Returns: false
|
||||
@ -2285,7 +2285,7 @@ deprecated: v4.0.0
|
||||
Returns `true` if the given `object` is a `Date`. Otherwise, returns `false`.
|
||||
|
||||
```js
|
||||
const util = require('util');
|
||||
const util = require('node:util');
|
||||
|
||||
util.isDate(new Date());
|
||||
// Returns: true
|
||||
@ -2311,7 +2311,7 @@ Returns `true` if the given `object` is an [`Error`][]. Otherwise, returns
|
||||
`false`.
|
||||
|
||||
```js
|
||||
const util = require('util');
|
||||
const util = require('node:util');
|
||||
|
||||
util.isError(new Error());
|
||||
// Returns: true
|
||||
@ -2326,7 +2326,7 @@ possible to obtain an incorrect result when the `object` argument manipulates
|
||||
`@@toStringTag`.
|
||||
|
||||
```js
|
||||
const util = require('util');
|
||||
const util = require('node:util');
|
||||
const obj = { name: 'Error', message: 'an error occurred' };
|
||||
|
||||
util.isError(obj);
|
||||
@ -2352,7 +2352,7 @@ Returns `true` if the given `object` is a `Function`. Otherwise, returns
|
||||
`false`.
|
||||
|
||||
```js
|
||||
const util = require('util');
|
||||
const util = require('node:util');
|
||||
|
||||
function Foo() {}
|
||||
const Bar = () => {};
|
||||
@ -2381,7 +2381,7 @@ Returns `true` if the given `object` is strictly `null`. Otherwise, returns
|
||||
`false`.
|
||||
|
||||
```js
|
||||
const util = require('util');
|
||||
const util = require('node:util');
|
||||
|
||||
util.isNull(0);
|
||||
// Returns: false
|
||||
@ -2408,7 +2408,7 @@ Returns `true` if the given `object` is `null` or `undefined`. Otherwise,
|
||||
returns `false`.
|
||||
|
||||
```js
|
||||
const util = require('util');
|
||||
const util = require('node:util');
|
||||
|
||||
util.isNullOrUndefined(0);
|
||||
// Returns: false
|
||||
@ -2433,7 +2433,7 @@ deprecated: v4.0.0
|
||||
Returns `true` if the given `object` is a `Number`. Otherwise, returns `false`.
|
||||
|
||||
```js
|
||||
const util = require('util');
|
||||
const util = require('node:util');
|
||||
|
||||
util.isNumber(false);
|
||||
// Returns: false
|
||||
@ -2463,7 +2463,7 @@ Returns `true` if the given `object` is strictly an `Object` **and** not a
|
||||
Otherwise, returns `false`.
|
||||
|
||||
```js
|
||||
const util = require('util');
|
||||
const util = require('node:util');
|
||||
|
||||
util.isObject(5);
|
||||
// Returns: false
|
||||
@ -2493,7 +2493,7 @@ Returns `true` if the given `object` is a primitive type. Otherwise, returns
|
||||
`false`.
|
||||
|
||||
```js
|
||||
const util = require('util');
|
||||
const util = require('node:util');
|
||||
|
||||
util.isPrimitive(5);
|
||||
// Returns: true
|
||||
@ -2530,7 +2530,7 @@ deprecated: v4.0.0
|
||||
Returns `true` if the given `object` is a `RegExp`. Otherwise, returns `false`.
|
||||
|
||||
```js
|
||||
const util = require('util');
|
||||
const util = require('node:util');
|
||||
|
||||
util.isRegExp(/some regexp/);
|
||||
// Returns: true
|
||||
@ -2555,7 +2555,7 @@ deprecated: v4.0.0
|
||||
Returns `true` if the given `object` is a `string`. Otherwise, returns `false`.
|
||||
|
||||
```js
|
||||
const util = require('util');
|
||||
const util = require('node:util');
|
||||
|
||||
util.isString('');
|
||||
// Returns: true
|
||||
@ -2582,7 +2582,7 @@ deprecated: v4.0.0
|
||||
Returns `true` if the given `object` is a `Symbol`. Otherwise, returns `false`.
|
||||
|
||||
```js
|
||||
const util = require('util');
|
||||
const util = require('node:util');
|
||||
|
||||
util.isSymbol(5);
|
||||
// Returns: false
|
||||
@ -2607,7 +2607,7 @@ deprecated: v4.0.0
|
||||
Returns `true` if the given `object` is `undefined`. Otherwise, returns `false`.
|
||||
|
||||
```js
|
||||
const util = require('util');
|
||||
const util = require('node:util');
|
||||
|
||||
const foo = undefined;
|
||||
util.isUndefined(5);
|
||||
@ -2633,7 +2633,7 @@ The `util.log()` method prints the given `string` to `stdout` with an included
|
||||
timestamp.
|
||||
|
||||
```js
|
||||
const util = require('util');
|
||||
const util = require('node:util');
|
||||
|
||||
util.log('Timestamped message.');
|
||||
```
|
||||
|
||||
@ -4,11 +4,11 @@
|
||||
|
||||
<!-- source_link=lib/v8.js -->
|
||||
|
||||
The `v8` module exposes APIs that are specific to the version of [V8][]
|
||||
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:
|
||||
|
||||
```js
|
||||
const v8 = require('v8');
|
||||
const v8 = require('node:v8');
|
||||
```
|
||||
|
||||
## `v8.cachedDataVersionTag()`
|
||||
@ -80,7 +80,7 @@ for a duration depending on the heap size.
|
||||
|
||||
```js
|
||||
// Print heap snapshot to the console
|
||||
const v8 = require('v8');
|
||||
const v8 = require('node:v8');
|
||||
const stream = v8.getHeapSnapshot();
|
||||
stream.pipe(process.stdout);
|
||||
```
|
||||
@ -233,7 +233,7 @@ Usage:
|
||||
|
||||
```js
|
||||
// Print GC events to stdout for one minute.
|
||||
const v8 = require('v8');
|
||||
const v8 = require('node:v8');
|
||||
v8.setFlagsFromString('--trace_gc');
|
||||
setTimeout(() => { v8.setFlagsFromString('--notrace_gc'); }, 60e3);
|
||||
```
|
||||
@ -308,12 +308,12 @@ Generating a snapshot is a synchronous operation which blocks the event loop
|
||||
for a duration depending on the heap size.
|
||||
|
||||
```js
|
||||
const { writeHeapSnapshot } = require('v8');
|
||||
const { writeHeapSnapshot } = require('node:v8');
|
||||
const {
|
||||
Worker,
|
||||
isMainThread,
|
||||
parentPort
|
||||
} = require('worker_threads');
|
||||
} = require('node:worker_threads');
|
||||
|
||||
if (isMainThread) {
|
||||
const worker = new Worker(__filename);
|
||||
@ -593,7 +593,7 @@ module to produce promise lifecycle events in addition to events for other
|
||||
async resources. For request context management, see [`AsyncLocalStorage`][].
|
||||
|
||||
```mjs
|
||||
import { promiseHooks } from 'v8';
|
||||
import { promiseHooks } from 'node:v8';
|
||||
|
||||
// There are four lifecycle events produced by promises:
|
||||
|
||||
@ -662,13 +662,13 @@ added:
|
||||
throw as it would produce an infinite microtask loop.**
|
||||
|
||||
```mjs
|
||||
import { promiseHooks } from 'v8';
|
||||
import { promiseHooks } from 'node:v8';
|
||||
|
||||
const stop = promiseHooks.onInit((promise, parent) => {});
|
||||
```
|
||||
|
||||
```cjs
|
||||
const { promiseHooks } = require('v8');
|
||||
const { promiseHooks } = require('node:v8');
|
||||
|
||||
const stop = promiseHooks.onInit((promise, parent) => {});
|
||||
```
|
||||
@ -689,13 +689,13 @@ added:
|
||||
throw as it would produce an infinite microtask loop.**
|
||||
|
||||
```mjs
|
||||
import { promiseHooks } from 'v8';
|
||||
import { promiseHooks } from 'node:v8';
|
||||
|
||||
const stop = promiseHooks.onSettled((promise) => {});
|
||||
```
|
||||
|
||||
```cjs
|
||||
const { promiseHooks } = require('v8');
|
||||
const { promiseHooks } = require('node:v8');
|
||||
|
||||
const stop = promiseHooks.onSettled((promise) => {});
|
||||
```
|
||||
@ -716,13 +716,13 @@ added:
|
||||
throw as it would produce an infinite microtask loop.**
|
||||
|
||||
```mjs
|
||||
import { promiseHooks } from 'v8';
|
||||
import { promiseHooks } from 'node:v8';
|
||||
|
||||
const stop = promiseHooks.onBefore((promise) => {});
|
||||
```
|
||||
|
||||
```cjs
|
||||
const { promiseHooks } = require('v8');
|
||||
const { promiseHooks } = require('node:v8');
|
||||
|
||||
const stop = promiseHooks.onBefore((promise) => {});
|
||||
```
|
||||
@ -743,13 +743,13 @@ added:
|
||||
throw as it would produce an infinite microtask loop.**
|
||||
|
||||
```mjs
|
||||
import { promiseHooks } from 'v8';
|
||||
import { promiseHooks } from 'node:v8';
|
||||
|
||||
const stop = promiseHooks.onAfter((promise) => {});
|
||||
```
|
||||
|
||||
```cjs
|
||||
const { promiseHooks } = require('v8');
|
||||
const { promiseHooks } = require('node:v8');
|
||||
|
||||
const stop = promiseHooks.onAfter((promise) => {});
|
||||
```
|
||||
@ -783,7 +783,7 @@ specifics of all functions that can be passed to `callbacks` is in the
|
||||
[Hook Callbacks][] section.
|
||||
|
||||
```mjs
|
||||
import { promiseHooks } from 'v8';
|
||||
import { promiseHooks } from 'node:v8';
|
||||
|
||||
const stopAll = promiseHooks.createHook({
|
||||
init(promise, parent) {}
|
||||
@ -791,7 +791,7 @@ const stopAll = promiseHooks.createHook({
|
||||
```
|
||||
|
||||
```cjs
|
||||
const { promiseHooks } = require('v8');
|
||||
const { promiseHooks } = require('node:v8');
|
||||
|
||||
const stopAll = promiseHooks.createHook({
|
||||
init(promise, parent) {}
|
||||
|
||||
@ -8,10 +8,10 @@
|
||||
|
||||
<!-- source_link=lib/vm.js -->
|
||||
|
||||
The `vm` module enables compiling and running code within V8 Virtual
|
||||
The `node:vm` module enables compiling and running code within V8 Virtual
|
||||
Machine contexts.
|
||||
|
||||
<strong class="critical">The `vm` module is not a security
|
||||
<strong class="critical">The `node:vm` module is not a security
|
||||
mechanism. Do not use it to run untrusted code.</strong>
|
||||
|
||||
JavaScript code can be compiled and run immediately or
|
||||
@ -26,7 +26,7 @@ global variable. Any changes to global variables caused by the invoked
|
||||
code are reflected in the context object.
|
||||
|
||||
```js
|
||||
const vm = require('vm');
|
||||
const vm = require('node:vm');
|
||||
|
||||
const x = 1;
|
||||
|
||||
@ -177,7 +177,7 @@ the value of another global variable, then execute the code multiple times.
|
||||
The globals are contained in the `context` object.
|
||||
|
||||
```js
|
||||
const vm = require('vm');
|
||||
const vm = require('node:vm');
|
||||
|
||||
const context = {
|
||||
animal: 'cat',
|
||||
@ -259,7 +259,7 @@ the code multiple times in different contexts. The globals are set on and
|
||||
contained within each individual `context`.
|
||||
|
||||
```js
|
||||
const vm = require('vm');
|
||||
const vm = require('node:vm');
|
||||
|
||||
const script = new vm.Script('globalVar = "set"');
|
||||
|
||||
@ -304,7 +304,7 @@ The following example compiles code that increments a `global` variable then
|
||||
executes that code multiple times:
|
||||
|
||||
```js
|
||||
const vm = require('vm');
|
||||
const vm = require('node:vm');
|
||||
|
||||
global.globalVar = 0;
|
||||
|
||||
@ -351,7 +351,7 @@ loader][]. There is also no way to interact with the Loader yet, though
|
||||
support is planned.
|
||||
|
||||
```mjs
|
||||
import vm from 'vm';
|
||||
import vm from 'node:vm';
|
||||
|
||||
const contextifiedObject = vm.createContext({
|
||||
secret: 42,
|
||||
@ -422,7 +422,7 @@ await bar.evaluate();
|
||||
```
|
||||
|
||||
```cjs
|
||||
const vm = require('vm');
|
||||
const vm = require('node:vm');
|
||||
|
||||
const contextifiedObject = vm.createContext({
|
||||
secret: 42,
|
||||
@ -712,7 +712,7 @@ allow the module to access information outside the specified `context`. Use
|
||||
`vm.runInContext()` to create objects in a specific context.
|
||||
|
||||
```mjs
|
||||
import vm from 'vm';
|
||||
import vm from 'node:vm';
|
||||
|
||||
const contextifiedObject = vm.createContext({ secret: 42 });
|
||||
|
||||
@ -740,7 +740,7 @@ await module.evaluate();
|
||||
```
|
||||
|
||||
```cjs
|
||||
const vm = require('vm');
|
||||
const vm = require('node:vm');
|
||||
const contextifiedObject = vm.createContext({ secret: 42 });
|
||||
(async () => {
|
||||
const module = new vm.SourceTextModule(
|
||||
@ -812,7 +812,7 @@ provide a generic interface for exposing non-JavaScript sources to ECMAScript
|
||||
module graphs.
|
||||
|
||||
```js
|
||||
const vm = require('vm');
|
||||
const vm = require('node:vm');
|
||||
|
||||
const source = '{ "a": 1 }';
|
||||
const module = new vm.SyntheticModule(['default'], function() {
|
||||
@ -863,7 +863,7 @@ it is called before the module is linked, an [`ERR_VM_MODULE_STATUS`][] error
|
||||
will be thrown.
|
||||
|
||||
```mjs
|
||||
import vm from 'vm';
|
||||
import vm from 'node:vm';
|
||||
|
||||
const m = new vm.SyntheticModule(['x'], () => {
|
||||
m.setExport('x', 1);
|
||||
@ -876,7 +876,7 @@ assert.strictEqual(m.namespace.x, 1);
|
||||
```
|
||||
|
||||
```cjs
|
||||
const vm = require('vm');
|
||||
const vm = require('node:vm');
|
||||
(async () => {
|
||||
const m = new vm.SyntheticModule(['x'], () => {
|
||||
m.setExport('x', 1);
|
||||
@ -999,7 +999,7 @@ properties but also having the built-in objects and functions any standard
|
||||
will remain unchanged.
|
||||
|
||||
```js
|
||||
const vm = require('vm');
|
||||
const vm = require('node:vm');
|
||||
|
||||
global.globalVar = 3;
|
||||
|
||||
@ -1075,7 +1075,7 @@ the V8 engine, while the result of `v8.getHeapSpaceStatistics()` measure
|
||||
the memory occupied by each heap space in the current V8 instance.
|
||||
|
||||
```js
|
||||
const vm = require('vm');
|
||||
const vm = require('node:vm');
|
||||
// Measure the memory used by the main context.
|
||||
vm.measureMemory({ mode: 'summary' })
|
||||
// This is the same as vm.measureMemory()
|
||||
@ -1190,7 +1190,7 @@ The following example compiles and executes different scripts using a single
|
||||
[contextified][] object:
|
||||
|
||||
```js
|
||||
const vm = require('vm');
|
||||
const vm = require('node:vm');
|
||||
|
||||
const contextObject = { globalVar: 1 };
|
||||
vm.createContext(contextObject);
|
||||
@ -1302,7 +1302,7 @@ The following example compiles and executes code that increments a global
|
||||
variable and sets a new one. These globals are contained in the `contextObject`.
|
||||
|
||||
```js
|
||||
const vm = require('vm');
|
||||
const vm = require('node:vm');
|
||||
|
||||
const contextObject = {
|
||||
animal: 'cat',
|
||||
@ -1388,7 +1388,7 @@ the JavaScript [`eval()`][] function to run the same code:
|
||||
<!-- eslint-disable prefer-const -->
|
||||
|
||||
```js
|
||||
const vm = require('vm');
|
||||
const vm = require('node:vm');
|
||||
let localVar = 'initial value';
|
||||
|
||||
const vmResult = vm.runInThisContext('localVar = "vm";');
|
||||
@ -1412,17 +1412,17 @@ When using either [`script.runInThisContext()`][] or
|
||||
[`vm.runInThisContext()`][], the code is executed within the current V8 global
|
||||
context. The code passed to this VM context will have its own isolated scope.
|
||||
|
||||
In order to run a simple web server using the `http` module the code passed to
|
||||
the context must either call `require('http')` on its own, or have a reference
|
||||
to the `http` module passed to it. For instance:
|
||||
In order to run a simple web server using the `node:http` module the code passed
|
||||
to the context must either call `require('node:http')` on its own, or have a
|
||||
reference to the `node:http` module passed to it. For instance:
|
||||
|
||||
```js
|
||||
'use strict';
|
||||
const vm = require('vm');
|
||||
const vm = require('node:vm');
|
||||
|
||||
const code = `
|
||||
((require) => {
|
||||
const http = require('http');
|
||||
const http = require('node:http');
|
||||
|
||||
http.createServer((request, response) => {
|
||||
response.writeHead(200, { 'Content-Type': 'text/plain' });
|
||||
@ -1451,9 +1451,9 @@ According to the [V8 Embedder's Guide][]:
|
||||
When the method `vm.createContext()` is called, the `contextObject` argument
|
||||
(or a newly-created object if `contextObject` is `undefined`) is associated
|
||||
internally with a new instance of a V8 Context. This V8 Context provides the
|
||||
`code` run using the `vm` module's methods with an isolated global environment
|
||||
within which it can operate. The process of creating the V8 Context and
|
||||
associating it with the `contextObject` is what this document refers to as
|
||||
`code` run using the `node:vm` module's methods with an isolated global
|
||||
environment within which it can operate. The process of creating the V8 Context
|
||||
and associating it with the `contextObject` is what this document refers to as
|
||||
"contextifying" the object.
|
||||
|
||||
## Timeout interactions with asynchronous tasks and Promises
|
||||
@ -1469,7 +1469,7 @@ timeout of 5 milliseconds schedules an infinite loop to run after a promise
|
||||
resolves. The scheduled loop is never interrupted by the timeout:
|
||||
|
||||
```js
|
||||
const vm = require('vm');
|
||||
const vm = require('node:vm');
|
||||
|
||||
function loop() {
|
||||
console.log('entering loop');
|
||||
@ -1489,7 +1489,7 @@ This can be addressed by passing `microtaskMode: 'afterEvaluate'` to the code
|
||||
that creates the `Context`:
|
||||
|
||||
```js
|
||||
const vm = require('vm');
|
||||
const vm = require('node:vm');
|
||||
|
||||
function loop() {
|
||||
while (1) console.log(Date.now());
|
||||
|
||||
@ -11,9 +11,9 @@ specification. WASI gives sandboxed WebAssembly applications access to the
|
||||
underlying operating system via a collection of POSIX-like functions.
|
||||
|
||||
```mjs
|
||||
import { readFile } from 'fs/promises';
|
||||
import { readFile } from 'node:fs/promises';
|
||||
import { WASI } from 'wasi';
|
||||
import { argv, env } from 'process';
|
||||
import { argv, env } from 'node:process';
|
||||
|
||||
const wasi = new WASI({
|
||||
args: argv,
|
||||
@ -37,10 +37,10 @@ wasi.start(instance);
|
||||
|
||||
```cjs
|
||||
'use strict';
|
||||
const { readFile } = require('fs/promises');
|
||||
const { readFile } = require('node:fs/promises');
|
||||
const { WASI } = require('wasi');
|
||||
const { argv, env } = require('process');
|
||||
const { join } = require('path');
|
||||
const { argv, env } = require('node:process');
|
||||
const { join } = require('node:path');
|
||||
|
||||
const wasi = new WASI({
|
||||
args: argv,
|
||||
|
||||
@ -6,10 +6,10 @@
|
||||
|
||||
Node.js provides an implementation of the standard [Web Crypto API][].
|
||||
|
||||
Use `require('crypto').webcrypto` to access this module.
|
||||
Use `require('node:crypto').webcrypto` to access this module.
|
||||
|
||||
```js
|
||||
const { subtle } = require('crypto').webcrypto;
|
||||
const { subtle } = require('node:crypto').webcrypto;
|
||||
|
||||
(async function() {
|
||||
|
||||
@ -39,7 +39,7 @@ or asymmetric key pairs (public key and private key).
|
||||
#### AES keys
|
||||
|
||||
```js
|
||||
const { subtle } = require('crypto').webcrypto;
|
||||
const { subtle } = require('node:crypto').webcrypto;
|
||||
|
||||
async function generateAesKey(length = 256) {
|
||||
const key = await subtle.generateKey({
|
||||
@ -54,7 +54,7 @@ async function generateAesKey(length = 256) {
|
||||
#### ECDSA key pairs
|
||||
|
||||
```js
|
||||
const { subtle } = require('crypto').webcrypto;
|
||||
const { subtle } = require('node:crypto').webcrypto;
|
||||
|
||||
async function generateEcKey(namedCurve = 'P-521') {
|
||||
const {
|
||||
@ -72,7 +72,7 @@ async function generateEcKey(namedCurve = 'P-521') {
|
||||
#### ED25519/ED448/X25519/X448 key pairs
|
||||
|
||||
```js
|
||||
const { subtle } = require('crypto').webcrypto;
|
||||
const { subtle } = require('node:crypto').webcrypto;
|
||||
|
||||
async function generateEd25519Key() {
|
||||
return subtle.generateKey({
|
||||
@ -92,7 +92,7 @@ async function generateX25519Key() {
|
||||
#### HMAC keys
|
||||
|
||||
```js
|
||||
const { subtle } = require('crypto').webcrypto;
|
||||
const { subtle } = require('node:crypto').webcrypto;
|
||||
|
||||
async function generateHmacKey(hash = 'SHA-256') {
|
||||
const key = await subtle.generateKey({
|
||||
@ -107,7 +107,7 @@ async function generateHmacKey(hash = 'SHA-256') {
|
||||
#### RSA key pairs
|
||||
|
||||
```js
|
||||
const { subtle } = require('crypto').webcrypto;
|
||||
const { subtle } = require('node:crypto').webcrypto;
|
||||
const publicExponent = new Uint8Array([1, 0, 1]);
|
||||
|
||||
async function generateRsaKey(modulusLength = 2048, hash = 'SHA-256') {
|
||||
@ -128,7 +128,7 @@ async function generateRsaKey(modulusLength = 2048, hash = 'SHA-256') {
|
||||
### Encryption and decryption
|
||||
|
||||
```js
|
||||
const crypto = require('crypto').webcrypto;
|
||||
const crypto = require('node:crypto').webcrypto;
|
||||
|
||||
async function aesEncrypt(plaintext) {
|
||||
const ec = new TextEncoder();
|
||||
@ -161,7 +161,7 @@ async function aesDecrypt(ciphertext, key, iv) {
|
||||
### Exporting and importing keys
|
||||
|
||||
```js
|
||||
const { subtle } = require('crypto').webcrypto;
|
||||
const { subtle } = require('node:crypto').webcrypto;
|
||||
|
||||
async function generateAndExportHmacKey(format = 'jwk', hash = 'SHA-512') {
|
||||
const key = await subtle.generateKey({
|
||||
@ -185,7 +185,7 @@ async function importHmacKey(keyData, format = 'jwk', hash = 'SHA-512') {
|
||||
### Wrapping and unwrapping keys
|
||||
|
||||
```js
|
||||
const { subtle } = require('crypto').webcrypto;
|
||||
const { subtle } = require('node:crypto').webcrypto;
|
||||
|
||||
async function generateAndWrapHmacKey(format = 'jwk', hash = 'SHA-512') {
|
||||
const [
|
||||
@ -228,7 +228,7 @@ async function unwrapHmacKey(
|
||||
### Sign and verify
|
||||
|
||||
```js
|
||||
const { subtle } = require('crypto').webcrypto;
|
||||
const { subtle } = require('node:crypto').webcrypto;
|
||||
|
||||
async function sign(key, data) {
|
||||
const ec = new TextEncoder();
|
||||
@ -252,7 +252,7 @@ async function verify(key, signature, data) {
|
||||
### Deriving bits and keys
|
||||
|
||||
```js
|
||||
const { subtle } = require('crypto').webcrypto;
|
||||
const { subtle } = require('node:crypto').webcrypto;
|
||||
|
||||
async function pbkdf2(pass, salt, iterations = 1000, length = 256) {
|
||||
const ec = new TextEncoder();
|
||||
@ -295,7 +295,7 @@ async function pbkdf2Key(pass, salt, iterations = 1000, length = 256) {
|
||||
### Digest
|
||||
|
||||
```js
|
||||
const { subtle } = require('crypto').webcrypto;
|
||||
const { subtle } = require('node:crypto').webcrypto;
|
||||
|
||||
async function digest(data, algorithm = 'SHA-512') {
|
||||
const ec = new TextEncoder();
|
||||
@ -338,8 +338,9 @@ implementation and the APIs supported for each:
|
||||
added: v15.0.0
|
||||
-->
|
||||
|
||||
Calling `require('crypto').webcrypto` returns an instance of the `Crypto` class.
|
||||
`Crypto` is a singleton that provides access to the remainder of the crypto API.
|
||||
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`
|
||||
|
||||
|
||||
@ -62,15 +62,15 @@ for await (const value of stream)
|
||||
```cjs
|
||||
const {
|
||||
ReadableStream
|
||||
} = require('stream/web');
|
||||
} = require('node:stream/web');
|
||||
|
||||
const {
|
||||
setInterval: every
|
||||
} = require('timers/promises');
|
||||
} = require('node:timers/promises');
|
||||
|
||||
const {
|
||||
performance
|
||||
} = require('perf_hooks');
|
||||
} = require('node:perf_hooks');
|
||||
|
||||
const SECOND = 1000;
|
||||
|
||||
@ -179,7 +179,7 @@ console.log(await reader.read());
|
||||
```
|
||||
|
||||
```cjs
|
||||
const { ReadableStream } = require('stream/web');
|
||||
const { ReadableStream } = require('node:stream/web');
|
||||
|
||||
const stream = new ReadableStream();
|
||||
|
||||
@ -251,7 +251,7 @@ for await (const chunk of transformedStream)
|
||||
const {
|
||||
ReadableStream,
|
||||
TransformStream,
|
||||
} = require('stream/web');
|
||||
} = require('node:stream/web');
|
||||
|
||||
const stream = new ReadableStream({
|
||||
start(controller) {
|
||||
@ -342,7 +342,7 @@ The {ReadableStream} object supports the async iterator protocol using
|
||||
`for await` syntax.
|
||||
|
||||
```mjs
|
||||
import { Buffer } from 'buffer';
|
||||
import { Buffer } from 'node:buffer';
|
||||
|
||||
const stream = new ReadableStream(getSomeSource());
|
||||
|
||||
@ -577,7 +577,7 @@ available.
|
||||
|
||||
Do not pass a pooled {Buffer} object instance in to this method.
|
||||
Pooled `Buffer` objects are created using `Buffer.allocUnsafe()`,
|
||||
or `Buffer.from()`, or are often returned by various `fs` module
|
||||
or `Buffer.from()`, or are often returned by various `node:fs` module
|
||||
callbacks. These types of `Buffer`s use a shared underlying
|
||||
{ArrayBuffer} object that contains all of the data from all of
|
||||
the pooled `Buffer` instances. When a `Buffer`, {TypedArray},
|
||||
@ -1445,7 +1445,7 @@ const {
|
||||
buffer,
|
||||
json,
|
||||
text,
|
||||
} = require('stream/consumers');
|
||||
} = require('node:stream/consumers');
|
||||
```
|
||||
|
||||
#### `streamConsumers.arrayBuffer(stream)`
|
||||
|
||||
@ -6,11 +6,11 @@
|
||||
|
||||
<!-- source_link=lib/worker_threads.js -->
|
||||
|
||||
The `worker_threads` module enables the use of threads that execute JavaScript
|
||||
in parallel. To access it:
|
||||
The `node:worker_threads` module enables the use of threads that execute
|
||||
JavaScript in parallel. To access it:
|
||||
|
||||
```js
|
||||
const worker = require('worker_threads');
|
||||
const worker = require('node:worker_threads');
|
||||
```
|
||||
|
||||
Workers (threads) are useful for performing CPU-intensive JavaScript operations.
|
||||
@ -24,7 +24,7 @@ instances.
|
||||
```js
|
||||
const {
|
||||
Worker, isMainThread, parentPort, workerData
|
||||
} = require('worker_threads');
|
||||
} = require('node:worker_threads');
|
||||
|
||||
if (isMainThread) {
|
||||
module.exports = function parseJSAsync(script) {
|
||||
@ -88,7 +88,7 @@ const {
|
||||
isMainThread,
|
||||
setEnvironmentData,
|
||||
getEnvironmentData,
|
||||
} = require('worker_threads');
|
||||
} = require('node:worker_threads');
|
||||
|
||||
if (isMainThread) {
|
||||
setEnvironmentData('Hello', 'World!');
|
||||
@ -109,7 +109,7 @@ added: v10.5.0
|
||||
Is `true` if this code is not running inside of a [`Worker`][] thread.
|
||||
|
||||
```js
|
||||
const { Worker, isMainThread } = require('worker_threads');
|
||||
const { Worker, isMainThread } = require('node:worker_threads');
|
||||
|
||||
if (isMainThread) {
|
||||
// This re-loads the current file inside a Worker instance.
|
||||
@ -139,7 +139,7 @@ For example, Node.js marks the `ArrayBuffer`s it uses for its
|
||||
This operation cannot be undone.
|
||||
|
||||
```js
|
||||
const { MessageChannel, markAsUntransferable } = require('worker_threads');
|
||||
const { MessageChannel, markAsUntransferable } = require('node:worker_threads');
|
||||
|
||||
const pooledBuffer = new ArrayBuffer(8);
|
||||
const typedArray1 = new Uint8Array(pooledBuffer);
|
||||
@ -202,7 +202,7 @@ using `worker.postMessage()` are available in this thread using
|
||||
`parentPort.on('message')`.
|
||||
|
||||
```js
|
||||
const { Worker, isMainThread, parentPort } = require('worker_threads');
|
||||
const { Worker, isMainThread, parentPort } = require('node:worker_threads');
|
||||
|
||||
if (isMainThread) {
|
||||
const worker = new Worker(__filename);
|
||||
@ -238,7 +238,7 @@ that contains the message payload, corresponding to the oldest message in the
|
||||
`MessagePort`’s queue.
|
||||
|
||||
```js
|
||||
const { MessageChannel, receiveMessageOnPort } = require('worker_threads');
|
||||
const { MessageChannel, receiveMessageOnPort } = require('node:worker_threads');
|
||||
const { port1, port2 } = new MessageChannel();
|
||||
port1.postMessage({ hello: 'world' });
|
||||
|
||||
@ -284,7 +284,7 @@ constructor, to indicate that the current thread and the Worker thread should
|
||||
share read and write access to the same set of environment variables.
|
||||
|
||||
```js
|
||||
const { Worker, SHARE_ENV } = require('worker_threads');
|
||||
const { Worker, SHARE_ENV } = require('node:worker_threads');
|
||||
new Worker('process.env.SET_IN_WORKER = "foo"', { eval: true, env: SHARE_ENV })
|
||||
.on('exit', () => {
|
||||
console.log(process.env.SET_IN_WORKER); // Prints 'foo'.
|
||||
@ -338,7 +338,7 @@ The data is cloned as if using [`postMessage()`][`port.postMessage()`],
|
||||
according to the [HTML structured clone algorithm][].
|
||||
|
||||
```js
|
||||
const { Worker, isMainThread, workerData } = require('worker_threads');
|
||||
const { Worker, isMainThread, workerData } = require('node:worker_threads');
|
||||
|
||||
if (isMainThread) {
|
||||
const worker = new Worker(__filename, { workerData: 'Hello, world!' });
|
||||
@ -367,7 +367,7 @@ const {
|
||||
isMainThread,
|
||||
BroadcastChannel,
|
||||
Worker
|
||||
} = require('worker_threads');
|
||||
} = require('node:worker_threads');
|
||||
|
||||
const bc = new BroadcastChannel('hello');
|
||||
|
||||
@ -462,7 +462,7 @@ yields an object with `port1` and `port2` properties, which refer to linked
|
||||
[`MessagePort`][] instances.
|
||||
|
||||
```js
|
||||
const { MessageChannel } = require('worker_threads');
|
||||
const { MessageChannel } = require('node:worker_threads');
|
||||
|
||||
const { port1, port2 } = new MessageChannel();
|
||||
port1.on('message', (message) => console.log('received', message));
|
||||
@ -501,7 +501,7 @@ The `'close'` event is emitted once either side of the channel has been
|
||||
disconnected.
|
||||
|
||||
```js
|
||||
const { MessageChannel } = require('worker_threads');
|
||||
const { MessageChannel } = require('node:worker_threads');
|
||||
const { port1, port2 } = new MessageChannel();
|
||||
|
||||
// Prints:
|
||||
@ -618,7 +618,7 @@ In particular, the significant differences to `JSON` are:
|
||||
* {X509Certificate}s.
|
||||
|
||||
```js
|
||||
const { MessageChannel } = require('worker_threads');
|
||||
const { MessageChannel } = require('node:worker_threads');
|
||||
const { port1, port2 } = new MessageChannel();
|
||||
|
||||
port1.on('message', (message) => console.log(message));
|
||||
@ -643,7 +643,7 @@ from either thread. They cannot be listed in `transferList`.
|
||||
`transferList`; in that case, the underlying memory is copied rather than moved.
|
||||
|
||||
```js
|
||||
const { MessageChannel } = require('worker_threads');
|
||||
const { MessageChannel } = require('node:worker_threads');
|
||||
const { port1, port2 } = new MessageChannel();
|
||||
|
||||
port1.on('message', (message) => console.log(message));
|
||||
@ -670,7 +670,7 @@ The message object is cloned immediately, and can be modified after
|
||||
posting without having side effects.
|
||||
|
||||
For more information on the serialization and deserialization mechanisms
|
||||
behind this API, see the [serialization API of the `v8` module][v8.serdes].
|
||||
behind this API, see the [serialization API of the `node:v8` module][v8.serdes].
|
||||
|
||||
#### Considerations when transferring TypedArrays and Buffers
|
||||
|
||||
@ -822,8 +822,8 @@ Notable differences inside a Worker environment are:
|
||||
|
||||
* The [`process.stdin`][], [`process.stdout`][] and [`process.stderr`][]
|
||||
may be redirected by the parent thread.
|
||||
* The [`require('worker_threads').isMainThread`][] property is set to `false`.
|
||||
* The [`require('worker_threads').parentPort`][] message port is available.
|
||||
* The [`require('node:worker_threads').isMainThread`][] property is set to `false`.
|
||||
* The [`require('node:worker_threads').parentPort`][] message port is available.
|
||||
* [`process.exit()`][] does not stop the whole program, just the single thread,
|
||||
and [`process.abort()`][] is not available.
|
||||
* [`process.chdir()`][] and `process` methods that set group or user ids
|
||||
@ -844,11 +844,11 @@ Notable differences inside a Worker environment are:
|
||||
|
||||
Creating `Worker` instances inside of other `Worker`s is possible.
|
||||
|
||||
Like [Web Workers][] and the [`cluster` module][], two-way communication can be
|
||||
achieved through inter-thread message passing. Internally, a `Worker` has a
|
||||
built-in pair of [`MessagePort`][]s that are already associated with each other
|
||||
when the `Worker` is created. While the `MessagePort` object on the parent side
|
||||
is not directly exposed, its functionalities are exposed through
|
||||
Like [Web Workers][] and the [`node:cluster` module][], two-way communication
|
||||
can be achieved through inter-thread message passing. Internally, a `Worker` has
|
||||
a built-in pair of [`MessagePort`][]s that are already associated with each
|
||||
other when the `Worker` is created. While the `MessagePort` object on the parent
|
||||
side is not directly exposed, its functionalities are exposed through
|
||||
[`worker.postMessage()`][] and the [`worker.on('message')`][] event
|
||||
on the `Worker` object for the parent thread.
|
||||
|
||||
@ -863,10 +863,10 @@ and what kind of JavaScript values can be successfully transported through
|
||||
the thread barrier.
|
||||
|
||||
```js
|
||||
const assert = require('assert');
|
||||
const assert = require('node:assert');
|
||||
const {
|
||||
Worker, MessageChannel, MessagePort, isMainThread, parentPort
|
||||
} = require('worker_threads');
|
||||
} = require('node:worker_threads');
|
||||
if (isMainThread) {
|
||||
const worker = new Worker(__filename);
|
||||
const subChannel = new MessageChannel();
|
||||
@ -957,7 +957,7 @@ changes:
|
||||
* `stderr` {boolean} If this is set to `true`, then `worker.stderr` is
|
||||
not automatically piped through to `process.stderr` in the parent.
|
||||
* `workerData` {any} Any JavaScript value that is cloned and made
|
||||
available as [`require('worker_threads').workerData`][]. The cloning
|
||||
available as [`require('node:worker_threads').workerData`][]. The cloning
|
||||
occurs as described in the [HTML structured clone algorithm][], and an error
|
||||
is thrown if the object cannot be cloned (e.g. because it contains
|
||||
`function`s).
|
||||
@ -1019,7 +1019,7 @@ added: v10.5.0
|
||||
* `value` {any} The transmitted value
|
||||
|
||||
The `'message'` event is emitted when the worker thread has invoked
|
||||
[`require('worker_threads').parentPort.postMessage()`][].
|
||||
[`require('node:worker_threads').parentPort.postMessage()`][].
|
||||
See the [`port.on('message')`][] event for more details.
|
||||
|
||||
All messages sent from the worker thread are emitted before the
|
||||
@ -1107,7 +1107,7 @@ lifetime never accumulates any `idle` time, but is still be able to process
|
||||
messages.
|
||||
|
||||
```js
|
||||
const { Worker, isMainThread, parentPort } = require('worker_threads');
|
||||
const { Worker, isMainThread, parentPort } = require('node:worker_threads');
|
||||
|
||||
if (isMainThread) {
|
||||
const worker = new Worker(__filename);
|
||||
@ -1141,7 +1141,7 @@ added: v10.5.0
|
||||
* `transferList` {Object\[]}
|
||||
|
||||
Send a message to the worker that is received via
|
||||
[`require('worker_threads').parentPort.on('message')`][].
|
||||
[`require('node:worker_threads').parentPort.on('message')`][].
|
||||
See [`port.postMessage()`][] for more details.
|
||||
|
||||
### `worker.ref()`
|
||||
@ -1241,7 +1241,7 @@ added: v10.5.0
|
||||
* {integer}
|
||||
|
||||
An integer identifier for the referenced thread. Inside the worker thread,
|
||||
it is available as [`require('worker_threads').threadId`][].
|
||||
it is available as [`require('node:worker_threads').threadId`][].
|
||||
This value is unique for each `Worker` instance inside a single process.
|
||||
|
||||
### `worker.unref()`
|
||||
@ -1286,7 +1286,7 @@ if (isMainThread) {
|
||||
const {
|
||||
Worker,
|
||||
isMainThread,
|
||||
} = require('worker_threads');
|
||||
} = require('node:worker_threads');
|
||||
|
||||
if (isMainThread) {
|
||||
new Worker(__filename);
|
||||
@ -1330,11 +1330,11 @@ thread spawned will spawn another until the application crashes.
|
||||
[`WebAssembly.Module`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/Module
|
||||
[`Worker constructor options`]: #new-workerfilename-options
|
||||
[`Worker`]: #class-worker
|
||||
[`cluster` module]: cluster.md
|
||||
[`data:` URL]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URIs
|
||||
[`fs.close()`]: fs.md#fsclosefd-callback
|
||||
[`fs.open()`]: fs.md#fsopenpath-flags-mode-callback
|
||||
[`markAsUntransferable()`]: #workermarkasuntransferableobject
|
||||
[`node:cluster` module]: cluster.md
|
||||
[`perf_hooks.performance`]: perf_hooks.md#perf_hooksperformance
|
||||
[`perf_hooks` `eventLoopUtilization()`]: perf_hooks.md#performanceeventlooputilizationutilization1-utilization2
|
||||
[`port.on('message')`]: #event-message
|
||||
@ -1349,12 +1349,12 @@ thread spawned will spawn another until the application crashes.
|
||||
[`process.stdin`]: process.md#processstdin
|
||||
[`process.stdout`]: process.md#processstdout
|
||||
[`process.title`]: process.md#processtitle
|
||||
[`require('worker_threads').isMainThread`]: #workerismainthread
|
||||
[`require('worker_threads').parentPort.on('message')`]: #event-message
|
||||
[`require('worker_threads').parentPort.postMessage()`]: #workerpostmessagevalue-transferlist
|
||||
[`require('worker_threads').parentPort`]: #workerparentport
|
||||
[`require('worker_threads').threadId`]: #workerthreadid
|
||||
[`require('worker_threads').workerData`]: #workerworkerdata
|
||||
[`require('node:worker_threads').isMainThread`]: #workerismainthread
|
||||
[`require('node:worker_threads').parentPort.on('message')`]: #event-message
|
||||
[`require('node:worker_threads').parentPort.postMessage()`]: #workerpostmessagevalue-transferlist
|
||||
[`require('node:worker_threads').parentPort`]: #workerparentport
|
||||
[`require('node:worker_threads').threadId`]: #workerthreadid
|
||||
[`require('node:worker_threads').workerData`]: #workerworkerdata
|
||||
[`trace_events`]: tracing.md
|
||||
[`v8.getHeapSnapshot()`]: v8.md#v8getheapsnapshot
|
||||
[`vm`]: vm.md
|
||||
|
||||
@ -6,13 +6,13 @@
|
||||
|
||||
<!-- source_link=lib/zlib.js -->
|
||||
|
||||
The `zlib` module provides compression functionality implemented using Gzip,
|
||||
Deflate/Inflate, and Brotli.
|
||||
The `node:zlib` module provides compression functionality implemented using
|
||||
Gzip, Deflate/Inflate, and Brotli.
|
||||
|
||||
To access it:
|
||||
|
||||
```js
|
||||
const zlib = require('zlib');
|
||||
const zlib = require('node:zlib');
|
||||
```
|
||||
|
||||
Compression and decompression are built around the Node.js [Streams API][].
|
||||
@ -22,12 +22,12 @@ piping the source stream through a `zlib` `Transform` stream into a destination
|
||||
stream:
|
||||
|
||||
```js
|
||||
const { createGzip } = require('zlib');
|
||||
const { pipeline } = require('stream');
|
||||
const { createGzip } = require('node:zlib');
|
||||
const { pipeline } = require('node:stream');
|
||||
const {
|
||||
createReadStream,
|
||||
createWriteStream
|
||||
} = require('fs');
|
||||
} = require('node:fs');
|
||||
|
||||
const gzip = createGzip();
|
||||
const source = createReadStream('input.txt');
|
||||
@ -42,7 +42,7 @@ pipeline(source, gzip, destination, (err) => {
|
||||
|
||||
// Or, Promisified
|
||||
|
||||
const { promisify } = require('util');
|
||||
const { promisify } = require('node:util');
|
||||
const pipe = promisify(pipeline);
|
||||
|
||||
async function do_gzip(input, output) {
|
||||
@ -62,7 +62,7 @@ do_gzip('input.txt', 'input.txt.gz')
|
||||
It is also possible to compress or decompress data in a single step:
|
||||
|
||||
```js
|
||||
const { deflate, unzip } = require('zlib');
|
||||
const { deflate, unzip } = require('node:zlib');
|
||||
|
||||
const input = '.................................';
|
||||
deflate(input, (err, buffer) => {
|
||||
@ -84,7 +84,7 @@ unzip(buffer, (err, buffer) => {
|
||||
|
||||
// Or, Promisified
|
||||
|
||||
const { promisify } = require('util');
|
||||
const { promisify } = require('node:util');
|
||||
const do_unzip = promisify(unzip);
|
||||
|
||||
do_unzip(buffer)
|
||||
@ -105,7 +105,7 @@ Creating and using a large number of zlib objects simultaneously can cause
|
||||
significant memory fragmentation.
|
||||
|
||||
```js
|
||||
const zlib = require('zlib');
|
||||
const zlib = require('node:zlib');
|
||||
|
||||
const payload = Buffer.from('This is some data');
|
||||
|
||||
@ -124,7 +124,7 @@ operations be cached to avoid duplication of effort.
|
||||
|
||||
## Compressing HTTP requests and responses
|
||||
|
||||
The `zlib` module can be used to implement support for the `gzip`, `deflate`
|
||||
The `node:zlib` module can be used to implement support for the `gzip`, `deflate`
|
||||
and `br` content-encoding mechanisms defined by
|
||||
[HTTP](https://tools.ietf.org/html/rfc7230#section-4.2).
|
||||
|
||||
@ -140,10 +140,10 @@ tradeoffs involved in `zlib` usage.
|
||||
|
||||
```js
|
||||
// Client request example
|
||||
const zlib = require('zlib');
|
||||
const http = require('http');
|
||||
const fs = require('fs');
|
||||
const { pipeline } = require('stream');
|
||||
const zlib = require('node:zlib');
|
||||
const http = require('node:http');
|
||||
const fs = require('node:fs');
|
||||
const { pipeline } = require('node:stream');
|
||||
|
||||
const request = http.get({ host: 'example.com',
|
||||
path: '/',
|
||||
@ -181,10 +181,10 @@ request.on('response', (response) => {
|
||||
// server example
|
||||
// Running a gzip operation on every request is quite expensive.
|
||||
// It would be much more efficient to cache the compressed buffer.
|
||||
const zlib = require('zlib');
|
||||
const http = require('http');
|
||||
const fs = require('fs');
|
||||
const { pipeline } = require('stream');
|
||||
const zlib = require('node:zlib');
|
||||
const http = require('node:http');
|
||||
const fs = require('node:fs');
|
||||
const { pipeline } = require('node:stream');
|
||||
|
||||
http.createServer((request, response) => {
|
||||
const raw = fs.createReadStream('index.html');
|
||||
@ -319,9 +319,9 @@ In the following example, `flush()` is used to write a compressed partial
|
||||
HTTP response to the client:
|
||||
|
||||
```js
|
||||
const zlib = require('zlib');
|
||||
const http = require('http');
|
||||
const { pipeline } = require('stream');
|
||||
const zlib = require('node:zlib');
|
||||
const http = require('node:http');
|
||||
const { pipeline } = require('node:stream');
|
||||
|
||||
http.createServer((request, response) => {
|
||||
// For the sake of simplicity, the Accept-Encoding checks are omitted.
|
||||
@ -365,14 +365,14 @@ added: v0.5.8
|
||||
### zlib constants
|
||||
|
||||
All of the constants defined in `zlib.h` are also defined on
|
||||
`require('zlib').constants`. In the normal course of operations, it will not be
|
||||
necessary to use these constants. They are documented so that their presence is
|
||||
not surprising. This section is taken almost directly from the
|
||||
`require('node:zlib').constants`. In the normal course of operations, it will
|
||||
not be necessary to use these constants. They are documented so that their
|
||||
presence is not surprising. This section is taken almost directly from the
|
||||
[zlib documentation][].
|
||||
|
||||
Previously, the constants were available directly from `require('zlib')`, for
|
||||
instance `zlib.Z_NO_FLUSH`. Accessing the constants directly from the module is
|
||||
currently still possible but is deprecated.
|
||||
Previously, the constants were available directly from `require('node:zlib')`,
|
||||
for instance `zlib.Z_NO_FLUSH`. Accessing the constants directly from the module
|
||||
is currently still possible but is deprecated.
|
||||
|
||||
Allowed flush values.
|
||||
|
||||
@ -678,11 +678,11 @@ changes:
|
||||
description: This class was renamed from `Zlib` to `ZlibBase`.
|
||||
-->
|
||||
|
||||
Not exported by the `zlib` module. It is documented here because it is the base
|
||||
class of the compressor/decompressor classes.
|
||||
Not exported by the `node:zlib` module. It is documented here because it is the
|
||||
base class of the compressor/decompressor classes.
|
||||
|
||||
This class inherits from [`stream.Transform`][], allowing `zlib` objects to be
|
||||
used in pipes and similar stream operations.
|
||||
This class inherits from [`stream.Transform`][], allowing `node:zlib` objects to
|
||||
be used in pipes and similar stream operations.
|
||||
|
||||
### `zlib.bytesRead`
|
||||
|
||||
|
||||
@ -254,7 +254,7 @@ run `node benchmark/compare.js`.
|
||||
As an example on how to check for a possible performance improvement, the
|
||||
[#5134](https://github.com/nodejs/node/pull/5134) pull request will be used as
|
||||
an example. This pull request _claims_ to improve the performance of the
|
||||
`string_decoder` module.
|
||||
`node:string_decoder` module.
|
||||
|
||||
First build two versions of Node.js, one from the master branch (here called
|
||||
`./node-master`) and another with the pull request applied (here called
|
||||
@ -479,7 +479,7 @@ the code inside the `main` function if it's more than just declaration.
|
||||
```js
|
||||
'use strict';
|
||||
const common = require('../common.js');
|
||||
const { SlowBuffer } = require('buffer');
|
||||
const { SlowBuffer } = require('node:buffer');
|
||||
|
||||
const configs = {
|
||||
// Number of operations, specified here so they show up in the report.
|
||||
@ -539,7 +539,7 @@ const bench = common.createBenchmark(main, {
|
||||
});
|
||||
|
||||
function main(conf) {
|
||||
const http = require('http');
|
||||
const http = require('node:http');
|
||||
const len = conf.kb * 1024;
|
||||
const chunk = Buffer.alloc(len, 'x');
|
||||
const server = http.createServer((req, res) => {
|
||||
|
||||
@ -37,8 +37,8 @@ const fixtures = require('../common/fixtures'); // 3
|
||||
// This test ensures that the http-parser can handle UTF-8 characters // 5
|
||||
// in the http header. // 6
|
||||
|
||||
const assert = require('assert'); // 8
|
||||
const http = require('http'); // 9
|
||||
const assert = require('node:assert'); // 8
|
||||
const http = require('node:http'); // 9
|
||||
|
||||
const server = http.createServer(common.mustCall((req, res) => { // 11
|
||||
res.end('ok'); // 12
|
||||
@ -95,13 +95,13 @@ designed to test.
|
||||
### **Lines 8-9**
|
||||
|
||||
```js
|
||||
const assert = require('assert');
|
||||
const http = require('http');
|
||||
const assert = require('node:assert');
|
||||
const http = require('node:http');
|
||||
```
|
||||
|
||||
The test checks functionality in the `http` module.
|
||||
The test checks functionality in the `node:http` module.
|
||||
|
||||
Most tests use the `assert` module to confirm expectations of the test.
|
||||
Most tests use the `node:assert` module to confirm expectations of the test.
|
||||
|
||||
The require statements are sorted in
|
||||
[ASCII][] order (digits, upper
|
||||
@ -173,8 +173,8 @@ explain this with a real test from the test suite.
|
||||
```js
|
||||
'use strict';
|
||||
require('../common');
|
||||
const assert = require('assert');
|
||||
const http = require('http');
|
||||
const assert = require('node:assert');
|
||||
const http = require('node:http');
|
||||
|
||||
let request = 0;
|
||||
let listening = 0;
|
||||
@ -207,7 +207,7 @@ This test could be greatly simplified by using `common.mustCall` like this:
|
||||
```js
|
||||
'use strict';
|
||||
const common = require('../common');
|
||||
const http = require('http');
|
||||
const http = require('node:http');
|
||||
|
||||
const server = http.createServer(common.mustCall((req, res) => {
|
||||
res.end();
|
||||
@ -256,8 +256,8 @@ Node.js automatically crashes - and hence, the test fails - in the case of an
|
||||
|
||||
```js
|
||||
const common = require('../common');
|
||||
const assert = require('assert');
|
||||
const fs = require('fs').promises;
|
||||
const assert = require('node:assert');
|
||||
const fs = require('node:fs').promises;
|
||||
|
||||
// Wrap the `onFulfilled` handler in `common.mustCall()`.
|
||||
fs.readFile('test-file').then(
|
||||
@ -280,8 +280,8 @@ A test that would require `internal/freelist` could start like this:
|
||||
// Flags: --expose-internals
|
||||
|
||||
require('../common');
|
||||
const assert = require('assert');
|
||||
const freelist = require('internal/freelist');
|
||||
const assert = require('node:assert');
|
||||
const freelist = require('node:internal/freelist');
|
||||
```
|
||||
|
||||
In specific scenarios it may be useful to get a hold of `primordials` or
|
||||
@ -291,7 +291,8 @@ In specific scenarios it may be useful to get a hold of `primordials` or
|
||||
node --expose-internals -r internal/test/binding lib/fs.js
|
||||
```
|
||||
|
||||
This only works if you preload `internal/test/binding` by command line flag.
|
||||
This only works if you preload `node:internal/test/binding` by command line
|
||||
flag.
|
||||
|
||||
### Assertions
|
||||
|
||||
|
||||
@ -312,12 +312,12 @@ crypto.randomFill(buf, (err, buf) => {
|
||||
For the legacy Node.js crypto API, asynchronous single-call
|
||||
operations use the traditional Node.js callback pattern, as
|
||||
illustrated in the previous `randomFill()` example. In the
|
||||
Web Crypto API (accessible via `require('crypto').webcrypto`),
|
||||
Web Crypto API (accessible via `require('node:crypto').webcrypto`),
|
||||
all asynchronous single-call operations are Promise-based.
|
||||
|
||||
```js
|
||||
// Example Web Crypto API asynchronous single-call operation
|
||||
const { subtle } = require('crypto').webcrypto;
|
||||
const { subtle } = require('node:crypto').webcrypto;
|
||||
|
||||
subtle.generateKeys({ name: 'HMAC', length: 256 }, true, ['sign'])
|
||||
.then((key) => {
|
||||
|
||||
@ -359,7 +359,7 @@ Platform normalized `pwd` command options. Usage example:
|
||||
|
||||
```js
|
||||
const common = require('../common');
|
||||
const { spawn } = require('child_process');
|
||||
const { spawn } = require('node:child_process');
|
||||
|
||||
spawn(...common.pwdCommand, { stdio: ['pipe'] });
|
||||
```
|
||||
|
||||
Loading…
Reference in New Issue
Block a user