From cc398a829be38e8cabee2b27de8ebdcf444e6452 Mon Sep 17 00:00:00 2001 From: Antoine du Hamel Date: Wed, 20 Apr 2022 10:23:41 +0200 Subject: [PATCH] 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 Reviewed-By: Mestery Reviewed-By: Darshan Sen Reviewed-By: Akhil Marsonya Reviewed-By: Rafael Gonzaga Reviewed-By: Mohammed Keyvanzadeh Reviewed-By: Geoffrey Booth Reviewed-By: Stephen Belanger --- doc/api/assert.md | 166 +++---- doc/api/async_context.md | 58 +-- doc/api/async_hooks.md | 76 ++-- doc/api/buffer.md | 412 +++++++++--------- doc/api/child_process.md | 90 ++-- doc/api/cli.md | 6 +- doc/api/cluster.md | 72 +-- doc/api/console.md | 10 +- doc/api/crypto.md | 347 +++++++-------- doc/api/deprecations.md | 57 +-- doc/api/dgram.md | 44 +- doc/api/diagnostics_channel.md | 34 +- doc/api/dns.md | 26 +- doc/api/domain.md | 18 +- doc/api/embedding.md | 4 +- doc/api/errors.md | 68 +-- doc/api/esm.md | 24 +- doc/api/events.md | 44 +- doc/api/fs.md | 202 ++++----- doc/api/globals.md | 6 +- doc/api/http.md | 36 +- doc/api/http2.md | 116 ++--- doc/api/https.md | 26 +- doc/api/index.md | 2 +- doc/api/inspector.md | 15 +- doc/api/intl.md | 38 +- doc/api/module.md | 22 +- doc/api/modules.md | 10 +- doc/api/net.md | 12 +- doc/api/os.md | 4 +- doc/api/packages.md | 4 +- doc/api/path.md | 22 +- doc/api/perf_hooks.md | 40 +- doc/api/policy.md | 2 +- doc/api/process.md | 308 ++++++------- doc/api/querystring.md | 4 +- doc/api/readline.md | 35 +- doc/api/repl.md | 38 +- doc/api/stream.md | 207 ++++----- doc/api/string_decoder.md | 10 +- doc/api/synopsis.md | 2 +- doc/api/timers.md | 18 +- doc/api/tls.md | 32 +- doc/api/tracing.md | 20 +- doc/api/tty.md | 8 +- doc/api/url.md | 53 +-- doc/api/util.md | 94 ++-- doc/api/v8.md | 34 +- doc/api/vm.md | 56 +-- doc/api/wasi.md | 10 +- doc/api/webcrypto.md | 31 +- doc/api/webstreams.md | 16 +- doc/api/worker_threads.md | 78 ++-- doc/api/zlib.md | 64 +-- .../writing-and-running-benchmarks.md | 6 +- doc/contributing/writing-tests.md | 29 +- src/crypto/README.md | 4 +- test/common/README.md | 2 +- 58 files changed, 1640 insertions(+), 1632 deletions(-) diff --git a/doc/api/assert.md b/doc/api/assert.md index 7c9f8684d068ba..bf50fb2daadc6a 100644 --- a/doc/api/assert.md +++ b/doc/api/assert.md @@ -6,7 +6,7 @@ -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(); @@ -540,14 +540,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); @@ -557,7 +557,7 @@ assert.deepEqual('+00000000', false); are evaluated also: ```mjs -import assert from 'assert'; +import assert from 'node:assert'; const obj1 = { a: { @@ -592,7 +592,7 @@ assert.deepEqual(obj1, obj4); ``` ```cjs -const assert = require('assert'); +const assert = require('node:assert'); const obj1 = { a: { @@ -693,7 +693,7 @@ are recursively evaluated also by the following rules. below for further details. ```mjs -import assert from 'assert/strict'; +import assert from 'node:assert/strict'; // This fails because 1 !== '1'. assert.deepStrictEqual({ a: 1 }, { a: '1' }); @@ -785,7 +785,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' }); @@ -901,7 +901,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 ... @@ -914,7 +914,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 ... @@ -965,7 +965,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 () => { @@ -976,7 +976,7 @@ await assert.doesNotReject( ``` ```cjs -const assert = require('assert/strict'); +const assert = require('node:assert/strict'); (async () => { await assert.doesNotReject( @@ -989,7 +989,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(() => { @@ -998,7 +998,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(() => { @@ -1047,7 +1047,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( () => { @@ -1058,7 +1058,7 @@ assert.doesNotThrow( ``` ```cjs -const assert = require('assert/strict'); +const assert = require('node:assert/strict'); assert.doesNotThrow( () => { @@ -1072,7 +1072,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( () => { @@ -1083,7 +1083,7 @@ assert.doesNotThrow( ``` ```cjs -const assert = require('assert/strict'); +const assert = require('node:assert/strict'); assert.doesNotThrow( () => { @@ -1098,7 +1098,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( () => { @@ -1111,7 +1111,7 @@ assert.doesNotThrow( ``` ```cjs -const assert = require('assert/strict'); +const assert = require('node:assert/strict'); assert.doesNotThrow( () => { @@ -1155,7 +1155,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 @@ -1171,7 +1171,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 @@ -1205,7 +1205,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 @@ -1218,7 +1218,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 @@ -1263,7 +1263,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' @@ -1282,7 +1282,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' @@ -1306,7 +1306,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); @@ -1319,7 +1319,7 @@ suppressFrame(); ``` ```cjs -const assert = require('assert/strict'); +const assert = require('node:assert/strict'); function suppressFrame() { assert.fail('a', 'b', undefined, '!==', suppressFrame); @@ -1354,7 +1354,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 @@ -1380,7 +1380,7 @@ let err; ``` ```cjs -const assert = require('assert/strict'); +const assert = require('node:assert/strict'); assert.ifError(null); // OK @@ -1424,7 +1424,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 ... @@ -1437,7 +1437,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 ... @@ -1507,7 +1507,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: { @@ -1540,7 +1540,7 @@ assert.notDeepEqual(obj1, obj4); ``` ```cjs -const assert = require('assert'); +const assert = require('node:assert'); const obj1 = { a: { @@ -1619,14 +1619,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 @@ -1669,7 +1669,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 @@ -1682,7 +1682,7 @@ assert.notEqual(1, '1'); ``` ```cjs -const assert = require('assert'); +const assert = require('node:assert'); assert.notEqual(1, 2); // OK @@ -1718,7 +1718,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 @@ -1733,7 +1733,7 @@ assert.notStrictEqual(1, '1'); ``` ```cjs -const assert = require('assert/strict'); +const assert = require('node:assert/strict'); assert.notStrictEqual(1, 2); // OK @@ -1782,7 +1782,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 @@ -1817,7 +1817,7 @@ assert.ok(0); ``` ```cjs -const assert = require('assert/strict'); +const assert = require('node:assert/strict'); assert.ok(true); // OK @@ -1852,7 +1852,7 @@ assert.ok(0); ``` ```mjs -import assert from 'assert/strict'; +import assert from 'node:assert/strict'; // Using `assert()` works the same: assert(0); @@ -1862,7 +1862,7 @@ assert(0); ``` ```cjs -const assert = require('assert'); +const assert = require('node:assert'); // Using `assert()` works the same: assert(0); @@ -1903,7 +1903,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 () => { @@ -1917,7 +1917,7 @@ await assert.rejects( ``` ```cjs -const assert = require('assert/strict'); +const assert = require('node:assert/strict'); (async () => { await assert.rejects( @@ -1933,7 +1933,7 @@ const assert = require('assert/strict'); ``` ```mjs -import assert from 'assert/strict'; +import assert from 'node:assert/strict'; await assert.rejects( async () => { @@ -1948,7 +1948,7 @@ await assert.rejects( ``` ```cjs -const assert = require('assert/strict'); +const assert = require('node:assert/strict'); (async () => { await assert.rejects( @@ -1965,7 +1965,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')), @@ -1976,7 +1976,7 @@ assert.rejects( ``` ```cjs -const assert = require('assert/strict'); +const assert = require('node:assert/strict'); assert.rejects( Promise.reject(new Error('Wrong value')), @@ -2010,7 +2010,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: @@ -2038,7 +2038,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: @@ -2108,7 +2108,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; @@ -2177,7 +2177,7 @@ assert.throws( ``` ```cjs -const assert = require('assert/strict'); +const assert = require('node:assert/strict'); const err = new TypeError('Wrong value'); err.code = 404; @@ -2248,7 +2248,7 @@ assert.throws( Validate instanceof using constructor: ```mjs -import assert from 'assert/strict'; +import assert from 'node:assert/strict'; assert.throws( () => { @@ -2259,7 +2259,7 @@ assert.throws( ``` ```cjs -const assert = require('assert/strict'); +const assert = require('node:assert/strict'); assert.throws( () => { @@ -2275,7 +2275,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( () => { @@ -2286,7 +2286,7 @@ assert.throws( ``` ```cjs -const assert = require('assert/strict'); +const assert = require('node:assert/strict'); assert.throws( () => { @@ -2302,7 +2302,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( () => { @@ -2323,7 +2323,7 @@ assert.throws( ``` ```cjs -const assert = require('assert/strict'); +const assert = require('node:assert/strict'); assert.throws( () => { @@ -2351,7 +2351,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'); @@ -2387,7 +2387,7 @@ assert.throws(throwingFirst, /Second$/); ``` ```cjs -const assert = require('assert/strict'); +const assert = require('node:assert/strict'); function throwingFirst() { throw new Error('First'); diff --git a/doc/api/async_context.md b/doc/api/async_context.md index b28d39565fecb6..342788bf2f58c9 100644 --- a/doc/api/async_context.md +++ b/doc/api/async_context.md @@ -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(() => { diff --git a/doc/api/async_hooks.md b/doc/api/async_hooks.md index 96db9cc804373c..6e3e4024459c3d 100644 --- a/doc/api/async_hooks.md +++ b/doc/api/async_hooks.md @@ -6,15 +6,15 @@ -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) => { @@ -786,7 +786,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()}`); @@ -796,7 +796,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()}`); @@ -814,7 +814,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()}`); @@ -824,7 +824,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(() => { diff --git a/doc/api/buffer.md b/doc/api/buffer.md index f93db403f99edc..fead0f5652ac34 100644 --- a/doc/api/buffer.md +++ b/doc/api/buffer.md @@ -17,7 +17,7 @@ While the `Buffer` class is available within the global scope, it is still recommended to explicitly reference it via an import or require statement. ```mjs -import { Buffer } from 'buffer'; +import { Buffer } from 'node:buffer'; // Creates a zero-filled Buffer of length 10. const buf1 = Buffer.alloc(10); @@ -50,7 +50,7 @@ const buf7 = Buffer.from('tést', 'latin1'); ``` ```cjs -const { Buffer } = require('buffer'); +const { Buffer } = require('node:buffer'); // Creates a zero-filled Buffer of length 10. const buf1 = Buffer.alloc(10); @@ -102,7 +102,7 @@ specified. If no character encoding is specified, UTF-8 will be used as the default. ```mjs -import { Buffer } from 'buffer'; +import { Buffer } from 'node:buffer'; const buf = Buffer.from('hello world', 'utf8'); @@ -118,7 +118,7 @@ console.log(Buffer.from('fhqwhgads', 'utf16le')); ``` ```cjs -const { Buffer } = require('buffer'); +const { Buffer } = require('node:buffer'); const buf = Buffer.from('hello world', 'utf8'); @@ -197,7 +197,7 @@ The following legacy character encodings are also supported: U+FFFF. In Node.js, these code points are always supported. ```mjs -import { Buffer } from 'buffer'; +import { Buffer } from 'node:buffer'; Buffer.from('1ag123', 'hex'); // Prints , data truncated when first non-hexadecimal value @@ -211,7 +211,7 @@ Buffer.from('1634', 'hex'); ``` ```cjs -const { Buffer } = require('buffer'); +const { Buffer } = require('node:buffer'); Buffer.from('1ag123', 'hex'); // Prints , data truncated when first non-hexadecimal value @@ -263,7 +263,7 @@ There are two ways to create new [`TypedArray`][] instances from a `Buffer`: of the target type. ```mjs -import { Buffer } from 'buffer'; +import { Buffer } from 'node:buffer'; const buf = Buffer.from([1, 2, 3, 4]); const uint32array = new Uint32Array(buf); @@ -274,7 +274,7 @@ console.log(uint32array); ``` ```cjs -const { Buffer } = require('buffer'); +const { Buffer } = require('node:buffer'); const buf = Buffer.from([1, 2, 3, 4]); const uint32array = new Uint32Array(buf); @@ -288,7 +288,7 @@ console.log(uint32array); [`TypedArray`][] that shares its memory with the `Buffer`. ```mjs -import { Buffer } from 'buffer'; +import { Buffer } from 'node:buffer'; const buf = Buffer.from('hello', 'utf16le'); const uint16array = new Uint16Array( @@ -302,7 +302,7 @@ console.log(uint16array); ``` ```cjs -const { Buffer } = require('buffer'); +const { Buffer } = require('node:buffer'); const buf = Buffer.from('hello', 'utf16le'); const uint16array = new Uint16Array( @@ -321,7 +321,7 @@ memory as a [`TypedArray`][] instance by using the `TypedArray` object's behaves like `new Uint8Array()` in this context. ```mjs -import { Buffer } from 'buffer'; +import { Buffer } from 'node:buffer'; const arr = new Uint16Array(2); @@ -348,7 +348,7 @@ console.log(buf2); ``` ```cjs -const { Buffer } = require('buffer'); +const { Buffer } = require('node:buffer'); const arr = new Uint16Array(2); @@ -379,7 +379,7 @@ possible to use only a portion of the underlying [`ArrayBuffer`][] by passing in `byteOffset` and `length` parameters. ```mjs -import { Buffer } from 'buffer'; +import { Buffer } from 'node:buffer'; const arr = new Uint16Array(20); const buf = Buffer.from(arr.buffer, 0, 16); @@ -389,7 +389,7 @@ console.log(buf.length); ``` ```cjs -const { Buffer } = require('buffer'); +const { Buffer } = require('node:buffer'); const arr = new Uint16Array(20); const buf = Buffer.from(arr.buffer, 0, 16); @@ -418,7 +418,7 @@ function: `Buffer` instances can be iterated over using `for..of` syntax: ```mjs -import { Buffer } from 'buffer'; +import { Buffer } from 'node:buffer'; const buf = Buffer.from([1, 2, 3]); @@ -432,7 +432,7 @@ for (const b of buf) { ``` ```cjs -const { Buffer } = require('buffer'); +const { Buffer } = require('node:buffer'); const buf = Buffer.from([1, 2, 3]); @@ -476,7 +476,7 @@ changes: * `options` {Object} * `endings` {string} One of either `'transparent'` or `'native'`. When set to `'native'`, line endings in string source parts will be converted to - the platform native line-ending as specified by `require('os').EOL`. + the platform native line-ending as specified by `require('node:os').EOL`. * `type` {string} The Blob content-type. The intent is for `type` to convey the MIME media type of the data, however no validation of the type format is performed. @@ -561,8 +561,8 @@ contained by the `Blob` is copied only when the `arrayBuffer()` or `text()` methods are called. ```mjs -import { Blob, Buffer } from 'buffer'; -import { setTimeout as delay } from 'timers/promises'; +import { Blob, Buffer } from 'node:buffer'; +import { setTimeout as delay } from 'node:timers/promises'; const blob = new Blob(['hello there']); @@ -588,8 +588,8 @@ blob.text().then(console.log); ``` ```cjs -const { Blob, Buffer } = require('buffer'); -const { setTimeout: delay } = require('timers/promises'); +const { Blob, Buffer } = require('node:buffer'); +const { setTimeout: delay } = require('node:timers/promises'); const blob = new Blob(['hello there']); @@ -652,7 +652,7 @@ Allocates a new `Buffer` of `size` bytes. If `fill` is `undefined`, the `Buffer` will be zero-filled. ```mjs -import { Buffer } from 'buffer'; +import { Buffer } from 'node:buffer'; const buf = Buffer.alloc(5); @@ -661,7 +661,7 @@ console.log(buf); ``` ```cjs -const { Buffer } = require('buffer'); +const { Buffer } = require('node:buffer'); const buf = Buffer.alloc(5); @@ -677,7 +677,7 @@ If `fill` is specified, the allocated `Buffer` will be initialized by calling [`buf.fill(fill)`][`buf.fill()`]. ```mjs -import { Buffer } from 'buffer'; +import { Buffer } from 'node:buffer'; const buf = Buffer.alloc(5, 'a'); @@ -686,7 +686,7 @@ console.log(buf); ``` ```cjs -const { Buffer } = require('buffer'); +const { Buffer } = require('node:buffer'); const buf = Buffer.alloc(5, 'a'); @@ -698,7 +698,7 @@ If both `fill` and `encoding` are specified, the allocated `Buffer` will be initialized by calling [`buf.fill(fill, encoding)`][`buf.fill()`]. ```mjs -import { Buffer } from 'buffer'; +import { Buffer } from 'node:buffer'; const buf = Buffer.alloc(11, 'aGVsbG8gd29ybGQ=', 'base64'); @@ -707,7 +707,7 @@ console.log(buf); ``` ```cjs -const { Buffer } = require('buffer'); +const { Buffer } = require('node:buffer'); const buf = Buffer.alloc(11, 'aGVsbG8gd29ybGQ=', 'base64'); @@ -748,7 +748,7 @@ _may contain sensitive data_. Use [`Buffer.alloc()`][] instead to initialize `Buffer` instances with zeroes. ```mjs -import { Buffer } from 'buffer'; +import { Buffer } from 'node:buffer'; const buf = Buffer.allocUnsafe(10); @@ -762,7 +762,7 @@ console.log(buf); ``` ```cjs -const { Buffer } = require('buffer'); +const { Buffer } = require('node:buffer'); const buf = Buffer.allocUnsafe(10); @@ -827,7 +827,7 @@ to create an un-pooled `Buffer` instance using `Buffer.allocUnsafeSlow()` and then copying out the relevant bits. ```mjs -import { Buffer } from 'buffer'; +import { Buffer } from 'node:buffer'; // Need to keep around a few small chunks of memory. const store = []; @@ -847,7 +847,7 @@ socket.on('readable', () => { ``` ```cjs -const { Buffer } = require('buffer'); +const { Buffer } = require('node:buffer'); // Need to keep around a few small chunks of memory. const store = []; @@ -898,7 +898,7 @@ return value might be greater than the length of a `Buffer` created from the string. ```mjs -import { Buffer } from 'buffer'; +import { Buffer } from 'node:buffer'; const str = '\u00bd + \u00bc = \u00be'; @@ -908,7 +908,7 @@ console.log(`${str}: ${str.length} characters, ` + ``` ```cjs -const { Buffer } = require('buffer'); +const { Buffer } = require('node:buffer'); const str = '\u00bd + \u00bc = \u00be'; @@ -941,7 +941,7 @@ Compares `buf1` to `buf2`, typically for the purpose of sorting arrays of [`buf1.compare(buf2)`][`buf.compare()`]. ```mjs -import { Buffer } from 'buffer'; +import { Buffer } from 'node:buffer'; const buf1 = Buffer.from('1234'); const buf2 = Buffer.from('0123'); @@ -953,7 +953,7 @@ console.log(arr.sort(Buffer.compare)); ``` ```cjs -const { Buffer } = require('buffer'); +const { Buffer } = require('node:buffer'); const buf1 = Buffer.from('1234'); const buf2 = Buffer.from('0123'); @@ -994,7 +994,7 @@ combined length of the `Buffer`s in `list` exceeds `totalLength`, the result is truncated to `totalLength`. ```mjs -import { Buffer } from 'buffer'; +import { Buffer } from 'node:buffer'; // Create a single `Buffer` from a list of three `Buffer` instances. @@ -1015,7 +1015,7 @@ console.log(bufA.length); ``` ```cjs -const { Buffer } = require('buffer'); +const { Buffer } = require('node:buffer'); // Create a single `Buffer` from a list of three `Buffer` instances. @@ -1050,14 +1050,14 @@ Allocates a new `Buffer` using an `array` of bytes in the range `0` – `255`. Array entries outside that range will be truncated to fit into it. ```mjs -import { Buffer } from 'buffer'; +import { Buffer } from 'node:buffer'; // Creates a new Buffer containing the UTF-8 bytes of the string 'buffer'. const buf = Buffer.from([0x62, 0x75, 0x66, 0x66, 0x65, 0x72]); ``` ```cjs -const { Buffer } = require('buffer'); +const { Buffer } = require('node:buffer'); // Creates a new Buffer containing the UTF-8 bytes of the string 'buffer'. const buf = Buffer.from([0x62, 0x75, 0x66, 0x66, 0x65, 0x72]); @@ -1088,7 +1088,7 @@ memory. For example, when passed a reference to the `.buffer` property of a allocated memory as the [`TypedArray`][]'s underlying `ArrayBuffer`. ```mjs -import { Buffer } from 'buffer'; +import { Buffer } from 'node:buffer'; const arr = new Uint16Array(2); @@ -1109,7 +1109,7 @@ console.log(buf); ``` ```cjs -const { Buffer } = require('buffer'); +const { Buffer } = require('node:buffer'); const arr = new Uint16Array(2); @@ -1133,7 +1133,7 @@ The optional `byteOffset` and `length` arguments specify a memory range within the `arrayBuffer` that will be shared by the `Buffer`. ```mjs -import { Buffer } from 'buffer'; +import { Buffer } from 'node:buffer'; const ab = new ArrayBuffer(10); const buf = Buffer.from(ab, 0, 2); @@ -1143,7 +1143,7 @@ console.log(buf.length); ``` ```cjs -const { Buffer } = require('buffer'); +const { Buffer } = require('node:buffer'); const ab = new ArrayBuffer(10); const buf = Buffer.from(ab, 0, 2); @@ -1162,7 +1162,7 @@ of memory that extends beyond the bounds of a `TypedArray` view. A new beyond the range of the `TypedArray`: ```mjs -import { Buffer } from 'buffer'; +import { Buffer } from 'node:buffer'; const arrA = Uint8Array.from([0x63, 0x64, 0x65, 0x66]); // 4 elements const arrB = new Uint8Array(arrA.buffer, 1, 2); // 2 elements @@ -1174,7 +1174,7 @@ console.log(buf); ``` ```cjs -const { Buffer } = require('buffer'); +const { Buffer } = require('node:buffer'); const arrA = Uint8Array.from([0x63, 0x64, 0x65, 0x66]); // 4 elements const arrB = new Uint8Array(arrA.buffer, 1, 2); // 2 elements @@ -1197,7 +1197,7 @@ added: v5.10.0 Copies the passed `buffer` data onto a new `Buffer` instance. ```mjs -import { Buffer } from 'buffer'; +import { Buffer } from 'node:buffer'; const buf1 = Buffer.from('buffer'); const buf2 = Buffer.from(buf1); @@ -1211,7 +1211,7 @@ console.log(buf2.toString()); ``` ```cjs -const { Buffer } = require('buffer'); +const { Buffer } = require('node:buffer'); const buf1 = Buffer.from('buffer'); const buf2 = Buffer.from(buf1); @@ -1241,14 +1241,14 @@ For objects whose `valueOf()` function returns a value not strictly equal to `object`, returns `Buffer.from(object.valueOf(), offsetOrEncoding, length)`. ```mjs -import { Buffer } from 'buffer'; +import { Buffer } from 'node:buffer'; const buf = Buffer.from(new String('this is a test')); // Prints: ``` ```cjs -const { Buffer } = require('buffer'); +const { Buffer } = require('node:buffer'); const buf = Buffer.from(new String('this is a test')); // Prints: @@ -1258,7 +1258,7 @@ For objects that support `Symbol.toPrimitive`, returns `Buffer.from(object[Symbol.toPrimitive]('string'), offsetOrEncoding)`. ```mjs -import { Buffer } from 'buffer'; +import { Buffer } from 'node:buffer'; class Foo { [Symbol.toPrimitive]() { @@ -1271,7 +1271,7 @@ const buf = Buffer.from(new Foo(), 'utf8'); ``` ```cjs -const { Buffer } = require('buffer'); +const { Buffer } = require('node:buffer'); class Foo { [Symbol.toPrimitive]() { @@ -1299,7 +1299,7 @@ Creates a new `Buffer` containing `string`. The `encoding` parameter identifies the character encoding to be used when converting `string` into bytes. ```mjs -import { Buffer } from 'buffer'; +import { Buffer } from 'node:buffer'; const buf1 = Buffer.from('this is a tést'); const buf2 = Buffer.from('7468697320697320612074c3a97374', 'hex'); @@ -1313,7 +1313,7 @@ console.log(buf1.toString('latin1')); ``` ```cjs -const { Buffer } = require('buffer'); +const { Buffer } = require('node:buffer'); const buf1 = Buffer.from('this is a tést'); const buf2 = Buffer.from('7468697320697320612074c3a97374', 'hex'); @@ -1341,7 +1341,7 @@ added: v0.1.101 Returns `true` if `obj` is a `Buffer`, `false` otherwise. ```mjs -import { Buffer } from 'buffer'; +import { Buffer } from 'node:buffer'; Buffer.isBuffer(Buffer.alloc(10)); // true Buffer.isBuffer(Buffer.from('foo')); // true @@ -1351,7 +1351,7 @@ Buffer.isBuffer(new Uint8Array(1024)); // false ``` ```cjs -const { Buffer } = require('buffer'); +const { Buffer } = require('node:buffer'); Buffer.isBuffer(Buffer.alloc(10)); // true Buffer.isBuffer(Buffer.from('foo')); // true @@ -1373,7 +1373,7 @@ Returns `true` if `encoding` is the name of a supported character encoding, or `false` otherwise. ```mjs -import { Buffer } from 'buffer'; +import { Buffer } from 'node:buffer'; console.log(Buffer.isEncoding('utf8')); // Prints: true @@ -1389,7 +1389,7 @@ console.log(Buffer.isEncoding('')); ``` ```cjs -const { Buffer } = require('buffer'); +const { Buffer } = require('node:buffer'); console.log(Buffer.isEncoding('utf8')); // Prints: true @@ -1430,7 +1430,7 @@ access is the same as `Uint8Array`. In other words, `buf[index]` returns `>= buf.length`. ```mjs -import { Buffer } from 'buffer'; +import { Buffer } from 'node:buffer'; // Copy an ASCII string into a `Buffer` one byte at a time. // (This only works for ASCII-only strings. In general, one should use @@ -1448,7 +1448,7 @@ console.log(buf.toString('utf8')); ``` ```cjs -const { Buffer } = require('buffer'); +const { Buffer } = require('node:buffer'); // Copy an ASCII string into a `Buffer` one byte at a time. // (This only works for ASCII-only strings. In general, one should use @@ -1474,7 +1474,7 @@ This `ArrayBuffer` is not guaranteed to correspond exactly to the original `Buffer`. See the notes on `buf.byteOffset` for details. ```mjs -import { Buffer } from 'buffer'; +import { Buffer } from 'node:buffer'; const arrayBuffer = new ArrayBuffer(16); const buffer = Buffer.from(arrayBuffer); @@ -1484,7 +1484,7 @@ console.log(buffer.buffer === arrayBuffer); ``` ```cjs -const { Buffer } = require('buffer'); +const { Buffer } = require('node:buffer'); const arrayBuffer = new ArrayBuffer(16); const buffer = Buffer.from(arrayBuffer); @@ -1509,7 +1509,7 @@ A common issue when creating a `TypedArray` object that shares its memory with a `Buffer` is that in this case one needs to specify the `byteOffset` correctly: ```mjs -import { Buffer } from 'buffer'; +import { Buffer } from 'node:buffer'; // Create a buffer smaller than `Buffer.poolSize`. const nodeBuffer = Buffer.from([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]); @@ -1521,7 +1521,7 @@ new Int8Array(nodeBuffer.buffer, nodeBuffer.byteOffset, nodeBuffer.length); ``` ```cjs -const { Buffer } = require('buffer'); +const { Buffer } = require('node:buffer'); // Create a buffer smaller than `Buffer.poolSize`. const nodeBuffer = Buffer.from([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]); @@ -1566,7 +1566,7 @@ Comparison is based on the actual sequence of bytes in each `Buffer`. * `-1` is returned if `target` should come _after_ `buf` when sorted. ```mjs -import { Buffer } from 'buffer'; +import { Buffer } from 'node:buffer'; const buf1 = Buffer.from('ABC'); const buf2 = Buffer.from('BCD'); @@ -1588,7 +1588,7 @@ console.log([buf1, buf2, buf3].sort(Buffer.compare)); ``` ```cjs -const { Buffer } = require('buffer'); +const { Buffer } = require('node:buffer'); const buf1 = Buffer.from('ABC'); const buf2 = Buffer.from('BCD'); @@ -1614,7 +1614,7 @@ arguments can be used to limit the comparison to specific ranges within `target` and `buf` respectively. ```mjs -import { Buffer } from 'buffer'; +import { Buffer } from 'node:buffer'; const buf1 = Buffer.from([1, 2, 3, 4, 5, 6, 7, 8, 9]); const buf2 = Buffer.from([5, 6, 7, 8, 9, 1, 2, 3, 4]); @@ -1628,7 +1628,7 @@ console.log(buf1.compare(buf2, 5, 6, 5)); ``` ```cjs -const { Buffer } = require('buffer'); +const { Buffer } = require('node:buffer'); const buf1 = Buffer.from([1, 2, 3, 4, 5, 6, 7, 8, 9]); const buf2 = Buffer.from([5, 6, 7, 8, 9, 1, 2, 3, 4]); @@ -1667,7 +1667,7 @@ for all TypedArrays, including Node.js `Buffer`s, although it takes different function arguments. ```mjs -import { Buffer } from 'buffer'; +import { Buffer } from 'node:buffer'; // Create two `Buffer` instances. const buf1 = Buffer.allocUnsafe(26); @@ -1688,7 +1688,7 @@ console.log(buf2.toString('ascii', 0, 25)); ``` ```cjs -const { Buffer } = require('buffer'); +const { Buffer } = require('node:buffer'); // Create two `Buffer` instances. const buf1 = Buffer.allocUnsafe(26); @@ -1709,7 +1709,7 @@ console.log(buf2.toString('ascii', 0, 25)); ``` ```mjs -import { Buffer } from 'buffer'; +import { Buffer } from 'node:buffer'; // Create a `Buffer` and copy data from one region to an overlapping region // within the same `Buffer`. @@ -1728,7 +1728,7 @@ console.log(buf.toString()); ``` ```cjs -const { Buffer } = require('buffer'); +const { Buffer } = require('node:buffer'); // Create a `Buffer` and copy data from one region to an overlapping region // within the same `Buffer`. @@ -1758,7 +1758,7 @@ Creates and returns an [iterator][] of `[index, byte]` pairs from the contents of `buf`. ```mjs -import { Buffer } from 'buffer'; +import { Buffer } from 'node:buffer'; // Log the entire contents of a `Buffer`. @@ -1777,7 +1777,7 @@ for (const pair of buf.entries()) { ``` ```cjs -const { Buffer } = require('buffer'); +const { Buffer } = require('node:buffer'); // Log the entire contents of a `Buffer`. @@ -1814,7 +1814,7 @@ Returns `true` if both `buf` and `otherBuffer` have exactly the same bytes, [`buf.compare(otherBuffer) === 0`][`buf.compare()`]. ```mjs -import { Buffer } from 'buffer'; +import { Buffer } from 'node:buffer'; const buf1 = Buffer.from('ABC'); const buf2 = Buffer.from('414243', 'hex'); @@ -1827,7 +1827,7 @@ console.log(buf1.equals(buf3)); ``` ```cjs -const { Buffer } = require('buffer'); +const { Buffer } = require('node:buffer'); const buf1 = Buffer.from('ABC'); const buf2 = Buffer.from('414243', 'hex'); @@ -1876,7 +1876,7 @@ Fills `buf` with the specified `value`. If the `offset` and `end` are not given, the entire `buf` will be filled: ```mjs -import { Buffer } from 'buffer'; +import { Buffer } from 'node:buffer'; // Fill a `Buffer` with the ASCII character 'h'. @@ -1887,7 +1887,7 @@ console.log(b.toString()); ``` ```cjs -const { Buffer } = require('buffer'); +const { Buffer } = require('node:buffer'); // Fill a `Buffer` with the ASCII character 'h'. @@ -1905,7 +1905,7 @@ If the final write of a `fill()` operation falls on a multi-byte character, then only the bytes of that character that fit into `buf` are written: ```mjs -import { Buffer } from 'buffer'; +import { Buffer } from 'node:buffer'; // Fill a `Buffer` with character that takes up two bytes in UTF-8. @@ -1914,7 +1914,7 @@ console.log(Buffer.allocUnsafe(5).fill('\u0222')); ``` ```cjs -const { Buffer } = require('buffer'); +const { Buffer } = require('node:buffer'); // Fill a `Buffer` with character that takes up two bytes in UTF-8. @@ -1926,7 +1926,7 @@ If `value` contains invalid characters, it is truncated; if no valid fill data remains, an exception is thrown: ```mjs -import { Buffer } from 'buffer'; +import { Buffer } from 'node:buffer'; const buf = Buffer.allocUnsafe(5); @@ -1939,7 +1939,7 @@ console.log(buf.fill('zz', 'hex')); ``` ```cjs -const { Buffer } = require('buffer'); +const { Buffer } = require('node:buffer'); const buf = Buffer.allocUnsafe(5); @@ -1967,7 +1967,7 @@ added: v5.3.0 Equivalent to [`buf.indexOf() !== -1`][`buf.indexOf()`]. ```mjs -import { Buffer } from 'buffer'; +import { Buffer } from 'node:buffer'; const buf = Buffer.from('this is a buffer'); @@ -1988,7 +1988,7 @@ console.log(buf.includes('this', 4)); ``` ```cjs -const { Buffer } = require('buffer'); +const { Buffer } = require('node:buffer'); const buf = Buffer.from('this is a buffer'); @@ -2043,7 +2043,7 @@ If `value` is: value between `0` and `255`. ```mjs -import { Buffer } from 'buffer'; +import { Buffer } from 'node:buffer'; const buf = Buffer.from('this is a buffer'); @@ -2069,7 +2069,7 @@ console.log(utf16Buffer.indexOf('\u03a3', -4, 'utf16le')); ``` ```cjs -const { Buffer } = require('buffer'); +const { Buffer } = require('node:buffer'); const buf = Buffer.from('this is a buffer'); @@ -2103,7 +2103,7 @@ of coercion is `NaN` or `0`, then the entire buffer will be searched. This behavior matches [`String.prototype.indexOf()`][]. ```mjs -import { Buffer } from 'buffer'; +import { Buffer } from 'node:buffer'; const b = Buffer.from('abcdef'); @@ -2121,7 +2121,7 @@ console.log(b.indexOf('b', [])); ``` ```cjs -const { Buffer } = require('buffer'); +const { Buffer } = require('node:buffer'); const b = Buffer.from('abcdef'); @@ -2153,7 +2153,7 @@ added: v1.1.0 Creates and returns an [iterator][] of `buf` keys (indices). ```mjs -import { Buffer } from 'buffer'; +import { Buffer } from 'node:buffer'; const buf = Buffer.from('buffer'); @@ -2170,7 +2170,7 @@ for (const key of buf.keys()) { ``` ```cjs -const { Buffer } = require('buffer'); +const { Buffer } = require('node:buffer'); const buf = Buffer.from('buffer'); @@ -2210,7 +2210,7 @@ Identical to [`buf.indexOf()`][], except the last occurrence of `value` is found rather than the first occurrence. ```mjs -import { Buffer } from 'buffer'; +import { Buffer } from 'node:buffer'; const buf = Buffer.from('this buffer is a buffer'); @@ -2238,7 +2238,7 @@ console.log(utf16Buffer.lastIndexOf('\u03a3', -5, 'utf16le')); ``` ```cjs -const { Buffer } = require('buffer'); +const { Buffer } = require('node:buffer'); const buf = Buffer.from('this buffer is a buffer'); @@ -2274,7 +2274,7 @@ that coerce to `NaN`, like `{}` or `undefined`, will search the whole buffer. This behavior matches [`String.prototype.lastIndexOf()`][]. ```mjs -import { Buffer } from 'buffer'; +import { Buffer } from 'node:buffer'; const b = Buffer.from('abcdef'); @@ -2295,7 +2295,7 @@ console.log(b.lastIndexOf('b', [])); ``` ```cjs -const { Buffer } = require('buffer'); +const { Buffer } = require('node:buffer'); const b = Buffer.from('abcdef'); @@ -2328,7 +2328,7 @@ added: v0.1.90 Returns the number of bytes in `buf`. ```mjs -import { Buffer } from 'buffer'; +import { Buffer } from 'node:buffer'; // Create a `Buffer` and write a shorter string to it using UTF-8. @@ -2344,7 +2344,7 @@ console.log(buf.length); ``` ```cjs -const { Buffer } = require('buffer'); +const { Buffer } = require('node:buffer'); // Create a `Buffer` and write a shorter string to it using UTF-8. @@ -2428,7 +2428,7 @@ Reads an unsigned, big-endian 64-bit integer from `buf` at the specified This function is also available under the `readBigUint64BE` alias. ```mjs -import { Buffer } from 'buffer'; +import { Buffer } from 'node:buffer'; const buf = Buffer.from([0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff]); @@ -2437,7 +2437,7 @@ console.log(buf.readBigUInt64BE(0)); ``` ```cjs -const { Buffer } = require('buffer'); +const { Buffer } = require('node:buffer'); const buf = Buffer.from([0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff]); @@ -2469,7 +2469,7 @@ Reads an unsigned, little-endian 64-bit integer from `buf` at the specified This function is also available under the `readBigUint64LE` alias. ```mjs -import { Buffer } from 'buffer'; +import { Buffer } from 'node:buffer'; const buf = Buffer.from([0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff]); @@ -2478,7 +2478,7 @@ console.log(buf.readBigUInt64LE(0)); ``` ```cjs -const { Buffer } = require('buffer'); +const { Buffer } = require('node:buffer'); const buf = Buffer.from([0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff]); @@ -2504,7 +2504,7 @@ changes: Reads a 64-bit, big-endian double from `buf` at the specified `offset`. ```mjs -import { Buffer } from 'buffer'; +import { Buffer } from 'node:buffer'; const buf = Buffer.from([1, 2, 3, 4, 5, 6, 7, 8]); @@ -2513,7 +2513,7 @@ console.log(buf.readDoubleBE(0)); ``` ```cjs -const { Buffer } = require('buffer'); +const { Buffer } = require('node:buffer'); const buf = Buffer.from([1, 2, 3, 4, 5, 6, 7, 8]); @@ -2539,7 +2539,7 @@ changes: Reads a 64-bit, little-endian double from `buf` at the specified `offset`. ```mjs -import { Buffer } from 'buffer'; +import { Buffer } from 'node:buffer'; const buf = Buffer.from([1, 2, 3, 4, 5, 6, 7, 8]); @@ -2550,7 +2550,7 @@ console.log(buf.readDoubleLE(1)); ``` ```cjs -const { Buffer } = require('buffer'); +const { Buffer } = require('node:buffer'); const buf = Buffer.from([1, 2, 3, 4, 5, 6, 7, 8]); @@ -2578,7 +2578,7 @@ changes: Reads a 32-bit, big-endian float from `buf` at the specified `offset`. ```mjs -import { Buffer } from 'buffer'; +import { Buffer } from 'node:buffer'; const buf = Buffer.from([1, 2, 3, 4]); @@ -2587,7 +2587,7 @@ console.log(buf.readFloatBE(0)); ``` ```cjs -const { Buffer } = require('buffer'); +const { Buffer } = require('node:buffer'); const buf = Buffer.from([1, 2, 3, 4]); @@ -2613,7 +2613,7 @@ changes: Reads a 32-bit, little-endian float from `buf` at the specified `offset`. ```mjs -import { Buffer } from 'buffer'; +import { Buffer } from 'node:buffer'; const buf = Buffer.from([1, 2, 3, 4]); @@ -2624,7 +2624,7 @@ console.log(buf.readFloatLE(1)); ``` ```cjs -const { Buffer } = require('buffer'); +const { Buffer } = require('node:buffer'); const buf = Buffer.from([1, 2, 3, 4]); @@ -2654,7 +2654,7 @@ Reads a signed 8-bit integer from `buf` at the specified `offset`. Integers read from a `Buffer` are interpreted as two's complement signed values. ```mjs -import { Buffer } from 'buffer'; +import { Buffer } from 'node:buffer'; const buf = Buffer.from([-1, 5]); @@ -2667,7 +2667,7 @@ console.log(buf.readInt8(2)); ``` ```cjs -const { Buffer } = require('buffer'); +const { Buffer } = require('node:buffer'); const buf = Buffer.from([-1, 5]); @@ -2699,7 +2699,7 @@ Reads a signed, big-endian 16-bit integer from `buf` at the specified `offset`. Integers read from a `Buffer` are interpreted as two's complement signed values. ```mjs -import { Buffer } from 'buffer'; +import { Buffer } from 'node:buffer'; const buf = Buffer.from([0, 5]); @@ -2708,7 +2708,7 @@ console.log(buf.readInt16BE(0)); ``` ```cjs -const { Buffer } = require('buffer'); +const { Buffer } = require('node:buffer'); const buf = Buffer.from([0, 5]); @@ -2737,7 +2737,7 @@ Reads a signed, little-endian 16-bit integer from `buf` at the specified Integers read from a `Buffer` are interpreted as two's complement signed values. ```mjs -import { Buffer } from 'buffer'; +import { Buffer } from 'node:buffer'; const buf = Buffer.from([0, 5]); @@ -2748,7 +2748,7 @@ console.log(buf.readInt16LE(1)); ``` ```cjs -const { Buffer } = require('buffer'); +const { Buffer } = require('node:buffer'); const buf = Buffer.from([0, 5]); @@ -2778,7 +2778,7 @@ Reads a signed, big-endian 32-bit integer from `buf` at the specified `offset`. Integers read from a `Buffer` are interpreted as two's complement signed values. ```mjs -import { Buffer } from 'buffer'; +import { Buffer } from 'node:buffer'; const buf = Buffer.from([0, 0, 0, 5]); @@ -2787,7 +2787,7 @@ console.log(buf.readInt32BE(0)); ``` ```cjs -const { Buffer } = require('buffer'); +const { Buffer } = require('node:buffer'); const buf = Buffer.from([0, 0, 0, 5]); @@ -2816,7 +2816,7 @@ Reads a signed, little-endian 32-bit integer from `buf` at the specified Integers read from a `Buffer` are interpreted as two's complement signed values. ```mjs -import { Buffer } from 'buffer'; +import { Buffer } from 'node:buffer'; const buf = Buffer.from([0, 0, 0, 5]); @@ -2827,7 +2827,7 @@ console.log(buf.readInt32LE(1)); ``` ```cjs -const { Buffer } = require('buffer'); +const { Buffer } = require('node:buffer'); const buf = Buffer.from([0, 0, 0, 5]); @@ -2859,7 +2859,7 @@ and interprets the result as a big-endian, two's complement signed value supporting up to 48 bits of accuracy. ```mjs -import { Buffer } from 'buffer'; +import { Buffer } from 'node:buffer'; const buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]); @@ -2872,7 +2872,7 @@ console.log(buf.readIntBE(1, 0).toString(16)); ``` ```cjs -const { Buffer } = require('buffer'); +const { Buffer } = require('node:buffer'); const buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]); @@ -2906,7 +2906,7 @@ and interprets the result as a little-endian, two's complement signed value supporting up to 48 bits of accuracy. ```mjs -import { Buffer } from 'buffer'; +import { Buffer } from 'node:buffer'; const buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]); @@ -2915,7 +2915,7 @@ console.log(buf.readIntLE(0, 6).toString(16)); ``` ```cjs -const { Buffer } = require('buffer'); +const { Buffer } = require('node:buffer'); const buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]); @@ -2948,7 +2948,7 @@ Reads an unsigned 8-bit integer from `buf` at the specified `offset`. This function is also available under the `readUint8` alias. ```mjs -import { Buffer } from 'buffer'; +import { Buffer } from 'node:buffer'; const buf = Buffer.from([1, -2]); @@ -2961,7 +2961,7 @@ console.log(buf.readUInt8(2)); ``` ```cjs -const { Buffer } = require('buffer'); +const { Buffer } = require('node:buffer'); const buf = Buffer.from([1, -2]); @@ -2999,7 +2999,7 @@ Reads an unsigned, big-endian 16-bit integer from `buf` at the specified This function is also available under the `readUint16BE` alias. ```mjs -import { Buffer } from 'buffer'; +import { Buffer } from 'node:buffer'; const buf = Buffer.from([0x12, 0x34, 0x56]); @@ -3010,7 +3010,7 @@ console.log(buf.readUInt16BE(1).toString(16)); ``` ```cjs -const { Buffer } = require('buffer'); +const { Buffer } = require('node:buffer'); const buf = Buffer.from([0x12, 0x34, 0x56]); @@ -3046,7 +3046,7 @@ Reads an unsigned, little-endian 16-bit integer from `buf` at the specified This function is also available under the `readUint16LE` alias. ```mjs -import { Buffer } from 'buffer'; +import { Buffer } from 'node:buffer'; const buf = Buffer.from([0x12, 0x34, 0x56]); @@ -3059,7 +3059,7 @@ console.log(buf.readUInt16LE(2).toString(16)); ``` ```cjs -const { Buffer } = require('buffer'); +const { Buffer } = require('node:buffer'); const buf = Buffer.from([0x12, 0x34, 0x56]); @@ -3097,7 +3097,7 @@ Reads an unsigned, big-endian 32-bit integer from `buf` at the specified This function is also available under the `readUint32BE` alias. ```mjs -import { Buffer } from 'buffer'; +import { Buffer } from 'node:buffer'; const buf = Buffer.from([0x12, 0x34, 0x56, 0x78]); @@ -3106,7 +3106,7 @@ console.log(buf.readUInt32BE(0).toString(16)); ``` ```cjs -const { Buffer } = require('buffer'); +const { Buffer } = require('node:buffer'); const buf = Buffer.from([0x12, 0x34, 0x56, 0x78]); @@ -3140,7 +3140,7 @@ Reads an unsigned, little-endian 32-bit integer from `buf` at the specified This function is also available under the `readUint32LE` alias. ```mjs -import { Buffer } from 'buffer'; +import { Buffer } from 'node:buffer'; const buf = Buffer.from([0x12, 0x34, 0x56, 0x78]); @@ -3151,7 +3151,7 @@ console.log(buf.readUInt32LE(1).toString(16)); ``` ```cjs -const { Buffer } = require('buffer'); +const { Buffer } = require('node:buffer'); const buf = Buffer.from([0x12, 0x34, 0x56, 0x78]); @@ -3190,7 +3190,7 @@ up to 48 bits of accuracy. This function is also available under the `readUintBE` alias. ```mjs -import { Buffer } from 'buffer'; +import { Buffer } from 'node:buffer'; const buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]); @@ -3201,7 +3201,7 @@ console.log(buf.readUIntBE(1, 6).toString(16)); ``` ```cjs -const { Buffer } = require('buffer'); +const { Buffer } = require('node:buffer'); const buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]); @@ -3240,7 +3240,7 @@ up to 48 bits of accuracy. This function is also available under the `readUintLE` alias. ```mjs -import { Buffer } from 'buffer'; +import { Buffer } from 'node:buffer'; const buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]); @@ -3249,7 +3249,7 @@ console.log(buf.readUIntLE(0, 6).toString(16)); ``` ```cjs -const { Buffer } = require('buffer'); +const { Buffer } = require('node:buffer'); const buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]); @@ -3280,7 +3280,7 @@ Modifying the new `Buffer` slice will modify the memory in the original `Buffer` because the allocated memory of the two objects overlap. ```mjs -import { Buffer } from 'buffer'; +import { Buffer } from 'node:buffer'; // Create a `Buffer` with the ASCII alphabet, take a slice, and modify one byte // from the original `Buffer`. @@ -3304,7 +3304,7 @@ console.log(buf2.toString('ascii', 0, buf2.length)); ``` ```cjs -const { Buffer } = require('buffer'); +const { Buffer } = require('node:buffer'); // Create a `Buffer` with the ASCII alphabet, take a slice, and modify one byte // from the original `Buffer`. @@ -3331,7 +3331,7 @@ Specifying negative indexes causes the slice to be generated relative to the end of `buf` rather than the beginning. ```mjs -import { Buffer } from 'buffer'; +import { Buffer } from 'node:buffer'; const buf = Buffer.from('buffer'); @@ -3349,7 +3349,7 @@ console.log(buf.subarray(-5, -2).toString()); ``` ```cjs -const { Buffer } = require('buffer'); +const { Buffer } = require('node:buffer'); const buf = Buffer.from('buffer'); @@ -3401,7 +3401,7 @@ which is a superclass of `Buffer`. To copy the slice, use `Uint8Array.prototype.slice()`. ```mjs -import { Buffer } from 'buffer'; +import { Buffer } from 'node:buffer'; const buf = Buffer.from('buffer'); @@ -3423,7 +3423,7 @@ console.log(buf.toString()); ``` ```cjs -const { Buffer } = require('buffer'); +const { Buffer } = require('node:buffer'); const buf = Buffer.from('buffer'); @@ -3457,7 +3457,7 @@ byte order _in-place_. Throws [`ERR_INVALID_BUFFER_SIZE`][] if [`buf.length`][] is not a multiple of 2. ```mjs -import { Buffer } from 'buffer'; +import { Buffer } from 'node:buffer'; const buf1 = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8]); @@ -3476,7 +3476,7 @@ buf2.swap16(); ``` ```cjs -const { Buffer } = require('buffer'); +const { Buffer } = require('node:buffer'); const buf1 = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8]); @@ -3498,14 +3498,14 @@ One convenient use of `buf.swap16()` is to perform a fast in-place conversion between UTF-16 little-endian and UTF-16 big-endian: ```mjs -import { Buffer } from 'buffer'; +import { Buffer } from 'node:buffer'; const buf = Buffer.from('This is little-endian UTF-16', 'utf16le'); buf.swap16(); // Convert to big-endian UTF-16 text. ``` ```cjs -const { Buffer } = require('buffer'); +const { Buffer } = require('node:buffer'); const buf = Buffer.from('This is little-endian UTF-16', 'utf16le'); buf.swap16(); // Convert to big-endian UTF-16 text. @@ -3524,7 +3524,7 @@ byte order _in-place_. Throws [`ERR_INVALID_BUFFER_SIZE`][] if [`buf.length`][] is not a multiple of 4. ```mjs -import { Buffer } from 'buffer'; +import { Buffer } from 'node:buffer'; const buf1 = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8]); @@ -3543,7 +3543,7 @@ buf2.swap32(); ``` ```cjs -const { Buffer } = require('buffer'); +const { Buffer } = require('node:buffer'); const buf1 = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8]); @@ -3573,7 +3573,7 @@ Interprets `buf` as an array of 64-bit numbers and swaps byte order _in-place_. Throws [`ERR_INVALID_BUFFER_SIZE`][] if [`buf.length`][] is not a multiple of 8. ```mjs -import { Buffer } from 'buffer'; +import { Buffer } from 'node:buffer'; const buf1 = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8]); @@ -3592,7 +3592,7 @@ buf2.swap64(); ``` ```cjs -const { Buffer } = require('buffer'); +const { Buffer } = require('node:buffer'); const buf1 = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8]); @@ -3625,7 +3625,7 @@ this function when stringifying a `Buffer` instance. In particular, `Buffer.from(buf.toJSON())` works like `Buffer.from(buf)`. ```mjs -import { Buffer } from 'buffer'; +import { Buffer } from 'node:buffer'; const buf = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5]); const json = JSON.stringify(buf); @@ -3644,7 +3644,7 @@ console.log(copy); ``` ```cjs -const { Buffer } = require('buffer'); +const { Buffer } = require('node:buffer'); const buf = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5]); const json = JSON.stringify(buf); @@ -3684,7 +3684,7 @@ The maximum length of a string instance (in UTF-16 code units) is available as [`buffer.constants.MAX_STRING_LENGTH`][]. ```mjs -import { Buffer } from 'buffer'; +import { Buffer } from 'node:buffer'; const buf1 = Buffer.allocUnsafe(26); @@ -3709,7 +3709,7 @@ console.log(buf2.toString(undefined, 0, 3)); ``` ```cjs -const { Buffer } = require('buffer'); +const { Buffer } = require('node:buffer'); const buf1 = Buffer.allocUnsafe(26); @@ -3745,7 +3745,7 @@ Creates and returns an [iterator][] for `buf` values (bytes). This function is called automatically when a `Buffer` is used in a `for..of` statement. ```mjs -import { Buffer } from 'buffer'; +import { Buffer } from 'node:buffer'; const buf = Buffer.from('buffer'); @@ -3773,7 +3773,7 @@ for (const value of buf) { ``` ```cjs -const { Buffer } = require('buffer'); +const { Buffer } = require('node:buffer'); const buf = Buffer.from('buffer'); @@ -3820,7 +3820,7 @@ not contain enough space to fit the entire string, only part of `string` will be written. However, partially encoded characters will not be written. ```mjs -import { Buffer } from 'buffer'; +import { Buffer } from 'node:buffer'; const buf = Buffer.alloc(256); @@ -3838,7 +3838,7 @@ console.log(`${length} bytes: ${buffer.toString('utf8', 8, 10)}`); ``` ```cjs -const { Buffer } = require('buffer'); +const { Buffer } = require('node:buffer'); const buf = Buffer.alloc(256); @@ -3873,7 +3873,7 @@ Writes `value` to `buf` at the specified `offset` as big-endian. `value` is interpreted and written as a two's complement signed integer. ```mjs -import { Buffer } from 'buffer'; +import { Buffer } from 'node:buffer'; const buf = Buffer.allocUnsafe(8); @@ -3884,7 +3884,7 @@ console.log(buf); ``` ```cjs -const { Buffer } = require('buffer'); +const { Buffer } = require('node:buffer'); const buf = Buffer.allocUnsafe(8); @@ -3912,7 +3912,7 @@ Writes `value` to `buf` at the specified `offset` as little-endian. `value` is interpreted and written as a two's complement signed integer. ```mjs -import { Buffer } from 'buffer'; +import { Buffer } from 'node:buffer'; const buf = Buffer.allocUnsafe(8); @@ -3923,7 +3923,7 @@ console.log(buf); ``` ```cjs -const { Buffer } = require('buffer'); +const { Buffer } = require('node:buffer'); const buf = Buffer.allocUnsafe(8); @@ -3957,7 +3957,7 @@ Writes `value` to `buf` at the specified `offset` as big-endian. This function is also available under the `writeBigUint64BE` alias. ```mjs -import { Buffer } from 'buffer'; +import { Buffer } from 'node:buffer'; const buf = Buffer.allocUnsafe(8); @@ -3968,7 +3968,7 @@ console.log(buf); ``` ```cjs -const { Buffer } = require('buffer'); +const { Buffer } = require('node:buffer'); const buf = Buffer.allocUnsafe(8); @@ -4000,7 +4000,7 @@ changes: Writes `value` to `buf` at the specified `offset` as little-endian ```mjs -import { Buffer } from 'buffer'; +import { Buffer } from 'node:buffer'; const buf = Buffer.allocUnsafe(8); @@ -4011,7 +4011,7 @@ console.log(buf); ``` ```cjs -const { Buffer } = require('buffer'); +const { Buffer } = require('node:buffer'); const buf = Buffer.allocUnsafe(8); @@ -4044,7 +4044,7 @@ must be a JavaScript number. Behavior is undefined when `value` is anything other than a JavaScript number. ```mjs -import { Buffer } from 'buffer'; +import { Buffer } from 'node:buffer'; const buf = Buffer.allocUnsafe(8); @@ -4055,7 +4055,7 @@ console.log(buf); ``` ```cjs -const { Buffer } = require('buffer'); +const { Buffer } = require('node:buffer'); const buf = Buffer.allocUnsafe(8); @@ -4086,7 +4086,7 @@ must be a JavaScript number. Behavior is undefined when `value` is anything other than a JavaScript number. ```mjs -import { Buffer } from 'buffer'; +import { Buffer } from 'node:buffer'; const buf = Buffer.allocUnsafe(8); @@ -4097,7 +4097,7 @@ console.log(buf); ``` ```cjs -const { Buffer } = require('buffer'); +const { Buffer } = require('node:buffer'); const buf = Buffer.allocUnsafe(8); @@ -4127,7 +4127,7 @@ Writes `value` to `buf` at the specified `offset` as big-endian. Behavior is undefined when `value` is anything other than a JavaScript number. ```mjs -import { Buffer } from 'buffer'; +import { Buffer } from 'node:buffer'; const buf = Buffer.allocUnsafe(4); @@ -4138,7 +4138,7 @@ console.log(buf); ``` ```cjs -const { Buffer } = require('buffer'); +const { Buffer } = require('node:buffer'); const buf = Buffer.allocUnsafe(4); @@ -4168,7 +4168,7 @@ Writes `value` to `buf` at the specified `offset` as little-endian. Behavior is undefined when `value` is anything other than a JavaScript number. ```mjs -import { Buffer } from 'buffer'; +import { Buffer } from 'node:buffer'; const buf = Buffer.allocUnsafe(4); @@ -4179,7 +4179,7 @@ console.log(buf); ``` ```cjs -const { Buffer } = require('buffer'); +const { Buffer } = require('node:buffer'); const buf = Buffer.allocUnsafe(4); @@ -4212,7 +4212,7 @@ a signed 8-bit integer. `value` is interpreted and written as a two's complement signed integer. ```mjs -import { Buffer } from 'buffer'; +import { Buffer } from 'node:buffer'; const buf = Buffer.allocUnsafe(2); @@ -4224,7 +4224,7 @@ console.log(buf); ``` ```cjs -const { Buffer } = require('buffer'); +const { Buffer } = require('node:buffer'); const buf = Buffer.allocUnsafe(2); @@ -4258,7 +4258,7 @@ anything other than a signed 16-bit integer. The `value` is interpreted and written as a two's complement signed integer. ```mjs -import { Buffer } from 'buffer'; +import { Buffer } from 'node:buffer'; const buf = Buffer.allocUnsafe(2); @@ -4269,7 +4269,7 @@ console.log(buf); ``` ```cjs -const { Buffer } = require('buffer'); +const { Buffer } = require('node:buffer'); const buf = Buffer.allocUnsafe(2); @@ -4302,7 +4302,7 @@ anything other than a signed 16-bit integer. The `value` is interpreted and written as a two's complement signed integer. ```mjs -import { Buffer } from 'buffer'; +import { Buffer } from 'node:buffer'; const buf = Buffer.allocUnsafe(2); @@ -4313,7 +4313,7 @@ console.log(buf); ``` ```cjs -const { Buffer } = require('buffer'); +const { Buffer } = require('node:buffer'); const buf = Buffer.allocUnsafe(2); @@ -4346,7 +4346,7 @@ anything other than a signed 32-bit integer. The `value` is interpreted and written as a two's complement signed integer. ```mjs -import { Buffer } from 'buffer'; +import { Buffer } from 'node:buffer'; const buf = Buffer.allocUnsafe(4); @@ -4357,7 +4357,7 @@ console.log(buf); ``` ```cjs -const { Buffer } = require('buffer'); +const { Buffer } = require('node:buffer'); const buf = Buffer.allocUnsafe(4); @@ -4390,7 +4390,7 @@ anything other than a signed 32-bit integer. The `value` is interpreted and written as a two's complement signed integer. ```mjs -import { Buffer } from 'buffer'; +import { Buffer } from 'node:buffer'; const buf = Buffer.allocUnsafe(4); @@ -4401,7 +4401,7 @@ console.log(buf); ``` ```cjs -const { Buffer } = require('buffer'); +const { Buffer } = require('node:buffer'); const buf = Buffer.allocUnsafe(4); @@ -4434,7 +4434,7 @@ as big-endian. Supports up to 48 bits of accuracy. Behavior is undefined when `value` is anything other than a signed integer. ```mjs -import { Buffer } from 'buffer'; +import { Buffer } from 'node:buffer'; const buf = Buffer.allocUnsafe(6); @@ -4445,7 +4445,7 @@ console.log(buf); ``` ```cjs -const { Buffer } = require('buffer'); +const { Buffer } = require('node:buffer'); const buf = Buffer.allocUnsafe(6); @@ -4478,7 +4478,7 @@ as little-endian. Supports up to 48 bits of accuracy. Behavior is undefined when `value` is anything other than a signed integer. ```mjs -import { Buffer } from 'buffer'; +import { Buffer } from 'node:buffer'; const buf = Buffer.allocUnsafe(6); @@ -4489,7 +4489,7 @@ console.log(buf); ``` ```cjs -const { Buffer } = require('buffer'); +const { Buffer } = require('node:buffer'); const buf = Buffer.allocUnsafe(6); @@ -4527,7 +4527,7 @@ other than an unsigned 8-bit integer. This function is also available under the `writeUint8` alias. ```mjs -import { Buffer } from 'buffer'; +import { Buffer } from 'node:buffer'; const buf = Buffer.allocUnsafe(4); @@ -4541,7 +4541,7 @@ console.log(buf); ``` ```cjs -const { Buffer } = require('buffer'); +const { Buffer } = require('node:buffer'); const buf = Buffer.allocUnsafe(4); @@ -4582,7 +4582,7 @@ is anything other than an unsigned 16-bit integer. This function is also available under the `writeUint16BE` alias. ```mjs -import { Buffer } from 'buffer'; +import { Buffer } from 'node:buffer'; const buf = Buffer.allocUnsafe(4); @@ -4594,7 +4594,7 @@ console.log(buf); ``` ```cjs -const { Buffer } = require('buffer'); +const { Buffer } = require('node:buffer'); const buf = Buffer.allocUnsafe(4); @@ -4633,7 +4633,7 @@ anything other than an unsigned 16-bit integer. This function is also available under the `writeUint16LE` alias. ```mjs -import { Buffer } from 'buffer'; +import { Buffer } from 'node:buffer'; const buf = Buffer.allocUnsafe(4); @@ -4645,7 +4645,7 @@ console.log(buf); ``` ```cjs -const { Buffer } = require('buffer'); +const { Buffer } = require('node:buffer'); const buf = Buffer.allocUnsafe(4); @@ -4684,7 +4684,7 @@ is anything other than an unsigned 32-bit integer. This function is also available under the `writeUint32BE` alias. ```mjs -import { Buffer } from 'buffer'; +import { Buffer } from 'node:buffer'; const buf = Buffer.allocUnsafe(4); @@ -4695,7 +4695,7 @@ console.log(buf); ``` ```cjs -const { Buffer } = require('buffer'); +const { Buffer } = require('node:buffer'); const buf = Buffer.allocUnsafe(4); @@ -4733,7 +4733,7 @@ anything other than an unsigned 32-bit integer. This function is also available under the `writeUint32LE` alias. ```mjs -import { Buffer } from 'buffer'; +import { Buffer } from 'node:buffer'; const buf = Buffer.allocUnsafe(4); @@ -4744,7 +4744,7 @@ console.log(buf); ``` ```cjs -const { Buffer } = require('buffer'); +const { Buffer } = require('node:buffer'); const buf = Buffer.allocUnsafe(4); @@ -4784,7 +4784,7 @@ when `value` is anything other than an unsigned integer. This function is also available under the `writeUintBE` alias. ```mjs -import { Buffer } from 'buffer'; +import { Buffer } from 'node:buffer'; const buf = Buffer.allocUnsafe(6); @@ -4795,7 +4795,7 @@ console.log(buf); ``` ```cjs -const { Buffer } = require('buffer'); +const { Buffer } = require('node:buffer'); const buf = Buffer.allocUnsafe(6); @@ -4835,7 +4835,7 @@ when `value` is anything other than an unsigned integer. This function is also available under the `writeUintLE` alias. ```mjs -import { Buffer } from 'buffer'; +import { Buffer } from 'node:buffer'; const buf = Buffer.allocUnsafe(6); @@ -4846,7 +4846,7 @@ console.log(buf); ``` ```cjs -const { Buffer } = require('buffer'); +const { Buffer } = require('node:buffer'); const buf = Buffer.allocUnsafe(6); @@ -4991,11 +4991,11 @@ changes: See [`Buffer.from(string[, encoding])`][`Buffer.from(string)`]. -## `buffer` module APIs +## `node:buffer` module APIs While, the `Buffer` object is available as a global, there are additional -`Buffer`-related APIs that are available only via the `buffer` module -accessed using `require('buffer')`. +`Buffer`-related APIs that are available only via the `node:buffer` module +accessed using `require('node:buffer')`. ### `buffer.atob(data)` @@ -5116,7 +5116,7 @@ The transcoding process will use substitution characters if a given byte sequence cannot be adequately represented in the target encoding. For instance: ```mjs -import { Buffer, transcode } from 'buffer'; +import { Buffer, transcode } from 'node:buffer'; const newBuf = transcode(Buffer.from('€'), 'utf8', 'ascii'); console.log(newBuf.toString('ascii')); @@ -5124,7 +5124,7 @@ console.log(newBuf.toString('ascii')); ``` ```cjs -const { Buffer, transcode } = require('buffer'); +const { Buffer, transcode } = require('node:buffer'); const newBuf = transcode(Buffer.from('€'), 'utf8', 'ascii'); console.log(newBuf.toString('ascii')); diff --git a/doc/api/child_process.md b/doc/api/child_process.md index f2ddbfee457921..2cb65860ae3715 100644 --- a/doc/api/child_process.md +++ b/doc/api/child_process.md @@ -6,12 +6,12 @@ -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); @@ -196,7 +196,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 @@ -224,7 +224,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}`); @@ -250,8 +250,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'); @@ -266,7 +266,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) => { @@ -332,7 +332,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; @@ -356,8 +356,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); @@ -374,7 +374,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) => { @@ -493,7 +493,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 }); @@ -604,7 +604,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) => { @@ -623,7 +623,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']); @@ -660,7 +660,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) => { @@ -681,7 +681,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 }); @@ -724,7 +724,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, @@ -737,8 +737,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'); @@ -830,7 +830,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' }); @@ -1123,7 +1123,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) => { @@ -1317,7 +1317,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) => { @@ -1351,7 +1351,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', @@ -1396,7 +1396,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}`); @@ -1414,7 +1414,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, @@ -1464,7 +1464,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) => { @@ -1522,10 +1522,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'); }); @@ -1549,11 +1549,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 @@ -1562,13 +1562,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... @@ -1693,9 +1693,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: [ @@ -1735,7 +1735,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'); @@ -1761,7 +1761,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, @@ -1802,7 +1802,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. diff --git a/doc/api/cli.md b/doc/api/cli.md index e844881b1899f9..88fde012bef4f4 100644 --- a/doc/api/cli.md +++ b/doc/api/cli.md @@ -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` @@ -361,7 +361,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` diff --git a/doc/api/cluster.md b/doc/api/cluster.md index 242294753c5c09..11c2292123e800 100644 --- a/doc/api/cluster.md +++ b/doc/api/cluster.md @@ -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`); @@ -987,7 +987,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', @@ -1003,7 +1003,7 @@ cluster.fork(); // http worker ``` ```cjs -const cluster = require('cluster'); +const cluster = require('node:cluster'); cluster.setupPrimary({ exec: 'worker.js', @@ -1031,7 +1031,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'); @@ -1043,7 +1043,7 @@ if (cluster.isPrimary) { ``` ```cjs -const cluster = require('cluster'); +const cluster = require('node:cluster'); if (cluster.isPrimary) { console.log('I am primary'); @@ -1072,7 +1072,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'); @@ -1080,7 +1080,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'); diff --git a/doc/api/console.md b/doc/api/console.md index 335d6b767b4b44..1818d6f776b9f5 100644 --- a/doc/api/console.md +++ b/doc/api/console.md @@ -6,8 +6,8 @@ -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: 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 diff --git a/doc/api/crypto.md b/doc/api/crypto.md index b25a2aebe0dc55..7924ba2900034a 100644 --- a/doc/api/crypto.md +++ b/doc/api/crypto.md @@ -6,11 +6,12 @@ -The `crypto` module provides cryptographic functionality that includes a set of -wrappers for OpenSSL's hash, HMAC, cipher, decipher, sign, and verify functions. +The `node:crypto` module provides cryptographic functionality that includes a +set of wrappers for OpenSSL's hash, HMAC, cipher, decipher, sign, and verify +functions. ```mjs -const { createHmac } = await import('crypto'); +const { createHmac } = await import('node:crypto'); const secret = 'abcdefg'; const hash = createHmac('sha256', secret) @@ -22,7 +23,7 @@ console.log(hash); ``` ```cjs -const crypto = require('crypto'); +const crypto = require('node:crypto'); const secret = 'abcdefg'; const hash = crypto.createHmac('sha256', secret) @@ -36,8 +37,8 @@ console.log(hash); ## 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 `crypto` or -calling `require('crypto')` will result in an error being thrown. +`node:crypto` module. In such cases, attempting to `import` from `crypto` or +calling `require('node:crypto')` will result in an error being thrown. When using CommonJS, the error thrown can be caught using try/catch: @@ -46,7 +47,7 @@ When using CommonJS, the error thrown can be caught using try/catch: ```cjs let crypto; try { - crypto = require('crypto'); + crypto = require('node:crypto'); } catch (err) { console.log('crypto support is disabled!'); } @@ -64,7 +65,7 @@ of Node.js where crypto support is not enabled, consider using the ```mjs let crypto; try { - crypto = await import('crypto'); + crypto = await import('node:crypto'); } catch (err) { console.log('crypto support is disabled!'); } @@ -82,7 +83,7 @@ Netscape and was specified formally as part of [HTML5's `keygen` element][]. `` is deprecated since [HTML 5.2][] and new projects should not use this element anymore. -The `crypto` module provides the `Certificate` class for working with SPKAC +The `node:crypto` module provides the `Certificate` class for working with SPKAC data. The most common usage is handling output generated by the HTML5 `` element. Node.js uses [OpenSSL's SPKAC implementation][] internally. @@ -103,7 +104,7 @@ changes: includes a public key and a challenge. ```mjs -const { Certificate } = await import('crypto'); +const { Certificate } = await import('node:crypto'); const spkac = getSpkacSomehow(); const challenge = Certificate.exportChallenge(spkac); console.log(challenge.toString('utf8')); @@ -111,7 +112,7 @@ console.log(challenge.toString('utf8')); ``` ```cjs -const { Certificate } = require('crypto'); +const { Certificate } = require('node:crypto'); const spkac = getSpkacSomehow(); const challenge = Certificate.exportChallenge(spkac); console.log(challenge.toString('utf8')); @@ -135,7 +136,7 @@ changes: which includes a public key and a challenge. ```mjs -const { Certificate } = await import('crypto'); +const { Certificate } = await import('node:crypto'); const spkac = getSpkacSomehow(); const publicKey = Certificate.exportPublicKey(spkac); console.log(publicKey); @@ -143,7 +144,7 @@ console.log(publicKey); ``` ```cjs -const { Certificate } = require('crypto'); +const { Certificate } = require('node:crypto'); const spkac = getSpkacSomehow(); const publicKey = Certificate.exportPublicKey(spkac); console.log(publicKey); @@ -168,8 +169,8 @@ changes: `false` otherwise. ```mjs -import { Buffer } from 'buffer'; -const { Certificate } = await import('crypto'); +import { Buffer } from 'node:buffer'; +const { Certificate } = await import('node:crypto'); const spkac = getSpkacSomehow(); console.log(Certificate.verifySpkac(Buffer.from(spkac))); @@ -177,8 +178,8 @@ console.log(Certificate.verifySpkac(Buffer.from(spkac))); ``` ```cjs -const { Certificate } = require('crypto'); -const { Buffer } = require('buffer'); +const { Certificate } = require('node:crypto'); +const { Buffer } = require('node:buffer'); const spkac = getSpkacSomehow(); console.log(Certificate.verifySpkac(Buffer.from(spkac))); @@ -198,14 +199,14 @@ Instances of the `Certificate` class can be created using the `new` keyword or by calling `crypto.Certificate()` as a function: ```mjs -const { Certificate } = await import('crypto'); +const { Certificate } = await import('node:crypto'); const cert1 = new Certificate(); const cert2 = Certificate(); ``` ```cjs -const { Certificate } = require('crypto'); +const { Certificate } = require('node:crypto'); const cert1 = new Certificate(); const cert2 = Certificate(); @@ -223,7 +224,7 @@ added: v0.11.8 includes a public key and a challenge. ```mjs -const { Certificate } = await import('crypto'); +const { Certificate } = await import('node:crypto'); const cert = Certificate(); const spkac = getSpkacSomehow(); const challenge = cert.exportChallenge(spkac); @@ -232,7 +233,7 @@ console.log(challenge.toString('utf8')); ``` ```cjs -const { Certificate } = require('crypto'); +const { Certificate } = require('node:crypto'); const cert = Certificate(); const spkac = getSpkacSomehow(); const challenge = cert.exportChallenge(spkac); @@ -252,7 +253,7 @@ added: v0.11.8 which includes a public key and a challenge. ```mjs -const { Certificate } = await import('crypto'); +const { Certificate } = await import('node:crypto'); const cert = Certificate(); const spkac = getSpkacSomehow(); const publicKey = cert.exportPublicKey(spkac); @@ -261,7 +262,7 @@ console.log(publicKey); ``` ```cjs -const { Certificate } = require('crypto'); +const { Certificate } = require('node:crypto'); const cert = Certificate(); const spkac = getSpkacSomehow(); const publicKey = cert.exportPublicKey(spkac); @@ -281,8 +282,8 @@ added: v0.11.8 `false` otherwise. ```mjs -import { Buffer } from 'buffer'; -const { Certificate } = await import('crypto'); +import { Buffer } from 'node:buffer'; +const { Certificate } = await import('node:crypto'); const cert = Certificate(); const spkac = getSpkacSomehow(); @@ -291,8 +292,8 @@ console.log(cert.verifySpkac(Buffer.from(spkac))); ``` ```cjs -const { Certificate } = require('crypto'); -const { Buffer } = require('buffer'); +const { Certificate } = require('node:crypto'); +const { Buffer } = require('node:buffer'); const cert = Certificate(); const spkac = getSpkacSomehow(); @@ -327,7 +328,7 @@ const { scrypt, randomFill, createCipheriv -} = await import('crypto'); +} = await import('node:crypto'); const algorithm = 'aes-192-cbc'; const password = 'Password used to generate key'; @@ -360,7 +361,7 @@ const { scrypt, randomFill, createCipheriv -} = require('crypto'); +} = require('node:crypto'); const algorithm = 'aes-192-cbc'; const password = 'Password used to generate key'; @@ -404,7 +405,7 @@ const { scrypt, randomFill, createCipheriv -} = await import('crypto'); +} = await import('node:crypto'); const algorithm = 'aes-192-cbc'; const password = 'Password used to generate key'; @@ -433,17 +434,17 @@ scrypt(password, 'salt', 24, (err, key) => { const { createReadStream, createWriteStream, -} = require('fs'); +} = require('node:fs'); const { pipeline -} = require('stream'); +} = require('node:stream'); const { scrypt, randomFill, createCipheriv, -} = require('crypto'); +} = require('node:crypto'); const algorithm = 'aes-192-cbc'; const password = 'Password used to generate key'; @@ -475,7 +476,7 @@ const { scrypt, randomFill, createCipheriv -} = await import('crypto'); +} = await import('node:crypto'); const algorithm = 'aes-192-cbc'; const password = 'Password used to generate key'; @@ -502,7 +503,7 @@ const { scrypt, randomFill, createCipheriv, -} = require('crypto'); +} = require('node:crypto'); const algorithm = 'aes-192-cbc'; const password = 'Password used to generate key'; @@ -655,11 +656,11 @@ directly using the `new` keyword. Example: Using `Decipher` objects as streams: ```mjs -import { Buffer } from 'buffer'; +import { Buffer } from 'node:buffer'; const { scryptSync, createDecipheriv -} = await import('crypto'); +} = await import('node:crypto'); const algorithm = 'aes-192-cbc'; const password = 'Password used to generate key'; @@ -694,8 +695,8 @@ decipher.end(); const { scryptSync, createDecipheriv, -} = require('crypto'); -const { Buffer } = require('buffer'); +} = require('node:crypto'); +const { Buffer } = require('node:buffer'); const algorithm = 'aes-192-cbc'; const password = 'Password used to generate key'; @@ -733,11 +734,11 @@ import { createReadStream, createWriteStream, } from 'fs'; -import { Buffer } from 'buffer'; +import { Buffer } from 'node:buffer'; const { scryptSync, createDecipheriv -} = await import('crypto'); +} = await import('node:crypto'); const algorithm = 'aes-192-cbc'; const password = 'Password used to generate key'; @@ -758,12 +759,12 @@ input.pipe(decipher).pipe(output); const { createReadStream, createWriteStream, -} = require('fs'); +} = require('node:fs'); const { scryptSync, createDecipheriv, -} = require('crypto'); -const { Buffer } = require('buffer'); +} = require('node:crypto'); +const { Buffer } = require('node:buffer'); const algorithm = 'aes-192-cbc'; const password = 'Password used to generate key'; @@ -783,11 +784,11 @@ input.pipe(decipher).pipe(output); Example: Using the [`decipher.update()`][] and [`decipher.final()`][] methods: ```mjs -import { Buffer } from 'buffer'; +import { Buffer } from 'node:buffer'; const { scryptSync, createDecipheriv -} = await import('crypto'); +} = await import('node:crypto'); const algorithm = 'aes-192-cbc'; const password = 'Password used to generate key'; @@ -811,8 +812,8 @@ console.log(decrypted); const { scryptSync, createDecipheriv, -} = require('crypto'); -const { Buffer } = require('buffer'); +} = require('node:crypto'); +const { Buffer } = require('node:buffer'); const algorithm = 'aes-192-cbc'; const password = 'Password used to generate key'; @@ -981,11 +982,11 @@ Instances of the `DiffieHellman` class can be created using the [`crypto.createDiffieHellman()`][] function. ```mjs -import assert from 'assert'; +import assert from 'node:assert'; const { createDiffieHellman -} = await import('crypto'); +} = await import('node:crypto'); // Generate Alice's keys... const alice = createDiffieHellman(2048); @@ -1004,11 +1005,11 @@ assert.strictEqual(aliceSecret.toString('hex'), bobSecret.toString('hex')); ``` ```cjs -const assert = require('assert'); +const assert = require('node:assert'); const { createDiffieHellman, -} = require('crypto'); +} = require('node:crypto'); // Generate Alice's keys... const alice = createDiffieHellman(2048); @@ -1152,8 +1153,7 @@ added: v0.11.12 A bit field containing any warnings and/or errors resulting from a check performed during initialization of the `DiffieHellman` object. -The following values are valid for this property (as defined in `constants` -module): +The following values are valid for this property (as defined in `node:constants` module): * `DH_CHECK_P_NOT_SAFE_PRIME` * `DH_CHECK_P_NOT_PRIME` @@ -1172,12 +1172,12 @@ its keys after creation. In other words, it does not implement `setPublicKey()` or `setPrivateKey()` methods. ```mjs -const { createDiffieHellmanGroup } = await import('crypto'); +const { createDiffieHellmanGroup } = await import('node:crypto'); const dh = createDiffieHellmanGroup('modp1'); ``` ```cjs -const { createDiffieHellmanGroup } = require('crypto'); +const { createDiffieHellmanGroup } = require('node:crypto'); const dh = createDiffieHellmanGroup('modp1'); ``` @@ -1209,11 +1209,11 @@ Instances of the `ECDH` class can be created using the [`crypto.createECDH()`][] function. ```mjs -import assert from 'assert'; +import assert from 'node:assert'; const { createECDH -} = await import('crypto'); +} = await import('node:crypto'); // Generate Alice's keys... const alice = createECDH('secp521r1'); @@ -1232,11 +1232,11 @@ assert.strictEqual(aliceSecret.toString('hex'), bobSecret.toString('hex')); ``` ```cjs -const assert = require('assert'); +const assert = require('node:assert'); const { createECDH, -} = require('crypto'); +} = require('node:crypto'); // Generate Alice's keys... const alice = createECDH('secp521r1'); @@ -1289,7 +1289,7 @@ Example (uncompressing a key): const { createECDH, ECDH -} = await import('crypto'); +} = await import('node:crypto'); const ecdh = createECDH('secp256k1'); ecdh.generateKeys(); @@ -1310,7 +1310,7 @@ console.log(uncompressedKey === ecdh.getPublicKey('hex')); const { createECDH, ECDH, -} = require('crypto'); +} = require('node:crypto'); const ecdh = createECDH('secp256k1'); ecdh.generateKeys(); @@ -1461,7 +1461,7 @@ Example (obtaining a shared secret): const { createECDH, createHash -} = await import('crypto'); +} = await import('node:crypto'); const alice = createECDH('secp256k1'); const bob = createECDH('secp256k1'); @@ -1488,7 +1488,7 @@ console.log(aliceSecret === bobSecret); const { createECDH, createHash, -} = require('crypto'); +} = require('node:crypto'); const alice = createECDH('secp256k1'); const bob = createECDH('secp256k1'); @@ -1535,7 +1535,7 @@ Example: Using `Hash` objects as streams: ```mjs const { createHash -} = await import('crypto'); +} = await import('node:crypto'); const hash = createHash('sha256'); @@ -1557,7 +1557,7 @@ hash.end(); ```cjs const { createHash, -} = require('crypto'); +} = require('node:crypto'); const hash = createHash('sha256'); @@ -1579,9 +1579,9 @@ hash.end(); Example: Using `Hash` and piped streams: ```mjs -import { createReadStream } from 'fs'; -import { stdout } from 'process'; -const { createHash } = await import('crypto'); +import { createReadStream } from 'node:fs'; +import { stdout } from 'node:process'; +const { createHash } = await import('node:crypto'); const hash = createHash('sha256'); @@ -1590,9 +1590,9 @@ input.pipe(hash).setEncoding('hex').pipe(stdout); ``` ```cjs -const { createReadStream } = require('fs'); -const { createHash } = require('crypto'); -const { stdout } = require('process'); +const { createReadStream } = require('node:fs'); +const { createHash } = require('node:crypto'); +const { stdout } = require('node:process'); const hash = createHash('sha256'); @@ -1605,7 +1605,7 @@ Example: Using the [`hash.update()`][] and [`hash.digest()`][] methods: ```mjs const { createHash -} = await import('crypto'); +} = await import('node:crypto'); const hash = createHash('sha256'); @@ -1618,7 +1618,7 @@ console.log(hash.digest('hex')); ```cjs const { createHash, -} = require('crypto'); +} = require('node:crypto'); const hash = createHash('sha256'); @@ -1651,7 +1651,7 @@ its [`hash.digest()`][] method has been called. // Calculate a rolling hash. const { createHash -} = await import('crypto'); +} = await import('node:crypto'); const hash = createHash('sha256'); @@ -1671,7 +1671,7 @@ console.log(hash.copy().digest('hex')); // Calculate a rolling hash. const { createHash, -} = require('crypto'); +} = require('node:crypto'); const hash = createHash('sha256'); @@ -1749,7 +1749,7 @@ Example: Using `Hmac` objects as streams: ```mjs const { createHmac -} = await import('crypto'); +} = await import('node:crypto'); const hmac = createHmac('sha256', 'a secret'); @@ -1771,7 +1771,7 @@ hmac.end(); ```cjs const { createHmac, -} = require('crypto'); +} = require('node:crypto'); const hmac = createHmac('sha256', 'a secret'); @@ -1793,11 +1793,11 @@ hmac.end(); Example: Using `Hmac` and piped streams: ```mjs -import { createReadStream } from 'fs'; -import { stdout } from 'process'; +import { createReadStream } from 'node:fs'; +import { stdout } from 'node:process'; const { createHmac -} = await import('crypto'); +} = await import('node:crypto'); const hmac = createHmac('sha256', 'a secret'); @@ -1808,11 +1808,11 @@ input.pipe(hmac).pipe(stdout); ```cjs const { createReadStream, -} = require('fs'); +} = require('node:fs'); const { createHmac, -} = require('crypto'); -const { stdout } = require('process'); +} = require('node:crypto'); +const { stdout } = require('node:process'); const hmac = createHmac('sha256', 'a secret'); @@ -1825,7 +1825,7 @@ Example: Using the [`hmac.update()`][] and [`hmac.digest()`][] methods: ```mjs const { createHmac -} = await import('crypto'); +} = await import('node:crypto'); const hmac = createHmac('sha256', 'a secret'); @@ -1838,7 +1838,7 @@ console.log(hmac.digest('hex')); ```cjs const { createHmac, -} = require('crypto'); +} = require('node:crypto'); const hmac = createHmac('sha256', 'a secret'); @@ -1927,7 +1927,7 @@ added: v15.0.0 Example: Converting a `CryptoKey` instance to a `KeyObject`: ```mjs -const { webcrypto, KeyObject } = await import('crypto'); +const { webcrypto, KeyObject } = await import('node:crypto'); const { subtle } = webcrypto; const key = await subtle.generateKey({ @@ -1947,7 +1947,7 @@ const { subtle, }, KeyObject, -} = require('crypto'); +} = require('node:crypto'); (async function() { const key = await subtle.generateKey({ @@ -2151,7 +2151,7 @@ const { generateKeyPairSync, createSign, createVerify -} = await import('crypto'); +} = await import('node:crypto'); const { privateKey, publicKey } = generateKeyPairSync('ec', { namedCurve: 'sect239k1' @@ -2174,7 +2174,7 @@ const { generateKeyPairSync, createSign, createVerify, -} = require('crypto'); +} = require('node:crypto'); const { privateKey, publicKey } = generateKeyPairSync('ec', { namedCurve: 'sect239k1' @@ -2199,7 +2199,7 @@ const { generateKeyPairSync, createSign, createVerify -} = await import('crypto'); +} = await import('node:crypto'); const { privateKey, publicKey } = generateKeyPairSync('rsa', { modulusLength: 2048, @@ -2222,7 +2222,7 @@ const { generateKeyPairSync, createSign, createVerify, -} = require('crypto'); +} = require('node:crypto'); const { privateKey, publicKey } = generateKeyPairSync('rsa', { modulusLength: 2048, @@ -2455,7 +2455,7 @@ Encapsulates an X509 certificate and provides read-only access to its information. ```mjs -const { X509Certificate } = await import('crypto'); +const { X509Certificate } = await import('node:crypto'); const x509 = new X509Certificate('{... pem encoded cert ...}'); @@ -2463,7 +2463,7 @@ console.log(x509.subject); ``` ```cjs -const { X509Certificate } = require('crypto'); +const { X509Certificate } = require('node:crypto'); const x509 = new X509Certificate('{... pem encoded cert ...}'); @@ -2847,7 +2847,7 @@ added: v15.6.0 Verifies that this certificate was signed by the given public key. Does not perform any other validation checks on the certificate. -## `crypto` module methods and properties +## `node:crypto` module methods and properties ### `crypto.constants` @@ -3292,10 +3292,10 @@ Example: generating the sha256 sum of a file import { createReadStream } from 'fs'; -import { argv } from 'process'; +import { argv } from 'node:process'; const { createHash -} = await import('crypto'); +} = await import('node:crypto'); const filename = argv[2]; @@ -3317,11 +3317,11 @@ input.on('readable', () => { ```cjs const { createReadStream, -} = require('fs'); +} = require('node:fs'); const { createHash, -} = require('crypto'); -const { argv } = require('process'); +} = require('node:crypto'); +const { argv } = require('node:process'); const filename = argv[2]; @@ -3378,10 +3378,10 @@ Example: generating the sha256 HMAC of a file import { createReadStream } from 'fs'; -import { argv } from 'process'; +import { argv } from 'node:process'; const { createHmac -} = await import('crypto'); +} = await import('node:crypto'); const filename = argv[2]; @@ -3403,11 +3403,11 @@ input.on('readable', () => { ```cjs const { createReadStream, -} = require('fs'); +} = require('node:fs'); const { createHmac, -} = require('crypto'); -const { argv } = require('process'); +} = require('node:crypto'); +const { argv } = require('node:process'); const filename = argv[2]; @@ -3614,7 +3614,7 @@ Asynchronously generates a new random secret key of the given `length`. The ```mjs const { generateKey -} = await import('crypto'); +} = await import('node:crypto'); generateKey('hmac', { length: 64 }, (err, key) => { if (err) throw err; @@ -3625,7 +3625,7 @@ generateKey('hmac', { length: 64 }, (err, key) => { ```cjs const { generateKey, -} = require('crypto'); +} = require('node:crypto'); generateKey('hmac', { length: 64 }, (err, key) => { if (err) throw err; @@ -3698,7 +3698,7 @@ It is recommended to encode public keys as `'spki'` and private keys as ```mjs const { generateKeyPair -} = await import('crypto'); +} = await import('node:crypto'); generateKeyPair('rsa', { modulusLength: 4096, @@ -3720,7 +3720,7 @@ generateKeyPair('rsa', { ```cjs const { generateKeyPair, -} = require('crypto'); +} = require('node:crypto'); generateKeyPair('rsa', { modulusLength: 4096, @@ -3810,7 +3810,7 @@ and to keep the passphrase confidential. ```mjs const { generateKeyPairSync -} = await import('crypto'); +} = await import('node:crypto'); const { publicKey, @@ -3833,7 +3833,7 @@ const { ```cjs const { generateKeyPairSync, -} = require('crypto'); +} = require('node:crypto'); const { publicKey, @@ -3879,7 +3879,7 @@ Synchronously generates a new random secret key of the given `length`. The ```mjs const { generateKeySync -} = await import('crypto'); +} = await import('node:crypto'); const key = generateKeySync('hmac', { length: 64 }); console.log(key.export().toString('hex')); // e89..........41e @@ -3888,7 +3888,7 @@ console.log(key.export().toString('hex')); // e89..........41e ```cjs const { generateKeySync, -} = require('crypto'); +} = require('node:crypto'); const key = generateKeySync('hmac', { length: 64 }); console.log(key.export().toString('hex')); // e89..........41e @@ -4020,7 +4020,7 @@ added: v0.9.3 ```mjs const { getCiphers -} = await import('crypto'); +} = await import('node:crypto'); console.log(getCiphers()); // ['aes-128-cbc', 'aes-128-ccm', ...] ``` @@ -4028,7 +4028,7 @@ console.log(getCiphers()); // ['aes-128-cbc', 'aes-128-ccm', ...] ```cjs const { getCiphers, -} = require('crypto'); +} = require('node:crypto'); console.log(getCiphers()); // ['aes-128-cbc', 'aes-128-ccm', ...] ``` @@ -4044,7 +4044,7 @@ added: v2.3.0 ```mjs const { getCurves -} = await import('crypto'); +} = await import('node:crypto'); console.log(getCurves()); // ['Oakley-EC2N-3', 'Oakley-EC2N-4', ...] ``` @@ -4052,7 +4052,7 @@ console.log(getCurves()); // ['Oakley-EC2N-3', 'Oakley-EC2N-4', ...] ```cjs const { getCurves, -} = require('crypto'); +} = require('node:crypto'); console.log(getCurves()); // ['Oakley-EC2N-3', 'Oakley-EC2N-4', ...] ``` @@ -4082,7 +4082,7 @@ Example (obtaining a shared secret): ```mjs const { getDiffieHellman -} = await import('crypto'); +} = await import('node:crypto'); const alice = getDiffieHellman('modp14'); const bob = getDiffieHellman('modp14'); @@ -4099,7 +4099,7 @@ console.log(aliceSecret === bobSecret); ```cjs const { getDiffieHellman, -} = require('crypto'); +} = require('node:crypto'); const alice = getDiffieHellman('modp14'); const bob = getDiffieHellman('modp14'); @@ -4136,7 +4136,7 @@ added: v0.9.3 ```mjs const { getHashes -} = await import('crypto'); +} = await import('node:crypto'); console.log(getHashes()); // ['DSA', 'DSA-SHA', 'DSA-SHA1', ...] ``` @@ -4144,7 +4144,7 @@ console.log(getHashes()); // ['DSA', 'DSA-SHA', 'DSA-SHA1', ...] ```cjs const { getHashes, -} = require('crypto'); +} = require('node:crypto'); console.log(getHashes()); // ['DSA', 'DSA-SHA', 'DSA-SHA1', ...] ``` @@ -4180,10 +4180,10 @@ be passed to the callback as an {ArrayBuffer}. An error will be thrown if any of the input arguments specify invalid values or types. ```mjs -import { Buffer } from 'buffer'; +import { Buffer } from 'node:buffer'; const { hkdf -} = await import('crypto'); +} = await import('node:crypto'); hkdf('sha512', 'key', 'salt', 'info', 64, (err, derivedKey) => { if (err) throw err; @@ -4194,8 +4194,8 @@ hkdf('sha512', 'key', 'salt', 'info', 64, (err, derivedKey) => { ```cjs const { hkdf, -} = require('crypto'); -const { Buffer } = require('buffer'); +} = require('node:crypto'); +const { Buffer } = require('node:buffer'); hkdf('sha512', 'key', 'salt', 'info', 64, (err, derivedKey) => { if (err) throw err; @@ -4232,10 +4232,10 @@ An error will be thrown if any of the input arguments specify invalid values or types, or if the derived key cannot be generated. ```mjs -import { Buffer } from 'buffer'; +import { Buffer } from 'node:buffer'; const { hkdfSync -} = await import('crypto'); +} = await import('node:crypto'); const derivedKey = hkdfSync('sha512', 'key', 'salt', 'info', 64); console.log(Buffer.from(derivedKey).toString('hex')); // '24156e2...5391653' @@ -4244,8 +4244,8 @@ console.log(Buffer.from(derivedKey).toString('hex')); // '24156e2...5391653' ```cjs const { hkdfSync, -} = require('crypto'); -const { Buffer } = require('buffer'); +} = require('node:crypto'); +const { Buffer } = require('node:buffer'); const derivedKey = hkdfSync('sha512', 'key', 'salt', 'info', 64); console.log(Buffer.from(derivedKey).toString('hex')); // '24156e2...5391653' @@ -4313,7 +4313,7 @@ When passing strings for `password` or `salt`, please consider ```mjs const { pbkdf2 -} = await import('crypto'); +} = await import('node:crypto'); pbkdf2('secret', 'salt', 100000, 64, 'sha512', (err, derivedKey) => { if (err) throw err; @@ -4324,7 +4324,7 @@ pbkdf2('secret', 'salt', 100000, 64, 'sha512', (err, derivedKey) => { ```cjs const { pbkdf2, -} = require('crypto'); +} = require('node:crypto'); pbkdf2('secret', 'salt', 100000, 64, 'sha512', (err, derivedKey) => { if (err) throw err; @@ -4337,7 +4337,7 @@ The `crypto.DEFAULT_ENCODING` property can be used to change the way the deprecated and use should be avoided. ```mjs -import crypto from 'crypto'; +import crypto from 'node:crypto'; crypto.DEFAULT_ENCODING = 'hex'; crypto.pbkdf2('secret', 'salt', 100000, 512, 'sha512', (err, derivedKey) => { if (err) throw err; @@ -4346,7 +4346,7 @@ crypto.pbkdf2('secret', 'salt', 100000, 512, 'sha512', (err, derivedKey) => { ``` ```cjs -const crypto = require('crypto'); +const crypto = require('node:crypto'); crypto.DEFAULT_ENCODING = 'hex'; crypto.pbkdf2('secret', 'salt', 100000, 512, 'sha512', (err, derivedKey) => { if (err) throw err; @@ -4411,7 +4411,7 @@ When passing strings for `password` or `salt`, please consider ```mjs const { pbkdf2Sync -} = await import('crypto'); +} = await import('node:crypto'); const key = pbkdf2Sync('secret', 'salt', 100000, 64, 'sha512'); console.log(key.toString('hex')); // '3745e48...08d59ae' @@ -4420,7 +4420,7 @@ console.log(key.toString('hex')); // '3745e48...08d59ae' ```cjs const { pbkdf2Sync, -} = require('crypto'); +} = require('node:crypto'); const key = pbkdf2Sync('secret', 'salt', 100000, 64, 'sha512'); console.log(key.toString('hex')); // '3745e48...08d59ae' @@ -4431,14 +4431,14 @@ The `crypto.DEFAULT_ENCODING` property may be used to change the way the should be avoided. ```mjs -import crypto from 'crypto'; +import crypto from 'node:crypto'; crypto.DEFAULT_ENCODING = 'hex'; const key = crypto.pbkdf2Sync('secret', 'salt', 100000, 512, 'sha512'); console.log(key); // '3745e48...aa39b34' ``` ```cjs -const crypto = require('crypto'); +const crypto = require('node:crypto'); crypto.DEFAULT_ENCODING = 'hex'; const key = crypto.pbkdf2Sync('secret', 'salt', 100000, 512, 'sha512'); console.log(key); // '3745e48...aa39b34' @@ -4662,7 +4662,7 @@ If an error occurs, `err` will be an `Error` object; otherwise it is `null`. The // Asynchronous const { randomBytes -} = await import('crypto'); +} = await import('node:crypto'); randomBytes(256, (err, buf) => { if (err) throw err; @@ -4674,7 +4674,7 @@ randomBytes(256, (err, buf) => { // Asynchronous const { randomBytes, -} = require('crypto'); +} = require('node:crypto'); randomBytes(256, (err, buf) => { if (err) throw err; @@ -4690,7 +4690,7 @@ there is a problem generating the bytes. // Synchronous const { randomBytes -} = await import('crypto'); +} = await import('node:crypto'); const buf = randomBytes(256); console.log( @@ -4701,7 +4701,7 @@ console.log( // Synchronous const { randomBytes, -} = require('crypto'); +} = require('node:crypto'); const buf = randomBytes(256); console.log( @@ -4746,8 +4746,8 @@ changes: Synchronous version of [`crypto.randomFill()`][]. ```mjs -import { Buffer } from 'buffer'; -const { randomFillSync } = await import('crypto'); +import { Buffer } from 'node:buffer'; +const { randomFillSync } = await import('node:crypto'); const buf = Buffer.alloc(10); console.log(randomFillSync(buf).toString('hex')); @@ -4761,8 +4761,8 @@ console.log(buf.toString('hex')); ``` ```cjs -const { randomFillSync } = require('crypto'); -const { Buffer } = require('buffer'); +const { randomFillSync } = require('node:crypto'); +const { Buffer } = require('node:buffer'); const buf = Buffer.alloc(10); console.log(randomFillSync(buf).toString('hex')); @@ -4779,8 +4779,8 @@ Any `ArrayBuffer`, `TypedArray` or `DataView` instance may be passed as `buffer`. ```mjs -import { Buffer } from 'buffer'; -const { randomFillSync } = await import('crypto'); +import { Buffer } from 'node:buffer'; +const { randomFillSync } = await import('node:crypto'); const a = new Uint32Array(10); console.log(Buffer.from(randomFillSync(a).buffer, @@ -4795,8 +4795,8 @@ console.log(Buffer.from(randomFillSync(c)).toString('hex')); ``` ```cjs -const { randomFillSync } = require('crypto'); -const { Buffer } = require('buffer'); +const { randomFillSync } = require('node:crypto'); +const { Buffer } = require('node:buffer'); const a = new Uint32Array(10); console.log(Buffer.from(randomFillSync(a).buffer, @@ -4836,8 +4836,8 @@ requires that a callback is passed in. If the `callback` function is not provided, an error will be thrown. ```mjs -import { Buffer } from 'buffer'; -const { randomFill } = await import('crypto'); +import { Buffer } from 'node:buffer'; +const { randomFill } = await import('node:crypto'); const buf = Buffer.alloc(10); randomFill(buf, (err, buf) => { @@ -4858,8 +4858,8 @@ randomFill(buf, 5, 5, (err, buf) => { ``` ```cjs -const { randomFill } = require('crypto'); -const { Buffer } = require('buffer'); +const { randomFill } = require('node:crypto'); +const { Buffer } = require('node:buffer'); const buf = Buffer.alloc(10); randomFill(buf, (err, buf) => { @@ -4889,8 +4889,8 @@ contains finite numbers only, they are not drawn from a uniform random distribution and have no meaningful lower or upper bounds. ```mjs -import { Buffer } from 'buffer'; -const { randomFill } = await import('crypto'); +import { Buffer } from 'node:buffer'; +const { randomFill } = await import('node:crypto'); const a = new Uint32Array(10); randomFill(a, (err, buf) => { @@ -4914,8 +4914,8 @@ randomFill(c, (err, buf) => { ``` ```cjs -const { randomFill } = require('crypto'); -const { Buffer } = require('buffer'); +const { randomFill } = require('node:crypto'); +const { Buffer } = require('node:buffer'); const a = new Uint32Array(10); randomFill(a, (err, buf) => { @@ -4972,7 +4972,7 @@ generated synchronously. // Asynchronous const { randomInt -} = await import('crypto'); +} = await import('node:crypto'); randomInt(3, (err, n) => { if (err) throw err; @@ -4984,7 +4984,7 @@ randomInt(3, (err, n) => { // Asynchronous const { randomInt, -} = require('crypto'); +} = require('node:crypto'); randomInt(3, (err, n) => { if (err) throw err; @@ -4996,7 +4996,7 @@ randomInt(3, (err, n) => { // Synchronous const { randomInt -} = await import('crypto'); +} = await import('node:crypto'); const n = randomInt(3); console.log(`Random number chosen from (0, 1, 2): ${n}`); @@ -5006,7 +5006,7 @@ console.log(`Random number chosen from (0, 1, 2): ${n}`); // Synchronous const { randomInt, -} = require('crypto'); +} = require('node:crypto'); const n = randomInt(3); console.log(`Random number chosen from (0, 1, 2): ${n}`); @@ -5016,7 +5016,7 @@ console.log(`Random number chosen from (0, 1, 2): ${n}`); // With `min` argument const { randomInt -} = await import('crypto'); +} = await import('node:crypto'); const n = randomInt(1, 7); console.log(`The dice rolled: ${n}`); @@ -5026,7 +5026,7 @@ console.log(`The dice rolled: ${n}`); // With `min` argument const { randomInt, -} = require('crypto'); +} = require('node:crypto'); const n = randomInt(1, 7); console.log(`The dice rolled: ${n}`); @@ -5106,7 +5106,7 @@ or types. ```mjs const { scrypt -} = await import('crypto'); +} = await import('node:crypto'); // Using the factory defaults. scrypt('password', 'salt', 64, (err, derivedKey) => { @@ -5123,7 +5123,7 @@ scrypt('password', 'salt', 64, { N: 1024 }, (err, derivedKey) => { ```cjs const { scrypt, -} = require('crypto'); +} = require('node:crypto'); // Using the factory defaults. scrypt('password', 'salt', 64, (err, derivedKey) => { @@ -5187,7 +5187,7 @@ or types. ```mjs const { scryptSync -} = await import('crypto'); +} = await import('node:crypto'); // Using the factory defaults. const key1 = scryptSync('password', 'salt', 64); @@ -5200,7 +5200,7 @@ console.log(key2.toString('hex')); // '3745e48...aa39b34' ```cjs const { scryptSync, -} = require('crypto'); +} = require('node:crypto'); // Using the factory defaults. const key1 = scryptSync('password', 'salt', 64); @@ -5489,7 +5489,7 @@ instead. ### Support for weak or compromised algorithms -The `crypto` module still supports some algorithms which are already +The `node:crypto` module still supports some algorithms which are already compromised and are not currently recommended for use. The API also allows the use of ciphers and hashes with a small key size that are too weak for safe use. @@ -5541,12 +5541,12 @@ mode must adhere to certain restrictions when using the cipher API: authentication tag. ```mjs -import { Buffer } from 'buffer'; +import { Buffer } from 'node:buffer'; const { createCipheriv, createDecipheriv, randomBytes -} = await import('crypto'); +} = await import('node:crypto'); const key = 'keykeykeykeykeykeykeykey'; const nonce = randomBytes(12); @@ -5585,12 +5585,12 @@ console.log(receivedPlaintext); ``` ```cjs -const { Buffer } = require('buffer'); +const { Buffer } = require('node:buffer'); const { createCipheriv, createDecipheriv, randomBytes, -} = require('crypto'); +} = require('node:crypto'); const key = 'keykeykeykeykeykeykeykey'; const nonce = randomBytes(12); @@ -5631,7 +5631,8 @@ console.log(receivedPlaintext); ## Crypto constants The following constants exported by `crypto.constants` apply to various uses of -the `crypto`, `tls`, and `https` modules and are generally specific to OpenSSL. +the `node:crypto`, `node:tls`, and `node:https` modules and are generally +specific to OpenSSL. ### OpenSSL options diff --git a/doc/api/deprecations.md b/doc/api/deprecations.md index 0789ee154a8f30..4525ffea3a1a1a 100644 --- a/doc/api/deprecations.md +++ b/doc/api/deprecations.md @@ -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')` -### DEP0089: `require('assert')` +### DEP0089: `require('node:assert')` -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) => { @@ -565,8 +565,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'); @@ -576,8 +576,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'); @@ -590,8 +590,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'); @@ -602,8 +602,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'); @@ -622,8 +622,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'); @@ -635,8 +635,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'); @@ -864,7 +864,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])` diff --git a/doc/api/diagnostics_channel.md b/doc/api/diagnostics_channel.md index b6ba9ce5b9874b..346f5e8ab96f07 100644 --- a/doc/api/diagnostics_channel.md +++ b/doc/api/diagnostics_channel.md @@ -6,17 +6,17 @@ -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'); @@ -277,7 +277,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'); @@ -291,7 +291,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'); diff --git a/doc/api/dns.md b/doc/api/dns.md index 018f62a7784560..addc4fe9d18de6 100644 --- a/doc/api/dns.md +++ b/doc/api/dns.md @@ -6,7 +6,7 @@ -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()`] @@ -230,7 +230,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, @@ -295,7 +295,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 @@ -726,7 +726,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 @@ -736,7 +736,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` @@ -752,7 +752,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']); @@ -865,7 +865,7 @@ using `dnsPromises.lookup()`. Example usage: ```js -const dns = require('dns'); +const dns = require('node:dns'); const dnsPromises = dns.promises; const options = { family: 6, @@ -905,7 +905,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 diff --git a/doc/api/domain.md b/doc/api/domain.md index 9552b3bbcd478c..d88eeef7419d8f 100644 --- a/doc/api/domain.md +++ b/doc/api/domain.md @@ -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); diff --git a/doc/api/embedding.md b/doc/api/embedding.md index a682ed33e1e425..1aabd0179e1e15 100644 --- a/doc/api/embedding.md +++ b/doc/api/embedding.md @@ -141,9 +141,9 @@ int RunNodeInstance(MultiIsolatePlatform* platform, MaybeLocal 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; diff --git a/doc/api/errors.md b/doc/api/errors.md index 3517dc63e3bd56..8905524da2928b 100644 --- a/doc/api/errors.md +++ b/doc/api/errors.md @@ -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: ```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. @@ -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. @@ -814,14 +814,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()`][]. ### `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. @@ -1152,8 +1152,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. @@ -1162,10 +1162,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. @@ -1732,7 +1732,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. @@ -1740,21 +1740,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. ### `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. ### `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. @@ -1766,14 +1766,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. ### `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. @@ -2502,7 +2502,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'); @@ -2656,8 +2656,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. @@ -3155,7 +3155,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. @@ -3394,7 +3394,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 diff --git a/doc/api/esm.md b/doc/api/esm.md index b1e9f618e56daf..98cc02028cc72b 100644 --- a/doc/api/esm.md +++ b/doc/api/esm.md @@ -112,7 +112,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: @@ -252,12 +252,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); @@ -268,9 +268,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(); @@ -300,7 +300,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)); ``` @@ -580,8 +580,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', @@ -634,7 +634,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 }); ``` @@ -943,7 +943,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; @@ -1113,7 +1113,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}" ``` diff --git a/doc/api/events.md b/doc/api/events.md index 5192b051231921..b319ec434ebfcc 100644 --- a/doc/api/events.md +++ b/doc/api/events.md @@ -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', () => {}); @@ -756,7 +756,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() { @@ -851,7 +851,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(); @@ -895,7 +895,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(); @@ -928,7 +928,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(); @@ -944,7 +944,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(); @@ -977,7 +977,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(); @@ -1004,7 +1004,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(); @@ -1069,7 +1069,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', () => {}); @@ -1092,7 +1092,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(); @@ -1121,7 +1121,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 () => { @@ -1161,7 +1161,7 @@ added: v15.4.0 const { setMaxListeners, EventEmitter -} = require('events'); +} = require('node:events'); const target = new EventTarget(); const emitter = new EventEmitter(); @@ -1180,9 +1180,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' }); diff --git a/doc/api/fs.md b/doc/api/fs.md index 80002a22888fe3..689830987b4628 100644 --- a/doc/api/fs.md +++ b/doc/api/fs.md @@ -8,27 +8,27 @@ -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 }); @@ -505,7 +505,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 { @@ -694,8 +694,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); @@ -797,8 +797,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'); @@ -1014,7 +1014,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-')); @@ -1027,7 +1027,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])` @@ -1087,7 +1087,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('./'); @@ -1129,7 +1129,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); @@ -1176,7 +1176,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(); @@ -1449,7 +1449,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; @@ -1527,8 +1527,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(); @@ -1597,7 +1597,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'; @@ -1631,7 +1631,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) { @@ -1656,7 +1656,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) { @@ -1681,7 +1681,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') { @@ -1709,7 +1709,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) { @@ -1781,7 +1781,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; @@ -1792,7 +1792,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); ``` @@ -1802,7 +1802,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) => { @@ -1855,7 +1855,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; @@ -2010,7 +2010,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; @@ -2153,7 +2153,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'); @@ -2181,7 +2181,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 }); ``` @@ -2295,7 +2295,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!'); @@ -2317,7 +2317,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) { @@ -2341,7 +2341,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') { @@ -2365,7 +2365,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) { @@ -2389,7 +2389,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) { @@ -2581,7 +2581,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) => { @@ -2839,7 +2839,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) => { @@ -2851,7 +2851,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:\'] @@ -2903,7 +2903,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; @@ -2916,11 +2916,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(); @@ -2935,7 +2935,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); @@ -3181,7 +3181,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; @@ -3197,7 +3197,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); ``` @@ -3208,7 +3208,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('', (err, data) => { @@ -3225,7 +3225,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; @@ -3463,7 +3463,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; @@ -3632,7 +3632,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']; @@ -3728,7 +3728,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); ``` @@ -3772,7 +3772,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; @@ -3781,7 +3781,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; @@ -3821,7 +3821,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; @@ -4013,7 +4013,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) { @@ -4061,7 +4061,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}`); @@ -4288,8 +4288,8 @@ If `data` is a plain object, it must have an own (not inherited) `toString` function property. ```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) => { @@ -4301,7 +4301,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); ``` @@ -4319,8 +4319,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; @@ -4341,8 +4341,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); ``` @@ -4429,7 +4429,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); @@ -4466,7 +4466,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'); @@ -4479,7 +4479,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'); ``` @@ -4489,7 +4489,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; @@ -4593,7 +4593,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'); @@ -4664,7 +4664,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.'); @@ -5050,7 +5050,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(''); @@ -5567,7 +5567,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('./'); @@ -5838,7 +5838,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) { @@ -6520,7 +6520,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, @@ -6830,7 +6830,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'; @@ -6845,7 +6845,7 @@ try { ``` ```cjs -const { rename, stat } = require('fs/promises'); +const { rename, stat } = require('node:fs/promises'); (async function(from, to) { try { @@ -6862,7 +6862,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; @@ -6874,7 +6874,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; @@ -6899,7 +6899,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 { @@ -6913,7 +6913,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 { @@ -6930,11 +6930,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')); ``` @@ -6948,7 +6948,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 @@ -6972,7 +6972,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 @@ -6989,7 +6989,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')); @@ -7007,7 +7007,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')); @@ -7027,8 +7027,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 { @@ -7068,7 +7068,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) => { @@ -7102,7 +7102,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 { diff --git a/doc/api/globals.md b/doc/api/globals.md index 55361f74574781..22c351c7779139 100644 --- a/doc/api/globals.md +++ b/doc/api/globals.md @@ -272,7 +272,7 @@ added: v16.15.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` @@ -296,7 +296,7 @@ added: v16.15.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. ## `Event` @@ -537,7 +537,7 @@ added: v16.15.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. ## `TextDecoder` diff --git a/doc/api/http.md b/doc/api/http.md index 89980f7b86cf07..8dd5f95feb20e7 100644 --- a/doc/api/http.md +++ b/doc/api/http.md @@ -6,7 +6,7 @@ -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. @@ -186,7 +186,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); @@ -464,9 +464,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) => { @@ -560,7 +560,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', @@ -638,7 +638,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) => { @@ -1002,7 +1002,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 @@ -1026,7 +1026,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() { @@ -1136,7 +1136,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', }; @@ -1303,7 +1303,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(); @@ -1947,7 +1947,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; @@ -2048,7 +2048,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. @@ -2981,7 +2981,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) => { @@ -2995,7 +2995,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(); @@ -3231,7 +3231,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!' @@ -3430,7 +3430,7 @@ Examples: Example: ```js -const { validateHeaderName } = require('http'); +const { validateHeaderName } = require('node:http'); try { validateHeaderName(''); @@ -3464,7 +3464,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); diff --git a/doc/api/http2.md b/doc/api/http2.md index 3c82d0fb3b32cc..d9faae3a580df5 100644 --- a/doc/api/http2.md +++ b/doc/api/http2.md @@ -21,25 +21,25 @@ changes: -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!'); } @@ -57,7 +57,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!'); } @@ -83,8 +83,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'), @@ -116,8 +116,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') }); @@ -318,7 +318,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']; @@ -338,7 +338,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(); @@ -597,7 +597,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; @@ -741,7 +741,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) => { @@ -807,7 +807,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) => { @@ -834,7 +834,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); @@ -868,7 +868,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) => { @@ -892,7 +892,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) => { @@ -945,7 +945,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, @@ -1353,7 +1353,7 @@ added: v8.4.0 * `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': '/' }); @@ -1402,7 +1402,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 }); @@ -1493,7 +1493,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) => { @@ -1573,7 +1573,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 }); @@ -1613,7 +1613,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 }); @@ -1632,7 +1632,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 }); @@ -1680,8 +1680,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) => { @@ -1725,8 +1725,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) => { @@ -1792,7 +1792,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) { @@ -1827,7 +1827,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) { @@ -1862,7 +1862,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', @@ -1883,8 +1883,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'` @@ -1977,7 +1977,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, @@ -2097,7 +2097,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'` @@ -2190,7 +2190,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, @@ -2447,7 +2447,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 @@ -2585,8 +2585,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'), @@ -2713,7 +2713,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 */ @@ -2775,7 +2775,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 }); @@ -2847,7 +2847,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']); @@ -2934,7 +2934,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`. @@ -2980,7 +2980,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'); @@ -3002,7 +3002,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 = ''; @@ -3017,9 +3017,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) => { @@ -3047,7 +3047,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'); @@ -3081,7 +3081,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 }); ``` @@ -3091,7 +3091,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) { @@ -3114,7 +3114,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'); @@ -3143,8 +3143,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'); @@ -3819,7 +3819,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; @@ -3896,7 +3896,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. @@ -4000,7 +4000,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]; diff --git a/doc/api/https.md b/doc/api/https.md index c096a6dd327d13..f8e06bd230e7e5 100644 --- a/doc/api/https.md +++ b/doc/api/https.md @@ -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); @@ -351,7 +351,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', @@ -425,9 +425,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'); diff --git a/doc/api/index.md b/doc/api/index.md index c0980fd798cb06..cd8e2cd83f6792 100644 --- a/doc/api/index.md +++ b/doc/api/index.md @@ -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) diff --git a/doc/api/inspector.md b/doc/api/inspector.md index 9dcd7431b29e9b..dd5fac313d020b 100644 --- a/doc/api/inspector.md +++ b/doc/api/inspector.md @@ -6,12 +6,13 @@ -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 @@ -203,8 +204,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(); @@ -228,8 +229,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'); diff --git a/doc/api/intl.md b/doc/api/intl.md index cf4a852035d4e1..9d91c590ae0874 100644 --- a/doc/api/intl.md +++ b/doc/api/intl.md @@ -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 diff --git a/doc/api/module.md b/doc/api/module.md index 749bd350ba9c42..85ba9a79e2291d 100644 --- a/doc/api/module.md +++ b/doc/api/module.md @@ -1,4 +1,4 @@ -# Modules: `module` API +# Modules: `node:module` API @@ -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'); ``` diff --git a/doc/api/modules.md b/doc/api/modules.md index 9e9365fc80132c..955bd4dcaf58dc 100644 --- a/doc/api/modules.md +++ b/doc/api/modules.md @@ -688,7 +688,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` @@ -712,13 +712,13 @@ Use with care! ```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); ``` @@ -871,7 +871,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(); diff --git a/doc/api/net.md b/doc/api/net.md index 55c10a823eb2a9..ca4d189fd7060a 100644 --- a/doc/api/net.md +++ b/doc/api/net.md @@ -8,19 +8,19 @@ -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 @@ -868,7 +868,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: { @@ -1331,7 +1331,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!'); @@ -1447,7 +1447,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'); diff --git a/doc/api/os.md b/doc/api/os.md index 15729f8af98c5e..23467112487f57 100644 --- a/doc/api/os.md +++ b/doc/api/os.md @@ -6,11 +6,11 @@ -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` diff --git a/doc/api/packages.md b/doc/api/packages.md index 54bf99b0cb02b9..ec388fa17d25fe 100644 --- a/doc/api/packages.md +++ b/doc/api/packages.md @@ -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 diff --git a/doc/api/path.md b/doc/api/path.md index cc2bb4d1a8a3e3..149a01cdb1b072 100644 --- a/doc/api/path.md +++ b/doc/api/path.md @@ -6,19 +6,19 @@ -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 diff --git a/doc/api/perf_hooks.md b/doc/api/perf_hooks.md index 160156a39823e7..aabaca37309a55 100644 --- a/doc/api/perf_hooks.md +++ b/doc/api/perf_hooks.md @@ -18,7 +18,7 @@ Node.js supports the following [Web Performance APIs][]: * [Resource 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); @@ -123,8 +123,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(); @@ -349,7 +349,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'); @@ -891,7 +891,7 @@ added: v8.5.0 const { performance, PerformanceObserver -} = require('perf_hooks'); +} = require('node:perf_hooks'); const obs = new PerformanceObserver((list, observer) => { console.log(list.getEntries()); @@ -957,7 +957,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. @@ -993,7 +993,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()); @@ -1043,7 +1043,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')); @@ -1099,7 +1099,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')); @@ -1170,7 +1170,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. @@ -1417,11 +1417,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({ @@ -1466,8 +1466,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 = @@ -1499,8 +1499,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) => { @@ -1523,8 +1523,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); @@ -1543,8 +1543,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); diff --git a/doc/api/policy.md b/doc/api/policy.md index 0d53352788a32c..233d6c94640790 100644 --- a/doc/api/policy.md +++ b/doc/api/policy.md @@ -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 } diff --git a/doc/api/process.md b/doc/api/process.md index 23200b1a386888..4c0a972db83f0a 100644 --- a/doc/api/process.md +++ b/doc/api/process.md @@ -10,11 +10,11 @@ The `process` object provides information about, and control over, the current Node.js process. ```mjs -import process from 'process'; +import process from 'node:process'; ``` ```cjs -const process = require('process'); +const process = require('node:process'); ``` ## Process events @@ -43,7 +43,7 @@ The `'beforeExit'` should _not_ be used as an alternative to the `'exit'` event unless the intention is to schedule additional work. ```mjs -import process from 'process'; +import process from 'node:process'; process.on('beforeExit', (code) => { console.log('Process beforeExit event with code: ', code); @@ -62,7 +62,7 @@ console.log('This message is displayed first.'); ``` ```cjs -const process = require('process'); +const process = require('node:process'); process.on('beforeExit', (code) => { console.log('Process beforeExit event with code: ', code); @@ -112,7 +112,7 @@ by the [`process.exitCode`][] property, or the `exitCode` argument passed to the [`process.exit()`][] method. ```mjs -import process from 'process'; +import process from 'node:process'; process.on('exit', (code) => { console.log(`About to exit with code: ${code}`); @@ -120,7 +120,7 @@ process.on('exit', (code) => { ``` ```cjs -const process = require('process'); +const process = require('node:process'); process.on('exit', (code) => { console.log(`About to exit with code: ${code}`); @@ -133,7 +133,7 @@ causing any additional work still queued in the event loop to be abandoned. In the following example, for instance, the timeout will never occur: ```mjs -import process from 'process'; +import process from 'node:process'; process.on('exit', (code) => { setTimeout(() => { @@ -143,7 +143,7 @@ process.on('exit', (code) => { ``` ```cjs -const process = require('process'); +const process = require('node:process'); process.on('exit', (code) => { setTimeout(() => { @@ -206,7 +206,7 @@ Because of the unreliability of the event in cases like the [`Promise.race()`][] example above it has been deprecated. ```mjs -import process from 'process'; +import process from 'node:process'; process.on('multipleResolves', (type, promise, reason) => { console.error(type, promise, reason); @@ -235,7 +235,7 @@ main().then(console.log); ``` ```cjs -const process = require('process'); +const process = require('node:process'); process.on('multipleResolves', (type, promise, reason) => { console.error(type, promise, reason); @@ -296,7 +296,7 @@ of unhandled rejections grows, and the `'rejectionHandled'` event is emitted when the list of unhandled rejections shrinks. ```mjs -import process from 'process'; +import process from 'node:process'; const unhandledRejections = new Map(); process.on('unhandledRejection', (reason, promise) => { @@ -308,7 +308,7 @@ process.on('rejectionHandled', (promise) => { ``` ```cjs -const process = require('process'); +const process = require('node:process'); const unhandledRejections = new Map(); process.on('unhandledRejection', (reason, promise) => { @@ -357,7 +357,7 @@ provided exit code. Otherwise, in the presence of such handler the process will exit with 0. ```mjs -import process from 'process'; +import process from 'node:process'; process.on('uncaughtException', (err, origin) => { fs.writeSync( @@ -377,7 +377,7 @@ console.log('This will not run.'); ``` ```cjs -const process = require('process'); +const process = require('node:process'); process.on('uncaughtException', (err, origin) => { fs.writeSync( @@ -453,7 +453,7 @@ once an `'uncaughtException'` event is emitted. The process will still crash if no `'uncaughtException'` listener is installed. ```mjs -import process from 'process'; +import process from 'node:process'; process.on('uncaughtExceptionMonitor', (err, origin) => { MyMonitoringTool.logSync(err, origin); @@ -465,7 +465,7 @@ nonexistentFunc(); ``` ```cjs -const process = require('process'); +const process = require('node:process'); process.on('uncaughtExceptionMonitor', (err, origin) => { MyMonitoringTool.logSync(err, origin); @@ -503,7 +503,7 @@ useful for detecting and keeping track of promises that were rejected whose rejections have not yet been handled. ```mjs -import process from 'process'; +import process from 'node:process'; process.on('unhandledRejection', (reason, promise) => { console.log('Unhandled Rejection at:', promise, 'reason:', reason); @@ -516,7 +516,7 @@ somePromise.then((res) => { ``` ```cjs -const process = require('process'); +const process = require('node:process'); process.on('unhandledRejection', (reason, promise) => { console.log('Unhandled Rejection at:', promise, 'reason:', reason); @@ -532,7 +532,7 @@ The following will also trigger the `'unhandledRejection'` event to be emitted: ```mjs -import process from 'process'; +import process from 'node:process'; function SomeResource() { // Initially set the loaded status to a rejected promise @@ -544,7 +544,7 @@ const resource = new SomeResource(); ``` ```cjs -const process = require('process'); +const process = require('node:process'); function SomeResource() { // Initially set the loaded status to a rejected promise @@ -583,7 +583,7 @@ Node.js can emit warnings whenever it detects bad coding practices that could lead to sub-optimal application performance, bugs, or security vulnerabilities. ```mjs -import process from 'process'; +import process from 'node:process'; process.on('warning', (warning) => { console.warn(warning.name); // Print the warning name @@ -593,7 +593,7 @@ process.on('warning', (warning) => { ``` ```cjs -const process = require('process'); +const process = require('node:process'); process.on('warning', (warning) => { console.warn(warning.name); // Print the warning name @@ -702,7 +702,7 @@ The name of each event will be the uppercase common name for the signal (e.g. `'SIGINT'` for `SIGINT` signals). ```mjs -import process from 'process'; +import process from 'node:process'; // Begin reading from stdin so the process does not exit. process.stdin.resume(); @@ -721,7 +721,7 @@ process.on('SIGTERM', handle); ``` ```cjs -const process = require('process'); +const process = require('node:process'); // Begin reading from stdin so the process does not exit. process.stdin.resume(); @@ -828,7 +828,7 @@ passed through to V8 will contain underscores instead of non-leading dashes: ```mjs -import { allowedNodeEnvironmentFlags } from 'process'; +import { allowedNodeEnvironmentFlags } from 'node:process'; allowedNodeEnvironmentFlags.forEach((flag) => { // -r @@ -839,7 +839,7 @@ allowedNodeEnvironmentFlags.forEach((flag) => { ``` ```cjs -const { allowedNodeEnvironmentFlags } = require('process'); +const { allowedNodeEnvironmentFlags } = require('node:process'); allowedNodeEnvironmentFlags.forEach((flag) => { // -r @@ -870,13 +870,13 @@ Possible values are: `'arm'`, `'arm64'`, `'ia32'`, `'mips'`,`'mipsel'`, `'ppc'`, `'ppc64'`, `'s390'`, `'s390x'`, and `'x64'`. ```mjs -import { arch } from 'process'; +import { arch } from 'node:process'; console.log(`This processor architecture is ${arch}`); ``` ```cjs -const { arch } = require('process'); +const { arch } = require('node:process'); console.log(`This processor architecture is ${arch}`); ``` @@ -899,7 +899,7 @@ arguments. For example, assuming the following script for `process-args.js`: ```mjs -import { argv } from 'process'; +import { argv } from 'node:process'; // print process.argv argv.forEach((val, index) => { @@ -908,7 +908,7 @@ argv.forEach((val, index) => { ``` ```cjs -const { argv } = require('process'); +const { argv } = require('node:process'); // print process.argv argv.forEach((val, index) => { @@ -1007,7 +1007,7 @@ Node.js process or throws an exception if doing so fails (for instance, if the specified `directory` does not exist). ```mjs -import { chdir, cwd } from 'process'; +import { chdir, cwd } from 'node:process'; console.log(`Starting directory: ${cwd()}`); try { @@ -1019,7 +1019,7 @@ try { ``` ```cjs -const { chdir, cwd } = require('process'); +const { chdir, cwd } = require('node:process'); console.log(`Starting directory: ${cwd()}`); try { @@ -1127,7 +1127,7 @@ The result of a previous call to `process.cpuUsage()` can be passed as the argument to the function, to get a diff reading. ```mjs -import { cpuUsage } from 'process'; +import { cpuUsage } from 'node:process'; const startUsage = cpuUsage(); // { user: 38579, system: 6986 } @@ -1141,7 +1141,7 @@ console.log(cpuUsage(startUsage)); ``` ```cjs -const { cpuUsage } = require('process'); +const { cpuUsage } = require('node:process'); const startUsage = cpuUsage(); // { user: 38579, system: 6986 } @@ -1166,13 +1166,13 @@ The `process.cwd()` method returns the current working directory of the Node.js process. ```mjs -import { cwd } from 'process'; +import { cwd } from 'node:process'; console.log(`Current directory: ${cwd()}`); ``` ```cjs -const { cwd } = require('process'); +const { cwd } = require('node:process'); console.log(`Current directory: ${cwd()}`); ``` @@ -1188,13 +1188,13 @@ added: v0.7.2 The port used by the Node.js debugger when enabled. ```mjs -import process from 'process'; +import process from 'node:process'; process.debugPort = 5858; ``` ```cjs -const process = require('process'); +const process = require('node:process'); process.debugPort = 5858; ``` @@ -1249,9 +1249,9 @@ the call returns, by passing the `RTLD_NOW` constant. In this example the constant is assumed to be available. ```mjs -import { dlopen } from 'process'; -import { constants } from 'os'; -import { fileURLToPath } from 'url'; +import { dlopen } from 'node:process'; +import { constants } from 'node:os'; +import { fileURLToPath } from 'node:url'; const module = { exports: {} }; dlopen(module, fileURLToPath(new URL('local.node', import.meta.url)), @@ -1260,9 +1260,9 @@ module.exports.foo(); ``` ```cjs -const { dlopen } = require('process'); -const { constants } = require('os'); -const { join } = require('path'); +const { dlopen } = require('node:process'); +const { constants } = require('node:os'); +const { join } = require('node:path'); const module = { exports: {} }; dlopen(module, join(__dirname, 'local.node'), constants.dlopen.RTLD_NOW); @@ -1290,7 +1290,7 @@ specific process warnings. These can be listened for by adding a handler to the [`'warning'`][process_warning] event. ```mjs -import { emitWarning } from 'process'; +import { emitWarning } from 'node:process'; // Emit a warning with a code and additional detail. emitWarning('Something happened!', { @@ -1303,7 +1303,7 @@ emitWarning('Something happened!', { ``` ```cjs -const { emitWarning } = require('process'); +const { emitWarning } = require('node:process'); // Emit a warning with a code and additional detail. emitWarning('Something happened!', { @@ -1320,7 +1320,7 @@ In this example, an `Error` object is generated internally by [`'warning'`][process_warning] handler. ```mjs -import process from 'process'; +import process from 'node:process'; process.on('warning', (warning) => { console.warn(warning.name); // 'Warning' @@ -1332,7 +1332,7 @@ process.on('warning', (warning) => { ``` ```cjs -const process = require('process'); +const process = require('node:process'); process.on('warning', (warning) => { console.warn(warning.name); // 'Warning' @@ -1364,7 +1364,7 @@ specific process warnings. These can be listened for by adding a handler to the [`'warning'`][process_warning] event. ```mjs -import { emitWarning } from 'process'; +import { emitWarning } from 'node:process'; // Emit a warning using a string. emitWarning('Something happened!'); @@ -1372,7 +1372,7 @@ emitWarning('Something happened!'); ``` ```cjs -const { emitWarning } = require('process'); +const { emitWarning } = require('node:process'); // Emit a warning using a string. emitWarning('Something happened!'); @@ -1380,7 +1380,7 @@ emitWarning('Something happened!'); ``` ```mjs -import { emitWarning } from 'process'; +import { emitWarning } from 'node:process'; // Emit a warning using a string and a type. emitWarning('Something Happened!', 'CustomWarning'); @@ -1388,7 +1388,7 @@ emitWarning('Something Happened!', 'CustomWarning'); ``` ```cjs -const { emitWarning } = require('process'); +const { emitWarning } = require('node:process'); // Emit a warning using a string and a type. emitWarning('Something Happened!', 'CustomWarning'); @@ -1396,14 +1396,14 @@ emitWarning('Something Happened!', 'CustomWarning'); ``` ```mjs -import { emitWarning } from 'process'; +import { emitWarning } from 'node:process'; emitWarning('Something happened!', 'CustomWarning', 'WARN001'); // Emits: (node:56338) [WARN001] CustomWarning: Something happened! ``` ```cjs -const { emitWarning } = require('process'); +const { emitWarning } = require('node:process'); process.emitWarning('Something happened!', 'CustomWarning', 'WARN001'); // Emits: (node:56338) [WARN001] CustomWarning: Something happened! @@ -1414,7 +1414,7 @@ In each of the previous examples, an `Error` object is generated internally by handler. ```mjs -import process from 'process'; +import process from 'node:process'; process.on('warning', (warning) => { console.warn(warning.name); @@ -1425,7 +1425,7 @@ process.on('warning', (warning) => { ``` ```cjs -const process = require('process'); +const process = require('node:process'); process.on('warning', (warning) => { console.warn(warning.name); @@ -1440,7 +1440,7 @@ If `warning` is passed as an `Error` object, it will be passed through to the `code` and `ctor` arguments will be ignored): ```mjs -import { emitWarning } from 'process'; +import { emitWarning } from 'node:process'; // Emit a warning using an Error object. const myWarning = new Error('Something happened!'); @@ -1453,7 +1453,7 @@ emitWarning(myWarning); ``` ```cjs -const { emitWarning } = require('process'); +const { emitWarning } = require('node:process'); // Emit a warning using an Error object. const myWarning = new Error('Something happened!'); @@ -1487,7 +1487,7 @@ As a best practice, warnings should be emitted only once per process. To do so, place the `emitWarning()` behind a boolean. ```mjs -import { emitWarning } from 'process'; +import { emitWarning } from 'node:process'; function emitMyWarning() { if (!emitMyWarning.warned) { @@ -1502,7 +1502,7 @@ emitMyWarning(); ``` ```cjs -const { emitWarning } = require('process'); +const { emitWarning } = require('node:process'); function emitMyWarning() { if (!emitMyWarning.warned) { @@ -1567,14 +1567,14 @@ $ node -e 'process.env.foo = "bar"' && echo $foo While the following will: ```mjs -import { env } from 'process'; +import { env } from 'node:process'; env.foo = 'bar'; console.log(env.foo); ``` ```cjs -const { env } = require('process'); +const { env } = require('node:process'); env.foo = 'bar'; console.log(env.foo); @@ -1585,7 +1585,7 @@ to a string. **This behavior is deprecated.** Future versions of Node.js may throw an error when the value is not a string, number, or boolean. ```mjs -import { env } from 'process'; +import { env } from 'node:process'; env.test = null; console.log(env.test); @@ -1596,7 +1596,7 @@ console.log(env.test); ``` ```cjs -const { env } = require('process'); +const { env } = require('node:process'); env.test = null; console.log(env.test); @@ -1609,7 +1609,7 @@ console.log(env.test); Use `delete` to delete a property from `process.env`. ```mjs -import { env } from 'process'; +import { env } from 'node:process'; env.TEST = 1; delete env.TEST; @@ -1618,7 +1618,7 @@ console.log(env.TEST); ``` ```cjs -const { env } = require('process'); +const { env } = require('node:process'); env.TEST = 1; delete env.TEST; @@ -1629,7 +1629,7 @@ console.log(env.TEST); On Windows operating systems, environment variables are case-insensitive. ```mjs -import { env } from 'process'; +import { env } from 'node:process'; env.TEST = 1; console.log(env.test); @@ -1637,7 +1637,7 @@ console.log(env.test); ``` ```cjs -const { env } = require('process'); +const { env } = require('node:process'); env.TEST = 1; console.log(env.test); @@ -1723,13 +1723,13 @@ called. To exit with a 'failure' code: ```mjs -import { exit } from 'process'; +import { exit } from 'node:process'; exit(1); ``` ```cjs -const { exit } = require('process'); +const { exit } = require('node:process'); exit(1); ``` @@ -1751,7 +1751,7 @@ For instance, the following example illustrates a _misuse_ of the truncated and lost: ```mjs -import { exit } from 'process'; +import { exit } from 'node:process'; // This is an example of what *not* to do: if (someConditionNotMet()) { @@ -1761,7 +1761,7 @@ if (someConditionNotMet()) { ``` ```cjs -const { exit } = require('process'); +const { exit } = require('node:process'); // This is an example of what *not* to do: if (someConditionNotMet()) { @@ -1780,7 +1780,7 @@ Rather than calling `process.exit()` directly, the code _should_ set the scheduling any additional work for the event loop: ```mjs -import process from 'process'; +import process from 'node:process'; // How to properly set the exit code while letting // the process exit gracefully. @@ -1791,7 +1791,7 @@ if (someConditionNotMet()) { ``` ```cjs -const process = require('process'); +const process = require('node:process'); // How to properly set the exit code while letting // the process exit gracefully. @@ -1838,8 +1838,8 @@ containing the types of the active resources that are currently keeping the event loop alive. ```mjs -import { getActiveResourcesInfo } from 'process'; -import { setTimeout } from 'timers'; +import { getActiveResourcesInfo } from 'node:process'; +import { setTimeout } from 'node:timers'; console.log('Before:', getActiveResourcesInfo()); setTimeout(() => {}, 1000); @@ -1850,8 +1850,8 @@ console.log('After:', getActiveResourcesInfo()); ``` ```cjs -const { getActiveResourcesInfo } = require('process'); -const { setTimeout } = require('timers'); +const { getActiveResourcesInfo } = require('node:process'); +const { setTimeout } = require('node:timers'); console.log('Before:', getActiveResourcesInfo()); setTimeout(() => {}, 1000); @@ -1871,7 +1871,7 @@ The `process.getegid()` method returns the numerical effective group identity of the Node.js process. (See getegid(2).) ```mjs -import process from 'process'; +import process from 'node:process'; if (process.getegid) { console.log(`Current gid: ${process.getegid()}`); @@ -1879,7 +1879,7 @@ if (process.getegid) { ``` ```cjs -const process = require('process'); +const process = require('node:process'); if (process.getegid) { console.log(`Current gid: ${process.getegid()}`); @@ -1901,7 +1901,7 @@ The `process.geteuid()` method returns the numerical effective user identity of the process. (See geteuid(2).) ```mjs -import process from 'process'; +import process from 'node:process'; if (process.geteuid) { console.log(`Current uid: ${process.geteuid()}`); @@ -1909,7 +1909,7 @@ if (process.geteuid) { ``` ```cjs -const process = require('process'); +const process = require('node:process'); if (process.geteuid) { console.log(`Current uid: ${process.geteuid()}`); @@ -1931,7 +1931,7 @@ The `process.getgid()` method returns the numerical group identity of the process. (See getgid(2).) ```mjs -import process from 'process'; +import process from 'node:process'; if (process.getgid) { console.log(`Current gid: ${process.getgid()}`); @@ -1939,7 +1939,7 @@ if (process.getgid) { ``` ```cjs -const process = require('process'); +const process = require('node:process'); if (process.getgid) { console.log(`Current gid: ${process.getgid()}`); @@ -1962,7 +1962,7 @@ IDs. POSIX leaves it unspecified if the effective group ID is included but Node.js ensures it always is. ```mjs -import process from 'process'; +import process from 'node:process'; if (process.getgroups) { console.log(process.getgroups()); // [ 16, 21, 297 ] @@ -1970,7 +1970,7 @@ if (process.getgroups) { ``` ```cjs -const process = require('process'); +const process = require('node:process'); if (process.getgroups) { console.log(process.getgroups()); // [ 16, 21, 297 ] @@ -1992,7 +1992,7 @@ The `process.getuid()` method returns the numeric user identity of the process. (See getuid(2).) ```mjs -import process from 'process'; +import process from 'node:process'; if (process.getuid) { console.log(`Current uid: ${process.getuid()}`); @@ -2000,7 +2000,7 @@ if (process.getuid) { ``` ```cjs -const process = require('process'); +const process = require('node:process'); if (process.getuid) { console.log(`Current uid: ${process.getuid()}`); @@ -2050,7 +2050,7 @@ past, and not related to the time of day and therefore not subject to clock drift. The primary use is for measuring performance between intervals: ```mjs -import { hrtime } from 'process'; +import { hrtime } from 'node:process'; const NS_PER_SEC = 1e9; const time = hrtime(); @@ -2066,7 +2066,7 @@ setTimeout(() => { ``` ```cjs -const { hrtime } = require('process'); +const { hrtime } = require('node:process'); const NS_PER_SEC = 1e9; const time = hrtime(); @@ -2097,7 +2097,7 @@ argument since the difference can just be computed directly by subtraction of the two `bigint`s. ```mjs -import { hrtime } from 'process'; +import { hrtime } from 'node:process'; const start = hrtime.bigint(); // 191051479007711n @@ -2112,7 +2112,7 @@ setTimeout(() => { ``` ```cjs -const { hrtime } = require('process'); +const { hrtime } = require('node:process'); const start = hrtime.bigint(); // 191051479007711n @@ -2143,7 +2143,7 @@ access or the `CAP_SETGID` capability. Use care when dropping privileges: ```mjs -import { getgroups, initgroups, setgid } from 'process'; +import { getgroups, initgroups, setgid } from 'node:process'; console.log(getgroups()); // [ 0 ] initgroups('nodeuser', 1000); // switch user @@ -2153,7 +2153,7 @@ console.log(getgroups()); // [ 27, 30, 46, 1000 ] ``` ```cjs -const { getgroups, initgroups, setgid } = require('process'); +const { getgroups, initgroups, setgid } = require('node:process'); console.log(getgroups()); // [ 0 ] initgroups('nodeuser', 1000); // switch user @@ -2192,7 +2192,7 @@ signal sender, like the `kill` system call. The signal sent may do something other than kill the target process. ```mjs -import process, { kill } from 'process'; +import process, { kill } from 'node:process'; process.on('SIGHUP', () => { console.log('Got SIGHUP signal.'); @@ -2207,7 +2207,7 @@ kill(process.pid, 'SIGHUP'); ``` ```cjs -const process = require('process'); +const process = require('node:process'); process.on('SIGHUP', () => { console.log('Got SIGHUP signal.'); @@ -2270,7 +2270,7 @@ Returns an object describing the memory usage of the Node.js process measured in bytes. ```mjs -import { memoryUsage } from 'process'; +import { memoryUsage } from 'node:process'; console.log(memoryUsage()); // Prints: @@ -2284,7 +2284,7 @@ console.log(memoryUsage()); ``` ```cjs -const { memoryUsage } = require('process'); +const { memoryUsage } = require('node:process'); console.log(memoryUsage()); // Prints: @@ -2335,14 +2335,14 @@ This is the same value as the `rss` property provided by `process.memoryUsage()` but `process.memoryUsage.rss()` is faster. ```mjs -import { memoryUsage } from 'process'; +import { memoryUsage } from 'node:process'; console.log(memoryUsage.rss()); // 35655680 ``` ```cjs -const { rss } = require('process'); +const { rss } = require('node:process'); console.log(memoryUsage.rss()); // 35655680 @@ -2368,7 +2368,7 @@ create an infinite loop if one were to recursively call `process.nextTick()`. See the [Event Loop][] guide for more background. ```mjs -import { nextTick } from 'process'; +import { nextTick } from 'node:process'; console.log('start'); nextTick(() => { @@ -2382,7 +2382,7 @@ console.log('scheduled'); ``` ```cjs -const { nextTick } = require('process'); +const { nextTick } = require('node:process'); console.log('start'); nextTick(() => { @@ -2400,7 +2400,7 @@ to assign event handlers _after_ an object has been constructed but before any I/O has occurred: ```mjs -import { nextTick } from 'process'; +import { nextTick } from 'node:process'; function MyThing(options) { this.setupOptions(options); @@ -2417,7 +2417,7 @@ thing.getReadyForStuff(); ``` ```cjs -const { nextTick } = require('process'); +const { nextTick } = require('node:process'); function MyThing(options) { this.setupOptions(options); @@ -2465,7 +2465,7 @@ It is not clear whether `foo()` or `bar()` will be called first. The following approach is much better: ```mjs -import { nextTick } from 'process'; +import { nextTick } from 'node:process'; function definitelyAsync(arg, cb) { if (arg) { @@ -2478,7 +2478,7 @@ function definitelyAsync(arg, cb) { ``` ```cjs -const { nextTick } = require('process'); +const { nextTick } = require('node:process'); function definitelyAsync(arg, cb) { if (arg) { @@ -2499,7 +2499,7 @@ Node.js, every time the "next tick queue" is drained, the microtask queue is drained immediately after. ```mjs -import { nextTick } from 'process'; +import { nextTick } from 'node:process'; Promise.resolve().then(() => console.log(2)); queueMicrotask(() => console.log(3)); @@ -2511,7 +2511,7 @@ nextTick(() => console.log(1)); ``` ```cjs -const { nextTick } = require('process'); +const { nextTick } = require('node:process'); Promise.resolve().then(() => console.log(2)); queueMicrotask(() => console.log(3)); @@ -2593,13 +2593,13 @@ added: v0.1.15 The `process.pid` property returns the PID of the process. ```mjs -import { pid } from 'process'; +import { pid } from 'node:process'; console.log(`This process is pid ${pid}`); ``` ```cjs -const { pid } = require('process'); +const { pid } = require('node:process'); console.log(`This process is pid ${pid}`); ``` @@ -2626,13 +2626,13 @@ Currently possible values are: * `'win32'` ```mjs -import { platform } from 'process'; +import { platform } from 'node:process'; console.log(`This platform is ${platform}`); ``` ```cjs -const { platform } = require('process'); +const { platform } = require('node:process'); console.log(`This platform is ${platform}`); ``` @@ -2656,13 +2656,13 @@ The `process.ppid` property returns the PID of the parent of the current process. ```mjs -import { ppid } from 'process'; +import { ppid } from 'node:process'; console.log(`The parent process is pid ${ppid}`); ``` ```cjs -const { ppid } = require('process'); +const { ppid } = require('node:process'); console.log(`The parent process is pid ${ppid}`); ``` @@ -2754,13 +2754,13 @@ by log processing systems than the default multi-line format designed for human consumption. ```mjs -import { report } from 'process'; +import { report } from 'node:process'; console.log(`Reports are compact? ${report.compact}`); ``` ```cjs -const { report } = require('process'); +const { report } = require('node:process'); console.log(`Reports are compact? ${report.compact}`); ``` @@ -2784,13 +2784,13 @@ indicating that reports are written to the current working directory of the Node.js process. ```mjs -import { report } from 'process'; +import { report } from 'node:process'; console.log(`Report directory is ${report.directory}`); ``` ```cjs -const { report } = require('process'); +const { report } = require('node:process'); console.log(`Report directory is ${report.directory}`); ``` @@ -2814,13 +2814,13 @@ filename will be comprised of a timestamp, PID, and sequence number. The default value is the empty string. ```mjs -import { report } from 'process'; +import { report } from 'node:process'; console.log(`Report filename is ${report.filename}`); ``` ```cjs -const { report } = require('process'); +const { report } = require('node:process'); console.log(`Report filename is ${report.filename}`); ``` @@ -2845,24 +2845,24 @@ running process. The report's JavaScript stack trace is taken from `err`, if present. ```mjs -import { report } from 'process'; +import { report } from 'node:process'; const data = report.getReport(); console.log(data.header.nodejsVersion); // Similar to process.report.writeReport() -import fs from 'fs'; +import fs from 'node:fs'; fs.writeFileSync('my-report.log', util.inspect(data), 'utf8'); ``` ```cjs -const { report } = require('process'); +const { report } = require('node:process'); const data = report.getReport(); console.log(data.header.nodejsVersion); // Similar to process.report.writeReport() -const fs = require('fs'); +const fs = require('node:fs'); fs.writeFileSync('my-report.log', util.inspect(data), 'utf8'); ``` @@ -2885,13 +2885,13 @@ If `true`, a diagnostic report is generated on fatal errors, such as out of memory errors or failed C++ assertions. ```mjs -import { report } from 'process'; +import { report } from 'node:process'; console.log(`Report on fatal error: ${report.reportOnFatalError}`); ``` ```cjs -const { report } = require('process'); +const { report } = require('node:process'); console.log(`Report on fatal error: ${report.reportOnFatalError}`); ``` @@ -2914,13 +2914,13 @@ If `true`, a diagnostic report is generated when the process receives the signal specified by `process.report.signal`. ```mjs -import { report } from 'process'; +import { report } from 'node:process'; console.log(`Report on signal: ${report.reportOnSignal}`); ``` ```cjs -const { report } = require('process'); +const { report } = require('node:process'); console.log(`Report on signal: ${report.reportOnSignal}`); ``` @@ -2942,13 +2942,13 @@ changes: If `true`, a diagnostic report is generated on uncaught exception. ```mjs -import { report } from 'process'; +import { report } from 'node:process'; console.log(`Report on exception: ${report.reportOnUncaughtException}`); ``` ```cjs -const { report } = require('process'); +const { report } = require('node:process'); console.log(`Report on exception: ${report.reportOnUncaughtException}`); ``` @@ -2971,13 +2971,13 @@ The signal used to trigger the creation of a diagnostic report. Defaults to `'SIGUSR2'`. ```mjs -import { report } from 'process'; +import { report } from 'node:process'; console.log(`Report signal: ${report.signal}`); ``` ```cjs -const { report } = require('process'); +const { report } = require('node:process'); console.log(`Report signal: ${report.signal}`); ``` @@ -3008,13 +3008,13 @@ filename includes the date, time, PID, and a sequence number. The report's JavaScript stack trace is taken from `err`, if present. ```mjs -import { report } from 'process'; +import { report } from 'node:process'; report.writeReport(); ``` ```cjs -const { report } = require('process'); +const { report } = require('node:process'); report.writeReport(); ``` @@ -3071,7 +3071,7 @@ added: v12.6.0 time slice. This field is not supported on Windows. ```mjs -import { resourceUsage } from 'process'; +import { resourceUsage } from 'node:process'; console.log(resourceUsage()); /* @@ -3098,7 +3098,7 @@ console.log(resourceUsage()); ``` ```cjs -const { resourceUsage } = require('process'); +const { resourceUsage } = require('node:process'); console.log(resourceUsage()); /* @@ -3164,7 +3164,7 @@ name string. If a group name is specified, this method blocks while resolving the associated a numeric ID. ```mjs -import process from 'process'; +import process from 'node:process'; if (process.getegid && process.setegid) { console.log(`Current gid: ${process.getegid()}`); @@ -3178,7 +3178,7 @@ if (process.getegid && process.setegid) { ``` ```cjs -const process = require('process'); +const process = require('node:process'); if (process.getegid && process.setegid) { console.log(`Current gid: ${process.getegid()}`); @@ -3209,7 +3209,7 @@ string. If a username is specified, the method blocks while resolving the associated numeric ID. ```mjs -import process from 'process'; +import process from 'node:process'; if (process.geteuid && process.seteuid) { console.log(`Current uid: ${process.geteuid()}`); @@ -3223,7 +3223,7 @@ if (process.geteuid && process.seteuid) { ``` ```cjs -const process = require('process'); +const process = require('node:process'); if (process.geteuid && process.seteuid) { console.log(`Current uid: ${process.geteuid()}`); @@ -3254,7 +3254,7 @@ string. If a group name is specified, this method blocks while resolving the associated numeric ID. ```mjs -import process from 'process'; +import process from 'node:process'; if (process.getgid && process.setgid) { console.log(`Current gid: ${process.getgid()}`); @@ -3268,7 +3268,7 @@ if (process.getgid && process.setgid) { ``` ```cjs -const process = require('process'); +const process = require('node:process'); if (process.getgid && process.setgid) { console.log(`Current gid: ${process.getgid()}`); @@ -3300,7 +3300,7 @@ process to have `root` or the `CAP_SETGID` capability. The `groups` array can contain numeric group IDs, group names, or both. ```mjs -import process from 'process'; +import process from 'node:process'; if (process.getgroups && process.setgroups) { try { @@ -3313,7 +3313,7 @@ if (process.getgroups && process.setgroups) { ``` ```cjs -const process = require('process'); +const process = require('node:process'); if (process.getgroups && process.setgroups) { try { @@ -3343,7 +3343,7 @@ If a username is specified, the method blocks while resolving the associated numeric ID. ```mjs -import process from 'process'; +import process from 'node:process'; if (process.getuid && process.setuid) { console.log(`Current uid: ${process.getuid()}`); @@ -3357,7 +3357,7 @@ if (process.getuid && process.setuid) { ``` ```cjs -const process = require('process'); +const process = require('node:process'); if (process.getuid && process.setuid) { console.log(`Current uid: ${process.getuid()}`); @@ -3478,13 +3478,13 @@ a [Writable][] stream. For example, to copy `process.stdin` to `process.stdout`: ```mjs -import { stdin, stdout } from 'process'; +import { stdin, stdout } from 'node:process'; stdin.pipe(stdout); ``` ```cjs -const { stdin, stdout } = require('process'); +const { stdin, stdout } = require('node:process'); stdin.pipe(stdout); ``` @@ -3651,7 +3651,7 @@ added: v0.1.19 processes inherit the mask from the parent process. Returns the previous mask. ```mjs -import { umask } from 'process'; +import { umask } from 'node:process'; const newmask = 0o022; const oldmask = umask(newmask); @@ -3661,7 +3661,7 @@ console.log( ``` ```cjs -const { umask } = require('process'); +const { umask } = require('node:process'); const newmask = 0o022; const oldmask = umask(newmask); @@ -3697,14 +3697,14 @@ added: v0.1.3 The `process.version` property contains the Node.js version string. ```mjs -import { version } from 'process'; +import { version } from 'node:process'; console.log(`Version: ${version}`); // Version: v14.8.0 ``` ```cjs -const { version } = require('process'); +const { version } = require('node:process'); console.log(`Version: ${version}`); // Version: v14.8.0 @@ -3734,13 +3734,13 @@ ABI version, which is increased whenever a C++ API changes. Node.js will refuse to load modules that were compiled against a different module ABI version. ```mjs -import { versions } from 'process'; +import { versions } from 'node:process'; console.log(versions); ``` ```cjs -const { versions } = require('process'); +const { versions } = require('node:process'); console.log(versions); ``` diff --git a/doc/api/querystring.md b/doc/api/querystring.md index 32e9904553d568..a3db3c13a80a3d 100644 --- a/doc/api/querystring.md +++ b/doc/api/querystring.md @@ -8,11 +8,11 @@ -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, diff --git a/doc/api/readline.md b/doc/api/readline.md index a6751441010f94..816a0a2d1c52f7 100644 --- a/doc/api/readline.md +++ b/doc/api/readline.md @@ -6,18 +6,19 @@ -The `readline` module provides an interface for reading data from a [Readable][] -stream (such as [`process.stdin`][]) one line at a time. It can be accessed -using: +The `node:readline` module provides an interface for reading data from a +[Readable][] stream (such as [`process.stdin`][]) one line at a time. +It can be accessed using: ```js -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. ```js -const readline = require('readline'); +const readline = require('node:readline'); const rl = readline.createInterface({ input: process.stdin, @@ -329,7 +330,7 @@ Promise that fulfills with the answer. If the question is canceled using an `AbortController` it will reject with an `AbortError`. ```js -const util = require('util'); +const util = require('node:util'); const question = util.promisify(rl.question).bind(rl); async function questionExample() { @@ -639,7 +640,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 @@ -767,7 +768,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, @@ -794,13 +795,13 @@ rl.on('line', (line) => { ## Example: Read file stream line-by-Line -A common use case for `readline` is to consume an input file one line at a +A common use case for `node:readline` is to consume an input file one line at a 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'); @@ -824,8 +825,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'), @@ -841,9 +842,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 { diff --git a/doc/api/repl.md b/doc/api/repl.md index 4c75bdec2c4dbf..28dc5ecce55f51 100644 --- a/doc/api/repl.md +++ b/doc/api/repl.md @@ -6,17 +6,17 @@ -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({ diff --git a/doc/api/stream.md b/doc/api/stream.md index ae3e83ca5bd08b..5d197f18900020 100644 --- a/doc/api/stream.md +++ b/doc/api/stream.md @@ -7,7 +7,7 @@ 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(); @@ -467,7 +467,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(); @@ -513,7 +513,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!'); @@ -848,7 +848,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(); @@ -1018,7 +1018,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()}`); @@ -1167,7 +1167,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'. @@ -1181,7 +1181,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'); @@ -1472,7 +1472,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', @@ -1524,7 +1524,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); @@ -1574,8 +1574,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 @@ -1588,7 +1589,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); @@ -1610,7 +1611,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'); @@ -1654,7 +1655,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 })) { @@ -1714,8 +1715,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)) { @@ -1759,8 +1760,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)) { @@ -1817,8 +1818,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)) { @@ -1862,8 +1863,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] @@ -1908,8 +1909,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 @@ -1957,8 +1958,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 @@ -2006,8 +2007,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 @@ -2056,8 +2057,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])) { @@ -2093,7 +2094,7 @@ added: v16.15.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] ``` @@ -2115,7 +2116,7 @@ added: v16.15.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] ``` @@ -2138,7 +2139,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']] @@ -2179,7 +2180,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; @@ -2314,7 +2315,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'); @@ -2336,7 +2337,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'); @@ -2399,9 +2400,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. @@ -2429,7 +2430,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( @@ -2447,7 +2448,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(); @@ -2468,8 +2469,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( @@ -2493,8 +2494,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( @@ -2525,9 +2526,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'); @@ -2567,7 +2568,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) { @@ -2601,8 +2602,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*() { @@ -2650,7 +2651,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'; @@ -2791,7 +2792,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( @@ -2830,7 +2831,7 @@ const stream = addAbortSignal( -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 @@ -2841,7 +2842,7 @@ parent class constructor: ```js -const { Writable } = require('stream'); +const { Writable } = require('node:stream'); class MyWritable extends Writable { constructor({ highWaterMark, ...options }) { @@ -2892,7 +2893,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) { @@ -2974,7 +2975,7 @@ changes: ```js -const { Writable } = require('stream'); +const { Writable } = require('node:stream'); class MyWritable extends Writable { constructor(options) { @@ -2988,8 +2989,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)) @@ -3002,7 +3003,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) { @@ -3019,7 +3020,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({ @@ -3054,8 +3055,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) { @@ -3211,7 +3212,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) { @@ -3232,7 +3233,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) { @@ -3253,8 +3254,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) { @@ -3334,7 +3335,7 @@ changes: ```js -const { Readable } = require('stream'); +const { Readable } = require('node:stream'); class MyReadable extends Readable { constructor(options) { @@ -3348,8 +3349,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)) @@ -3362,7 +3363,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) { @@ -3376,7 +3377,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) { @@ -3407,8 +3408,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) { @@ -3580,7 +3581,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) { @@ -3602,7 +3603,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) { @@ -3673,7 +3674,7 @@ changes: ```js -const { Duplex } = require('stream'); +const { Duplex } = require('node:stream'); class MyDuplex extends Duplex { constructor(options) { @@ -3686,8 +3687,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)) @@ -3700,7 +3701,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) { @@ -3715,8 +3716,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') @@ -3764,7 +3765,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 { @@ -3805,7 +3806,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({ @@ -3870,7 +3871,7 @@ output on the `Readable` side is not consumed. ```js -const { Transform } = require('stream'); +const { Transform } = require('node:stream'); class MyTransform extends Transform { constructor(options) { @@ -3883,8 +3884,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)) @@ -3897,7 +3898,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) { @@ -4041,7 +4042,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; @@ -4070,9 +4071,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'); diff --git a/doc/api/string_decoder.md b/doc/api/string_decoder.md index a628a5a8a14cf4..70387d2edba696 100644 --- a/doc/api/string_decoder.md +++ b/doc/api/string_decoder.md @@ -6,18 +6,18 @@ -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])); diff --git a/doc/api/synopsis.md b/doc/api/synopsis.md index c035b9a93cda9a..78d17ad685bd26 100644 --- a/doc/api/synopsis.md +++ b/doc/api/synopsis.md @@ -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; diff --git a/doc/api/timers.md b/doc/api/timers.md index decb2c1561645a..21878a8b8a83f4 100644 --- a/doc/api/timers.md +++ b/doc/api/timers.md @@ -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 @@ -251,7 +251,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; @@ -269,7 +269,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; @@ -329,7 +329,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 { @@ -344,7 +344,7 @@ const { setTimeout, setImmediate, setInterval, -} = require('timers/promises'); +} = require('node:timers/promises'); ``` ### `timersPromises.setTimeout([delay[, value[, options]]])` @@ -376,7 +376,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' @@ -410,7 +410,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' @@ -454,7 +454,7 @@ console.log(Date.now()); ```cjs const { setInterval, -} = require('timers/promises'); +} = require('node:timers/promises'); const interval = 100; (async function() { @@ -491,7 +491,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 ``` diff --git a/doc/api/tls.md b/doc/api/tls.md index 155d864538e546..4dc898464d31f3 100644 --- a/doc/api/tls.md +++ b/doc/api/tls.md @@ -6,19 +6,19 @@ -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` @@ -1678,8 +1678,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. @@ -2079,14 +2079,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'), diff --git a/doc/api/tracing.md b/doc/api/tracing.md index df76d985f71dbe..890938eb9e1396 100644 --- a/doc/api/tracing.md +++ b/doc/api/tracing.md @@ -6,11 +6,11 @@ -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 -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") diff --git a/doc/api/url.md b/doc/api/url.md index b1f44f9efa97ba..e4018dc6ba82f9 100644 --- a/doc/api/url.md +++ b/doc/api/url.md @@ -6,15 +6,15 @@ -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); @@ -1005,7 +1005,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 @@ -1016,7 +1016,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 @@ -1046,7 +1046,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 @@ -1057,7 +1057,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 @@ -1080,7 +1080,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); @@ -1098,7 +1098,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) @@ -1140,7 +1140,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); @@ -1154,7 +1154,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); @@ -1180,7 +1180,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) @@ -1190,7 +1190,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) @@ -1230,7 +1230,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)); @@ -1249,7 +1249,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)); @@ -1295,7 +1295,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` @@ -1424,7 +1425,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', @@ -1583,7 +1584,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' diff --git a/doc/api/util.md b/doc/api/util.md index eb79edf42589f0..838fbe77d30959 100644 --- a/doc/api/util.md +++ b/doc/api/util.md @@ -6,12 +6,12 @@ -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'); @@ -433,8 +433,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); @@ -460,7 +460,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) { @@ -638,7 +638,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]; @@ -656,7 +656,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 })); ``` @@ -664,7 +664,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, [[ @@ -720,7 +720,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 }; @@ -734,8 +734,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], @@ -762,7 +762,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; @@ -886,7 +886,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) { @@ -921,7 +921,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) => { @@ -990,7 +990,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 @@ -1028,8 +1028,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) => { @@ -1042,8 +1042,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); @@ -1066,7 +1066,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() { @@ -1096,7 +1096,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) { // ... @@ -1389,7 +1389,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. @@ -1401,7 +1401,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)` @@ -2202,7 +2202,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 @@ -2227,7 +2227,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 @@ -2252,7 +2252,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 @@ -2277,7 +2277,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 @@ -2303,7 +2303,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 @@ -2318,7 +2318,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); @@ -2344,7 +2344,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 = () => {}; @@ -2373,7 +2373,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 @@ -2400,7 +2400,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 @@ -2425,7 +2425,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 @@ -2455,7 +2455,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 @@ -2485,7 +2485,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 @@ -2522,7 +2522,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 @@ -2547,7 +2547,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 @@ -2574,7 +2574,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 @@ -2599,7 +2599,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); @@ -2625,7 +2625,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.'); ``` diff --git a/doc/api/v8.md b/doc/api/v8.md index 1d0c463c95c4c6..80d86e400f3dd6 100644 --- a/doc/api/v8.md +++ b/doc/api/v8.md @@ -4,11 +4,11 @@ -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); ``` @@ -248,7 +248,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); ``` @@ -314,12 +314,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); @@ -599,7 +599,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: @@ -666,13 +666,13 @@ added: v16.14.0 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) => {}); ``` @@ -691,13 +691,13 @@ added: v16.14.0 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: v16.14.0 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) => {}); ``` @@ -741,13 +741,13 @@ added: v16.14.0 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) => {}); ``` @@ -779,7 +779,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) {} @@ -787,7 +787,7 @@ const stopAll = promiseHooks.createHook({ ``` ```cjs -const { promiseHooks } = require('v8'); +const { promiseHooks } = require('node:v8'); const stopAll = promiseHooks.createHook({ init(promise, parent) {} diff --git a/doc/api/vm.md b/doc/api/vm.md index ec8aa61159a620..c8a0a27c991f0d 100644 --- a/doc/api/vm.md +++ b/doc/api/vm.md @@ -8,10 +8,10 @@ -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. -The `vm` module is not a security +The `node:vm` module is not a security mechanism. Do not use it to run untrusted code. 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; @@ -175,7 +175,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', @@ -257,7 +257,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"'); @@ -302,7 +302,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; @@ -349,7 +349,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, @@ -420,7 +420,7 @@ await bar.evaluate(); ``` ```cjs -const vm = require('vm'); +const vm = require('node:vm'); const contextifiedObject = vm.createContext({ secret: 42, @@ -708,7 +708,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 }); @@ -736,7 +736,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( @@ -808,7 +808,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() { @@ -859,7 +859,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); @@ -872,7 +872,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); @@ -993,7 +993,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; @@ -1069,7 +1069,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() @@ -1182,7 +1182,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); @@ -1292,7 +1292,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', @@ -1376,7 +1376,7 @@ the JavaScript [`eval()`][] function to run the same code: ```js -const vm = require('vm'); +const vm = require('node:vm'); let localVar = 'initial value'; const vmResult = vm.runInThisContext('localVar = "vm";'); @@ -1400,17 +1400,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' }); @@ -1439,9 +1439,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 @@ -1457,7 +1457,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'); @@ -1477,7 +1477,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()); diff --git a/doc/api/wasi.md b/doc/api/wasi.md index 644daa217e900e..1b457201345ff0 100644 --- a/doc/api/wasi.md +++ b/doc/api/wasi.md @@ -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, diff --git a/doc/api/webcrypto.md b/doc/api/webcrypto.md index d1dc8243b4c6a5..9454fead349b69 100644 --- a/doc/api/webcrypto.md +++ b/doc/api/webcrypto.md @@ -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` diff --git a/doc/api/webstreams.md b/doc/api/webstreams.md index 8d03b691cb6621..0fe9aeeba93383 100644 --- a/doc/api/webstreams.md +++ b/doc/api/webstreams.md @@ -70,15 +70,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; @@ -183,7 +183,7 @@ console.log(await reader.read()); ``` ```cjs -const { ReadableStream } = require('stream/web'); +const { ReadableStream } = require('node:stream/web'); const stream = new ReadableStream(); @@ -255,7 +255,7 @@ for await (const chunk of transformedStream) const { ReadableStream, TransformStream, -} = require('stream/web'); +} = require('node:stream/web'); const stream = new ReadableStream({ start(controller) { @@ -345,7 +345,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()); @@ -572,7 +572,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}, @@ -1332,7 +1332,7 @@ const { buffer, json, text, -} = require('stream/consumers'); +} = require('node:stream/consumers'); ``` #### `streamConsumers.arrayBuffer(stream)` diff --git a/doc/api/worker_threads.md b/doc/api/worker_threads.md index e1f616e209ab69..eea21aec60bdb5 100644 --- a/doc/api/worker_threads.md +++ b/doc/api/worker_threads.md @@ -6,11 +6,11 @@ -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!' }); @@ -365,7 +365,7 @@ const { isMainThread, BroadcastChannel, Worker -} = require('worker_threads'); +} = require('node:worker_threads'); const bc = new BroadcastChannel('hello'); @@ -460,7 +460,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)); @@ -499,7 +499,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: @@ -612,7 +612,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)); @@ -637,7 +637,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)); @@ -664,7 +664,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 @@ -828,8 +828,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 @@ -850,11 +850,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. @@ -869,10 +869,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(); @@ -963,7 +963,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). @@ -1025,7 +1025,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 @@ -1111,7 +1111,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); @@ -1145,7 +1145,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()` @@ -1245,7 +1245,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()` @@ -1290,7 +1290,7 @@ if (isMainThread) { const { Worker, isMainThread, -} = require('worker_threads'); +} = require('node:worker_threads'); if (isMainThread) { new Worker(__filename); @@ -1334,11 +1334,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 @@ -1353,12 +1353,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 diff --git a/doc/api/zlib.md b/doc/api/zlib.md index 2c3a044381bbab..83a767a07e0253 100644 --- a/doc/api/zlib.md +++ b/doc/api/zlib.md @@ -6,13 +6,13 @@ -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` diff --git a/doc/contributing/writing-and-running-benchmarks.md b/doc/contributing/writing-and-running-benchmarks.md index a5f27382334aa7..bab0cc1c2fa928 100644 --- a/doc/contributing/writing-and-running-benchmarks.md +++ b/doc/contributing/writing-and-running-benchmarks.md @@ -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) => { diff --git a/doc/contributing/writing-tests.md b/doc/contributing/writing-tests.md index 77be88f1b8b102..c24526f0139843 100644 --- a/doc/contributing/writing-tests.md +++ b/doc/contributing/writing-tests.md @@ -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 diff --git a/src/crypto/README.md b/src/crypto/README.md index 28351eb024196c..22d4954b464ff0 100644 --- a/src/crypto/README.md +++ b/src/crypto/README.md @@ -301,12 +301,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) => { diff --git a/test/common/README.md b/test/common/README.md index d8c8d55ec97192..60462345abf46c 100644 --- a/test/common/README.md +++ b/test/common/README.md @@ -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'] }); ```