diff --git a/doc/api/assert.md b/doc/api/assert.md index 991275969c4193..da9a4ba55827f3 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(); @@ -547,14 +547,14 @@ The following example does not throw an [`AssertionError`][] because the primitives are compared using the [`==` operator][]. ```mjs -import assert from 'assert'; +import assert from 'node:assert'; // WARNING: This does not throw an AssertionError! assert.deepEqual('+00000000', false); ``` ```cjs -const assert = require('assert'); +const assert = require('node:assert'); // WARNING: This does not throw an AssertionError! assert.deepEqual('+00000000', false); @@ -564,7 +564,7 @@ assert.deepEqual('+00000000', false); are evaluated also: ```mjs -import assert from 'assert'; +import assert from 'node:assert'; const obj1 = { a: { @@ -599,7 +599,7 @@ assert.deepEqual(obj1, obj4); ``` ```cjs -const assert = require('assert'); +const assert = require('node:assert'); const obj1 = { a: { @@ -705,7 +705,7 @@ are recursively evaluated also by the following rules. are not enumerable properties. ```mjs -import assert from 'assert/strict'; +import assert from 'node:assert/strict'; // This fails because 1 !== '1'. assert.deepStrictEqual({ a: 1 }, { a: '1' }); @@ -797,7 +797,7 @@ assert.deepStrictEqual(weakMap1, weakMap3); ``` ```cjs -const assert = require('assert/strict'); +const assert = require('node:assert/strict'); // This fails because 1 !== '1'. assert.deepStrictEqual({ a: 1 }, { a: '1' }); @@ -913,7 +913,7 @@ changes: Expects the `string` input not to match the regular expression. ```mjs -import assert from 'assert/strict'; +import assert from 'node:assert/strict'; assert.doesNotMatch('I will fail', /fail/); // AssertionError [ERR_ASSERTION]: The input was expected to not match the ... @@ -926,7 +926,7 @@ assert.doesNotMatch('I will pass', /different/); ``` ```cjs -const assert = require('assert/strict'); +const assert = require('node:assert/strict'); assert.doesNotMatch('I will fail', /fail/); // AssertionError [ERR_ASSERTION]: The input was expected to not match the ... @@ -977,7 +977,7 @@ Besides the async nature to await the completion behaves identically to [`assert.doesNotThrow()`][]. ```mjs -import assert from 'assert/strict'; +import assert from 'node:assert/strict'; await assert.doesNotReject( async () => { @@ -988,7 +988,7 @@ await assert.doesNotReject( ``` ```cjs -const assert = require('assert/strict'); +const assert = require('node:assert/strict'); (async () => { await assert.doesNotReject( @@ -1001,7 +1001,7 @@ const assert = require('assert/strict'); ``` ```mjs -import assert from 'assert/strict'; +import assert from 'node:assert/strict'; assert.doesNotReject(Promise.reject(new TypeError('Wrong value'))) .then(() => { @@ -1010,7 +1010,7 @@ assert.doesNotReject(Promise.reject(new TypeError('Wrong value'))) ``` ```cjs -const assert = require('assert/strict'); +const assert = require('node:assert/strict'); assert.doesNotReject(Promise.reject(new TypeError('Wrong value'))) .then(() => { @@ -1059,7 +1059,7 @@ The following, for instance, will throw the [`TypeError`][] because there is no matching error type in the assertion: ```mjs -import assert from 'assert/strict'; +import assert from 'node:assert/strict'; assert.doesNotThrow( () => { @@ -1070,7 +1070,7 @@ assert.doesNotThrow( ``` ```cjs -const assert = require('assert/strict'); +const assert = require('node:assert/strict'); assert.doesNotThrow( () => { @@ -1084,7 +1084,7 @@ However, the following will result in an [`AssertionError`][] with the message 'Got unwanted exception...': ```mjs -import assert from 'assert/strict'; +import assert from 'node:assert/strict'; assert.doesNotThrow( () => { @@ -1095,7 +1095,7 @@ assert.doesNotThrow( ``` ```cjs -const assert = require('assert/strict'); +const assert = require('node:assert/strict'); assert.doesNotThrow( () => { @@ -1110,7 +1110,7 @@ parameter, the value of `message` will be appended to the [`AssertionError`][] message: ```mjs -import assert from 'assert/strict'; +import assert from 'node:assert/strict'; assert.doesNotThrow( () => { @@ -1123,7 +1123,7 @@ assert.doesNotThrow( ``` ```cjs -const assert = require('assert/strict'); +const assert = require('node:assert/strict'); assert.doesNotThrow( () => { @@ -1169,7 +1169,7 @@ using the [`==` operator][]. `NaN` is specially handled and treated as being identical if both sides are `NaN`. ```mjs -import assert from 'assert'; +import assert from 'node:assert'; assert.equal(1, 1); // OK, 1 == 1 @@ -1185,7 +1185,7 @@ assert.equal({ a: { b: 1 } }, { a: { b: 1 } }); ``` ```cjs -const assert = require('assert'); +const assert = require('node:assert'); assert.equal(1, 1); // OK, 1 == 1 @@ -1219,7 +1219,7 @@ error message. If the `message` parameter is an instance of an [`Error`][] then it will be thrown instead of the [`AssertionError`][]. ```mjs -import assert from 'assert/strict'; +import assert from 'node:assert/strict'; assert.fail(); // AssertionError [ERR_ASSERTION]: Failed @@ -1232,7 +1232,7 @@ assert.fail(new TypeError('need array')); ``` ```cjs -const assert = require('assert/strict'); +const assert = require('node:assert/strict'); assert.fail(); // AssertionError [ERR_ASSERTION]: Failed @@ -1277,7 +1277,7 @@ removed from stacktrace (see [`Error.captureStackTrace`][]). If no arguments are given, the default message `Failed` will be used. ```mjs -import assert from 'assert/strict'; +import assert from 'node:assert/strict'; assert.fail('a', 'b'); // AssertionError [ERR_ASSERTION]: 'a' != 'b' @@ -1296,7 +1296,7 @@ assert.fail(1, 2, new TypeError('need array')); ``` ```cjs -const assert = require('assert/strict'); +const assert = require('node:assert/strict'); assert.fail('a', 'b'); // AssertionError [ERR_ASSERTION]: 'a' != 'b' @@ -1320,7 +1320,7 @@ influence on the error message. Example use of `stackStartFn` for truncating the exception's stacktrace: ```mjs -import assert from 'assert/strict'; +import assert from 'node:assert/strict'; function suppressFrame() { assert.fail('a', 'b', undefined, '!==', suppressFrame); @@ -1333,7 +1333,7 @@ suppressFrame(); ``` ```cjs -const assert = require('assert/strict'); +const assert = require('node:assert/strict'); function suppressFrame() { assert.fail('a', 'b', undefined, '!==', suppressFrame); @@ -1368,7 +1368,7 @@ from the error passed to `ifError()` including the potential new frames for `ifError()` itself. ```mjs -import assert from 'assert/strict'; +import assert from 'node:assert/strict'; assert.ifError(null); // OK @@ -1394,7 +1394,7 @@ let err; ``` ```cjs -const assert = require('assert/strict'); +const assert = require('node:assert/strict'); assert.ifError(null); // OK @@ -1438,7 +1438,7 @@ changes: Expects the `string` input to match the regular expression. ```mjs -import assert from 'assert/strict'; +import assert from 'node:assert/strict'; assert.match('I will fail', /pass/); // AssertionError [ERR_ASSERTION]: The input did not match the regular ... @@ -1451,7 +1451,7 @@ assert.match('I will pass', /pass/); ``` ```cjs -const assert = require('assert/strict'); +const assert = require('node:assert/strict'); assert.match('I will fail', /pass/); // AssertionError [ERR_ASSERTION]: The input did not match the regular ... @@ -1523,7 +1523,7 @@ An alias of [`assert.notDeepStrictEqual()`][]. Tests for any deep inequality. Opposite of [`assert.deepEqual()`][]. ```mjs -import assert from 'assert'; +import assert from 'node:assert'; const obj1 = { a: { @@ -1556,7 +1556,7 @@ assert.notDeepEqual(obj1, obj4); ``` ```cjs -const assert = require('assert'); +const assert = require('node:assert'); const obj1 = { a: { @@ -1635,14 +1635,14 @@ changes: Tests for deep strict inequality. Opposite of [`assert.deepStrictEqual()`][]. ```mjs -import assert from 'assert/strict'; +import assert from 'node:assert/strict'; assert.notDeepStrictEqual({ a: 1 }, { a: '1' }); // OK ``` ```cjs -const assert = require('assert/strict'); +const assert = require('node:assert/strict'); assert.notDeepStrictEqual({ a: 1 }, { a: '1' }); // OK @@ -1687,7 +1687,7 @@ Tests shallow, coercive inequality with the [`!=` operator][]. `NaN` is specially handled and treated as being identical if both sides are `NaN`. ```mjs -import assert from 'assert'; +import assert from 'node:assert'; assert.notEqual(1, 2); // OK @@ -1700,7 +1700,7 @@ assert.notEqual(1, '1'); ``` ```cjs -const assert = require('assert'); +const assert = require('node:assert'); assert.notEqual(1, 2); // OK @@ -1736,7 +1736,7 @@ Tests strict inequality between the `actual` and `expected` parameters as determined by [`Object.is()`][]. ```mjs -import assert from 'assert/strict'; +import assert from 'node:assert/strict'; assert.notStrictEqual(1, 2); // OK @@ -1751,7 +1751,7 @@ assert.notStrictEqual(1, '1'); ``` ```cjs -const assert = require('assert/strict'); +const assert = require('node:assert/strict'); assert.notStrictEqual(1, 2); // OK @@ -1800,7 +1800,7 @@ Be aware that in the `repl` the error message will be different to the one thrown in a file! See below for further details. ```mjs -import assert from 'assert/strict'; +import assert from 'node:assert/strict'; assert.ok(true); // OK @@ -1835,7 +1835,7 @@ assert.ok(0); ``` ```cjs -const assert = require('assert/strict'); +const assert = require('node:assert/strict'); assert.ok(true); // OK @@ -1870,7 +1870,7 @@ assert.ok(0); ``` ```mjs -import assert from 'assert/strict'; +import assert from 'node:assert/strict'; // Using `assert()` works the same: assert(0); @@ -1880,7 +1880,7 @@ assert(0); ``` ```cjs -const assert = require('assert'); +const assert = require('node:assert'); // Using `assert()` works the same: assert(0); @@ -1921,7 +1921,7 @@ If specified, `message` will be the message provided by the [`AssertionError`][] if the `asyncFn` fails to reject. ```mjs -import assert from 'assert/strict'; +import assert from 'node:assert/strict'; await assert.rejects( async () => { @@ -1935,7 +1935,7 @@ await assert.rejects( ``` ```cjs -const assert = require('assert/strict'); +const assert = require('node:assert/strict'); (async () => { await assert.rejects( @@ -1951,7 +1951,7 @@ const assert = require('assert/strict'); ``` ```mjs -import assert from 'assert/strict'; +import assert from 'node:assert/strict'; await assert.rejects( async () => { @@ -1966,7 +1966,7 @@ await assert.rejects( ``` ```cjs -const assert = require('assert/strict'); +const assert = require('node:assert/strict'); (async () => { await assert.rejects( @@ -1983,7 +1983,7 @@ const assert = require('assert/strict'); ``` ```mjs -import assert from 'assert/strict'; +import assert from 'node:assert/strict'; assert.rejects( Promise.reject(new Error('Wrong value')), @@ -1994,7 +1994,7 @@ assert.rejects( ``` ```cjs -const assert = require('assert/strict'); +const assert = require('node:assert/strict'); assert.rejects( Promise.reject(new Error('Wrong value')), @@ -2028,7 +2028,7 @@ Tests strict equality between the `actual` and `expected` parameters as determined by [`Object.is()`][]. ```mjs -import assert from 'assert/strict'; +import assert from 'node:assert/strict'; assert.strictEqual(1, 2); // AssertionError [ERR_ASSERTION]: Expected inputs to be strictly equal: @@ -2056,7 +2056,7 @@ assert.strictEqual(1, '1', new TypeError('Inputs are not identical')); ``` ```cjs -const assert = require('assert/strict'); +const assert = require('node:assert/strict'); assert.strictEqual(1, 2); // AssertionError [ERR_ASSERTION]: Expected inputs to be strictly equal: @@ -2126,7 +2126,7 @@ fails. Custom validation object/error instance: ```mjs -import assert from 'assert/strict'; +import assert from 'node:assert/strict'; const err = new TypeError('Wrong value'); err.code = 404; @@ -2195,7 +2195,7 @@ throws( ``` ```cjs -const assert = require('assert/strict'); +const assert = require('node:assert/strict'); const err = new TypeError('Wrong value'); err.code = 404; @@ -2266,7 +2266,7 @@ throws( Validate instanceof using constructor: ```mjs -import assert from 'assert/strict'; +import assert from 'node:assert/strict'; assert.throws( () => { @@ -2277,7 +2277,7 @@ assert.throws( ``` ```cjs -const assert = require('assert/strict'); +const assert = require('node:assert/strict'); assert.throws( () => { @@ -2293,7 +2293,7 @@ Using a regular expression runs `.toString` on the error object, and will therefore also include the error name. ```mjs -import assert from 'assert/strict'; +import assert from 'node:assert/strict'; assert.throws( () => { @@ -2304,7 +2304,7 @@ assert.throws( ``` ```cjs -const assert = require('assert/strict'); +const assert = require('node:assert/strict'); assert.throws( () => { @@ -2320,7 +2320,7 @@ The function must return `true` to indicate all internal validations passed. It will otherwise fail with an [`AssertionError`][]. ```mjs -import assert from 'assert/strict'; +import assert from 'node:assert/strict'; assert.throws( () => { @@ -2341,7 +2341,7 @@ assert.throws( ``` ```cjs -const assert = require('assert/strict'); +const assert = require('node:assert/strict'); assert.throws( () => { @@ -2369,7 +2369,7 @@ message as the thrown error message is going to result in an a string as the second argument gets considered: ```mjs -import assert from 'assert/strict'; +import assert from 'node:assert/strict'; function throwingFirst() { throw new Error('First'); @@ -2405,7 +2405,7 @@ assert.throws(throwingFirst, /Second$/); ``` ```cjs -const assert = require('assert/strict'); +const assert = require('node:assert/strict'); function throwingFirst() { throw new Error('First'); diff --git a/doc/api/async_context.md b/doc/api/async_context.md index 70144b6d323740..1720c0bbad8940 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 4a6af435299a25..9439edbe224159 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) => { @@ -788,7 +788,7 @@ V8. This means that programs using promises or `async`/`await` will not get correct execution and trigger ids for promise callback contexts by default. ```mjs -import { executionAsyncId, triggerAsyncId } from 'async_hooks'; +import { executionAsyncId, triggerAsyncId } from 'node:async_hooks'; Promise.resolve(1729).then(() => { console.log(`eid ${executionAsyncId()} tid ${triggerAsyncId()}`); @@ -798,7 +798,7 @@ Promise.resolve(1729).then(() => { ``` ```cjs -const { executionAsyncId, triggerAsyncId } = require('async_hooks'); +const { executionAsyncId, triggerAsyncId } = require('node:async_hooks'); Promise.resolve(1729).then(() => { console.log(`eid ${executionAsyncId()} tid ${triggerAsyncId()}`); @@ -816,7 +816,7 @@ Installing async hooks via `async_hooks.createHook` enables promise execution tracking: ```mjs -import { createHook, executionAsyncId, triggerAsyncId } from 'async_hooks'; +import { createHook, executionAsyncId, triggerAsyncId } from 'node:async_hooks'; createHook({ init() {} }).enable(); // forces PromiseHooks to be enabled. Promise.resolve(1729).then(() => { console.log(`eid ${executionAsyncId()} tid ${triggerAsyncId()}`); @@ -826,7 +826,7 @@ Promise.resolve(1729).then(() => { ``` ```cjs -const { createHook, executionAsyncId, triggerAsyncId } = require('async_hooks'); +const { createHook, executionAsyncId, triggerAsyncId } = require('node:async_hooks'); createHook({ init() {} }).enable(); // forces PromiseHooks to be enabled. Promise.resolve(1729).then(() => { diff --git a/doc/api/buffer.md b/doc/api/buffer.md index 156db8a8dfdca5..1bdc976fd12e42 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); @@ -104,7 +104,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'); @@ -120,7 +120,7 @@ console.log(Buffer.from('fhqwhgads', 'utf16le')); ``` ```cjs -const { Buffer } = require('buffer'); +const { Buffer } = require('node:buffer'); const buf = Buffer.from('hello world', 'utf8'); @@ -199,7 +199,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 @@ -213,7 +213,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 @@ -265,7 +265,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); @@ -276,7 +276,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); @@ -290,7 +290,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( @@ -304,7 +304,7 @@ console.log(uint16array); ``` ```cjs -const { Buffer } = require('buffer'); +const { Buffer } = require('node:buffer'); const buf = Buffer.from('hello', 'utf16le'); const uint16array = new Uint16Array( @@ -323,7 +323,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); @@ -350,7 +350,7 @@ console.log(buf2); ``` ```cjs -const { Buffer } = require('buffer'); +const { Buffer } = require('node:buffer'); const arr = new Uint16Array(2); @@ -381,7 +381,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); @@ -391,7 +391,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); @@ -420,7 +420,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]); @@ -434,7 +434,7 @@ for (const b of buf) { ``` ```cjs -const { Buffer } = require('buffer'); +const { Buffer } = require('node:buffer'); const buf = Buffer.from([1, 2, 3]); @@ -484,7 +484,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. @@ -579,8 +579,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']); @@ -606,8 +606,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']); @@ -670,7 +670,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); @@ -679,7 +679,7 @@ console.log(buf); ``` ```cjs -const { Buffer } = require('buffer'); +const { Buffer } = require('node:buffer'); const buf = Buffer.alloc(5); @@ -695,7 +695,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'); @@ -704,7 +704,7 @@ console.log(buf); ``` ```cjs -const { Buffer } = require('buffer'); +const { Buffer } = require('node:buffer'); const buf = Buffer.alloc(5, 'a'); @@ -716,7 +716,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'); @@ -725,7 +725,7 @@ console.log(buf); ``` ```cjs -const { Buffer } = require('buffer'); +const { Buffer } = require('node:buffer'); const buf = Buffer.alloc(11, 'aGVsbG8gd29ybGQ=', 'base64'); @@ -766,7 +766,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); @@ -780,7 +780,7 @@ console.log(buf); ``` ```cjs -const { Buffer } = require('buffer'); +const { Buffer } = require('node:buffer'); const buf = Buffer.allocUnsafe(10); @@ -845,7 +845,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 = []; @@ -865,7 +865,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 = []; @@ -916,7 +916,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'; @@ -926,7 +926,7 @@ console.log(`${str}: ${str.length} characters, ` + ``` ```cjs -const { Buffer } = require('buffer'); +const { Buffer } = require('node:buffer'); const str = '\u00bd + \u00bc = \u00be'; @@ -959,7 +959,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'); @@ -971,7 +971,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'); @@ -1012,7 +1012,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. @@ -1033,7 +1033,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. @@ -1068,14 +1068,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]); @@ -1106,7 +1106,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); @@ -1127,7 +1127,7 @@ console.log(buf); ``` ```cjs -const { Buffer } = require('buffer'); +const { Buffer } = require('node:buffer'); const arr = new Uint16Array(2); @@ -1151,7 +1151,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); @@ -1161,7 +1161,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); @@ -1180,7 +1180,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 @@ -1192,7 +1192,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 @@ -1215,7 +1215,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); @@ -1229,7 +1229,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); @@ -1259,14 +1259,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: @@ -1276,7 +1276,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]() { @@ -1289,7 +1289,7 @@ const buf = Buffer.from(new Foo(), 'utf8'); ``` ```cjs -const { Buffer } = require('buffer'); +const { Buffer } = require('node:buffer'); class Foo { [Symbol.toPrimitive]() { @@ -1317,7 +1317,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'); @@ -1331,7 +1331,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'); @@ -1359,7 +1359,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 @@ -1369,7 +1369,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 @@ -1391,7 +1391,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 @@ -1407,7 +1407,7 @@ console.log(Buffer.isEncoding('')); ``` ```cjs -const { Buffer } = require('buffer'); +const { Buffer } = require('node:buffer'); console.log(Buffer.isEncoding('utf8')); // Prints: true @@ -1448,7 +1448,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 @@ -1466,7 +1466,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 @@ -1492,7 +1492,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); @@ -1502,7 +1502,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); @@ -1527,7 +1527,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]); @@ -1539,7 +1539,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]); @@ -1584,7 +1584,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'); @@ -1606,7 +1606,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'); @@ -1632,7 +1632,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]); @@ -1646,7 +1646,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]); @@ -1685,7 +1685,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); @@ -1706,7 +1706,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); @@ -1727,7 +1727,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`. @@ -1746,7 +1746,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`. @@ -1776,7 +1776,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`. @@ -1795,7 +1795,7 @@ for (const pair of buf.entries()) { ``` ```cjs -const { Buffer } = require('buffer'); +const { Buffer } = require('node:buffer'); // Log the entire contents of a `Buffer`. @@ -1832,7 +1832,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'); @@ -1845,7 +1845,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'); @@ -1894,7 +1894,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'. @@ -1905,7 +1905,7 @@ console.log(b.toString()); ``` ```cjs -const { Buffer } = require('buffer'); +const { Buffer } = require('node:buffer'); // Fill a `Buffer` with the ASCII character 'h'. @@ -1923,7 +1923,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. @@ -1932,7 +1932,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. @@ -1944,7 +1944,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); @@ -1957,7 +1957,7 @@ console.log(buf.fill('zz', 'hex')); ``` ```cjs -const { Buffer } = require('buffer'); +const { Buffer } = require('node:buffer'); const buf = Buffer.allocUnsafe(5); @@ -1985,7 +1985,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'); @@ -2006,7 +2006,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'); @@ -2061,7 +2061,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'); @@ -2087,7 +2087,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'); @@ -2121,7 +2121,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'); @@ -2139,7 +2139,7 @@ console.log(b.indexOf('b', [])); ``` ```cjs -const { Buffer } = require('buffer'); +const { Buffer } = require('node:buffer'); const b = Buffer.from('abcdef'); @@ -2171,7 +2171,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'); @@ -2188,7 +2188,7 @@ for (const key of buf.keys()) { ``` ```cjs -const { Buffer } = require('buffer'); +const { Buffer } = require('node:buffer'); const buf = Buffer.from('buffer'); @@ -2228,7 +2228,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'); @@ -2256,7 +2256,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'); @@ -2292,7 +2292,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'); @@ -2313,7 +2313,7 @@ console.log(b.lastIndexOf('b', [])); ``` ```cjs -const { Buffer } = require('buffer'); +const { Buffer } = require('node:buffer'); const b = Buffer.from('abcdef'); @@ -2346,7 +2346,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. @@ -2362,7 +2362,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. @@ -2446,7 +2446,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]); @@ -2455,7 +2455,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]); @@ -2487,7 +2487,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]); @@ -2496,7 +2496,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]); @@ -2522,7 +2522,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]); @@ -2531,7 +2531,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]); @@ -2557,7 +2557,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]); @@ -2568,7 +2568,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]); @@ -2596,7 +2596,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]); @@ -2605,7 +2605,7 @@ console.log(buf.readFloatBE(0)); ``` ```cjs -const { Buffer } = require('buffer'); +const { Buffer } = require('node:buffer'); const buf = Buffer.from([1, 2, 3, 4]); @@ -2631,7 +2631,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]); @@ -2642,7 +2642,7 @@ console.log(buf.readFloatLE(1)); ``` ```cjs -const { Buffer } = require('buffer'); +const { Buffer } = require('node:buffer'); const buf = Buffer.from([1, 2, 3, 4]); @@ -2672,7 +2672,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]); @@ -2685,7 +2685,7 @@ console.log(buf.readInt8(2)); ``` ```cjs -const { Buffer } = require('buffer'); +const { Buffer } = require('node:buffer'); const buf = Buffer.from([-1, 5]); @@ -2717,7 +2717,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]); @@ -2726,7 +2726,7 @@ console.log(buf.readInt16BE(0)); ``` ```cjs -const { Buffer } = require('buffer'); +const { Buffer } = require('node:buffer'); const buf = Buffer.from([0, 5]); @@ -2755,7 +2755,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]); @@ -2766,7 +2766,7 @@ console.log(buf.readInt16LE(1)); ``` ```cjs -const { Buffer } = require('buffer'); +const { Buffer } = require('node:buffer'); const buf = Buffer.from([0, 5]); @@ -2796,7 +2796,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]); @@ -2805,7 +2805,7 @@ console.log(buf.readInt32BE(0)); ``` ```cjs -const { Buffer } = require('buffer'); +const { Buffer } = require('node:buffer'); const buf = Buffer.from([0, 0, 0, 5]); @@ -2834,7 +2834,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]); @@ -2845,7 +2845,7 @@ console.log(buf.readInt32LE(1)); ``` ```cjs -const { Buffer } = require('buffer'); +const { Buffer } = require('node:buffer'); const buf = Buffer.from([0, 0, 0, 5]); @@ -2877,7 +2877,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]); @@ -2890,7 +2890,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]); @@ -2924,7 +2924,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]); @@ -2933,7 +2933,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]); @@ -2966,7 +2966,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]); @@ -2979,7 +2979,7 @@ console.log(buf.readUInt8(2)); ``` ```cjs -const { Buffer } = require('buffer'); +const { Buffer } = require('node:buffer'); const buf = Buffer.from([1, -2]); @@ -3017,7 +3017,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]); @@ -3028,7 +3028,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]); @@ -3064,7 +3064,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]); @@ -3077,7 +3077,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]); @@ -3115,7 +3115,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]); @@ -3124,7 +3124,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]); @@ -3158,7 +3158,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]); @@ -3169,7 +3169,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]); @@ -3208,7 +3208,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]); @@ -3219,7 +3219,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]); @@ -3258,7 +3258,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]); @@ -3267,7 +3267,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]); @@ -3298,7 +3298,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`. @@ -3322,7 +3322,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`. @@ -3349,7 +3349,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'); @@ -3367,7 +3367,7 @@ console.log(buf.subarray(-5, -2).toString()); ``` ```cjs -const { Buffer } = require('buffer'); +const { Buffer } = require('node:buffer'); const buf = Buffer.from('buffer'); @@ -3419,7 +3419,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'); @@ -3441,7 +3441,7 @@ console.log(buf.toString()); ``` ```cjs -const { Buffer } = require('buffer'); +const { Buffer } = require('node:buffer'); const buf = Buffer.from('buffer'); @@ -3475,7 +3475,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]); @@ -3494,7 +3494,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]); @@ -3516,14 +3516,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. @@ -3542,7 +3542,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]); @@ -3561,7 +3561,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]); @@ -3591,7 +3591,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]); @@ -3610,7 +3610,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]); @@ -3643,7 +3643,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); @@ -3662,7 +3662,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); @@ -3702,7 +3702,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); @@ -3727,7 +3727,7 @@ console.log(buf2.toString(undefined, 0, 3)); ``` ```cjs -const { Buffer } = require('buffer'); +const { Buffer } = require('node:buffer'); const buf1 = Buffer.allocUnsafe(26); @@ -3763,7 +3763,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'); @@ -3791,7 +3791,7 @@ for (const value of buf) { ``` ```cjs -const { Buffer } = require('buffer'); +const { Buffer } = require('node:buffer'); const buf = Buffer.from('buffer'); @@ -3838,7 +3838,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); @@ -3856,7 +3856,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); @@ -3891,7 +3891,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); @@ -3902,7 +3902,7 @@ console.log(buf); ``` ```cjs -const { Buffer } = require('buffer'); +const { Buffer } = require('node:buffer'); const buf = Buffer.allocUnsafe(8); @@ -3930,7 +3930,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); @@ -3941,7 +3941,7 @@ console.log(buf); ``` ```cjs -const { Buffer } = require('buffer'); +const { Buffer } = require('node:buffer'); const buf = Buffer.allocUnsafe(8); @@ -3975,7 +3975,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); @@ -3986,7 +3986,7 @@ console.log(buf); ``` ```cjs -const { Buffer } = require('buffer'); +const { Buffer } = require('node:buffer'); const buf = Buffer.allocUnsafe(8); @@ -4018,7 +4018,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); @@ -4029,7 +4029,7 @@ console.log(buf); ``` ```cjs -const { Buffer } = require('buffer'); +const { Buffer } = require('node:buffer'); const buf = Buffer.allocUnsafe(8); @@ -4062,7 +4062,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); @@ -4073,7 +4073,7 @@ console.log(buf); ``` ```cjs -const { Buffer } = require('buffer'); +const { Buffer } = require('node:buffer'); const buf = Buffer.allocUnsafe(8); @@ -4104,7 +4104,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); @@ -4115,7 +4115,7 @@ console.log(buf); ``` ```cjs -const { Buffer } = require('buffer'); +const { Buffer } = require('node:buffer'); const buf = Buffer.allocUnsafe(8); @@ -4145,7 +4145,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); @@ -4156,7 +4156,7 @@ console.log(buf); ``` ```cjs -const { Buffer } = require('buffer'); +const { Buffer } = require('node:buffer'); const buf = Buffer.allocUnsafe(4); @@ -4186,7 +4186,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); @@ -4197,7 +4197,7 @@ console.log(buf); ``` ```cjs -const { Buffer } = require('buffer'); +const { Buffer } = require('node:buffer'); const buf = Buffer.allocUnsafe(4); @@ -4230,7 +4230,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); @@ -4242,7 +4242,7 @@ console.log(buf); ``` ```cjs -const { Buffer } = require('buffer'); +const { Buffer } = require('node:buffer'); const buf = Buffer.allocUnsafe(2); @@ -4276,7 +4276,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); @@ -4287,7 +4287,7 @@ console.log(buf); ``` ```cjs -const { Buffer } = require('buffer'); +const { Buffer } = require('node:buffer'); const buf = Buffer.allocUnsafe(2); @@ -4320,7 +4320,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); @@ -4331,7 +4331,7 @@ console.log(buf); ``` ```cjs -const { Buffer } = require('buffer'); +const { Buffer } = require('node:buffer'); const buf = Buffer.allocUnsafe(2); @@ -4364,7 +4364,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); @@ -4375,7 +4375,7 @@ console.log(buf); ``` ```cjs -const { Buffer } = require('buffer'); +const { Buffer } = require('node:buffer'); const buf = Buffer.allocUnsafe(4); @@ -4408,7 +4408,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); @@ -4419,7 +4419,7 @@ console.log(buf); ``` ```cjs -const { Buffer } = require('buffer'); +const { Buffer } = require('node:buffer'); const buf = Buffer.allocUnsafe(4); @@ -4452,7 +4452,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); @@ -4463,7 +4463,7 @@ console.log(buf); ``` ```cjs -const { Buffer } = require('buffer'); +const { Buffer } = require('node:buffer'); const buf = Buffer.allocUnsafe(6); @@ -4496,7 +4496,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); @@ -4507,7 +4507,7 @@ console.log(buf); ``` ```cjs -const { Buffer } = require('buffer'); +const { Buffer } = require('node:buffer'); const buf = Buffer.allocUnsafe(6); @@ -4545,7 +4545,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); @@ -4559,7 +4559,7 @@ console.log(buf); ``` ```cjs -const { Buffer } = require('buffer'); +const { Buffer } = require('node:buffer'); const buf = Buffer.allocUnsafe(4); @@ -4600,7 +4600,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); @@ -4612,7 +4612,7 @@ console.log(buf); ``` ```cjs -const { Buffer } = require('buffer'); +const { Buffer } = require('node:buffer'); const buf = Buffer.allocUnsafe(4); @@ -4651,7 +4651,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); @@ -4663,7 +4663,7 @@ console.log(buf); ``` ```cjs -const { Buffer } = require('buffer'); +const { Buffer } = require('node:buffer'); const buf = Buffer.allocUnsafe(4); @@ -4702,7 +4702,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); @@ -4713,7 +4713,7 @@ console.log(buf); ``` ```cjs -const { Buffer } = require('buffer'); +const { Buffer } = require('node:buffer'); const buf = Buffer.allocUnsafe(4); @@ -4751,7 +4751,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); @@ -4762,7 +4762,7 @@ console.log(buf); ``` ```cjs -const { Buffer } = require('buffer'); +const { Buffer } = require('node:buffer'); const buf = Buffer.allocUnsafe(4); @@ -4802,7 +4802,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); @@ -4813,7 +4813,7 @@ console.log(buf); ``` ```cjs -const { Buffer } = require('buffer'); +const { Buffer } = require('node:buffer'); const buf = Buffer.allocUnsafe(6); @@ -4853,7 +4853,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); @@ -4864,7 +4864,7 @@ console.log(buf); ``` ```cjs -const { Buffer } = require('buffer'); +const { Buffer } = require('node:buffer'); const buf = Buffer.allocUnsafe(6); @@ -5009,11 +5009,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)` @@ -5138,7 +5138,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')); @@ -5146,7 +5146,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 ad712eb8786f59..0f98613f729891 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); @@ -198,7 +198,7 @@ directly by the shell and special characters (vary based on need to be dealt with accordingly: ```js -const { exec } = require('child_process'); +const { exec } = require('node:child_process'); exec('"/path/to/test file/test.sh" arg1 arg2'); // Double quotes are used so that the space in the path is not interpreted as @@ -226,7 +226,7 @@ stderr output. If `encoding` is `'buffer'`, or an unrecognized character encoding, `Buffer` objects will be passed to the callback instead. ```js -const { exec } = require('child_process'); +const { exec } = require('node:child_process'); exec('cat *.js missing_file | wc -l', (error, stdout, stderr) => { if (error) { console.error(`exec error: ${error}`); @@ -252,8 +252,8 @@ rejected promise is returned, with the same `error` object given in the callback, but with two additional properties `stdout` and `stderr`. ```js -const util = require('util'); -const exec = util.promisify(require('child_process').exec); +const util = require('node:util'); +const exec = util.promisify(require('node:child_process').exec); async function lsExample() { const { stdout, stderr } = await exec('ls'); @@ -268,7 +268,7 @@ If the `signal` option is enabled, calling `.abort()` on the corresponding the error passed to the callback will be an `AbortError`: ```js -const { exec } = require('child_process'); +const { exec } = require('node:child_process'); const controller = new AbortController(); const { signal } = controller; const child = exec('grep ssh', { signal }, (error) => { @@ -338,7 +338,7 @@ not spawned, behaviors such as I/O redirection and file globbing are not supported. ```js -const { execFile } = require('child_process'); +const { execFile } = require('node:child_process'); const child = execFile('node', ['--version'], (error, stdout, stderr) => { if (error) { throw error; @@ -362,8 +362,8 @@ rejected promise is returned, with the same `error` object given in the callback, but with two additional properties `stdout` and `stderr`. ```js -const util = require('util'); -const execFile = util.promisify(require('child_process').execFile); +const util = require('node:util'); +const execFile = util.promisify(require('node:child_process').execFile); async function getVersion() { const { stdout } = await execFile('node', ['--version']); console.log(stdout); @@ -380,7 +380,7 @@ If the `signal` option is enabled, calling `.abort()` on the corresponding the error passed to the callback will be an `AbortError`: ```js -const { execFile } = require('child_process'); +const { execFile } = require('node:child_process'); const controller = new AbortController(); const { signal } = controller; const child = execFile('node', ['--version'], { signal }, (error) => { @@ -506,7 +506,7 @@ if (process.argv[2] === 'child') { console.log(`Hello from ${process.argv[2]}!`); }, 1_000); } else { - const { fork } = require('child_process'); + const { fork } = require('node:child_process'); const controller = new AbortController(); const { signal } = controller; const child = fork(__filename, ['child'], { signal }); @@ -625,7 +625,7 @@ Example of running `ls -lh /usr`, capturing `stdout`, `stderr`, and the exit code: ```js -const { spawn } = require('child_process'); +const { spawn } = require('node:child_process'); const ls = spawn('ls', ['-lh', '/usr']); ls.stdout.on('data', (data) => { @@ -644,7 +644,7 @@ ls.on('close', (code) => { Example: A very elaborate way to run `ps ax | grep ssh` ```js -const { spawn } = require('child_process'); +const { spawn } = require('node:child_process'); const ps = spawn('ps', ['ax']); const grep = spawn('grep', ['ssh']); @@ -681,7 +681,7 @@ grep.on('close', (code) => { Example of checking for failed `spawn`: ```js -const { spawn } = require('child_process'); +const { spawn } = require('node:child_process'); const subprocess = spawn('bad_command'); subprocess.on('error', (err) => { @@ -702,7 +702,7 @@ If the `signal` option is enabled, calling `.abort()` on the corresponding the error passed to the callback will be an `AbortError`: ```js -const { spawn } = require('child_process'); +const { spawn } = require('node:child_process'); const controller = new AbortController(); const { signal } = controller; const grep = spawn('grep', ['ssh'], { signal }); @@ -745,7 +745,7 @@ Example of a long-running process, by detaching and also ignoring its parent `stdio` file descriptors, in order to ignore the parent's termination: ```js -const { spawn } = require('child_process'); +const { spawn } = require('node:child_process'); const subprocess = spawn(process.argv[0], ['child_program.js'], { detached: true, @@ -758,8 +758,8 @@ subprocess.unref(); Alternatively one can redirect the child process' output into files: ```js -const fs = require('fs'); -const { spawn } = require('child_process'); +const fs = require('node:fs'); +const { spawn } = require('node:child_process'); const out = fs.openSync('./out.log', 'a'); const err = fs.openSync('./out.log', 'a'); @@ -853,7 +853,7 @@ pipes between the parent and child. The value is one of the following: default is `'ignore'`. ```js -const { spawn } = require('child_process'); +const { spawn } = require('node:child_process'); // Child will use parent's stdios. spawn('prg', [], { stdio: 'inherit' }); @@ -1152,7 +1152,7 @@ streams. The `'close'` event will always emit after [`'exit'`][] was already emitted, or [`'error'`][] if the child failed to spawn. ```js -const { spawn } = require('child_process'); +const { spawn } = require('node:child_process'); const ls = spawn('ls', ['-lh', '/usr']); ls.stdout.on('data', (data) => { @@ -1348,7 +1348,7 @@ signal(7) for a list of available signals. This function returns `true` if kill(2) succeeds, and `false` otherwise. ```js -const { spawn } = require('child_process'); +const { spawn } = require('node:child_process'); const grep = spawn('grep', ['ssh']); grep.on('close', (code, signal) => { @@ -1382,7 +1382,7 @@ new process in a shell or with the use of the `shell` option of `ChildProcess`: ```js 'use strict'; -const { spawn } = require('child_process'); +const { spawn } = require('node:child_process'); const subprocess = spawn( 'sh', @@ -1427,7 +1427,7 @@ fails to spawn due to errors, then the value is `undefined` and `error` is emitted. ```js -const { spawn } = require('child_process'); +const { spawn } = require('node:child_process'); const grep = spawn('grep', ['ssh']); console.log(`Spawned child pid: ${grep.pid}`); @@ -1445,7 +1445,7 @@ restore the removed reference count for the child process, forcing the parent to wait for the child to exit before exiting itself. ```js -const { spawn } = require('child_process'); +const { spawn } = require('node:child_process'); const subprocess = spawn(process.argv[0], ['child_program.js'], { detached: true, @@ -1495,7 +1495,7 @@ message might not be the same as what is originally sent. For example, in the parent script: ```js -const cp = require('child_process'); +const cp = require('node:child_process'); const n = cp.fork(`${__dirname}/sub.js`); n.on('message', (m) => { @@ -1553,10 +1553,10 @@ The `sendHandle` argument can be used, for instance, to pass the handle of a TCP server object to the child process as illustrated in the example below: ```js -const subprocess = require('child_process').fork('subprocess.js'); +const subprocess = require('node:child_process').fork('subprocess.js'); // Open up the server object and send the handle. -const server = require('net').createServer(); +const server = require('node:net').createServer(); server.on('connection', (socket) => { socket.end('handled by parent'); }); @@ -1580,11 +1580,11 @@ process.on('message', (m, server) => { Once the server is now shared between the parent and child, some connections can be handled by the parent and some by the child. -While the example above uses a server created using the `net` module, `dgram` -module servers use exactly the same workflow with the exceptions of listening on -a `'message'` event instead of `'connection'` and using `server.bind()` instead -of `server.listen()`. This is, however, currently only supported on Unix -platforms. +While the example above uses a server created using the `node:net` module, +`node:dgram` module servers use exactly the same workflow with the exceptions of +listening on a `'message'` event instead of `'connection'` and using +`server.bind()` instead of `server.listen()`. This is, however, currently only +supported on Unix platforms. #### Example: sending a socket object @@ -1593,13 +1593,13 @@ socket to the child process. The example below spawns two children that each handle connections with "normal" or "special" priority: ```js -const { fork } = require('child_process'); +const { fork } = require('node:child_process'); const normal = fork('subprocess.js', ['normal']); const special = fork('subprocess.js', ['special']); // Open up the server and send sockets to child. Use pauseOnConnect to prevent // the sockets from being read before they are sent to the child process. -const server = require('net').createServer({ pauseOnConnect: true }); +const server = require('node:net').createServer({ pauseOnConnect: true }); server.on('connection', (socket) => { // If this is special priority... @@ -1724,9 +1724,9 @@ pipe, so only the parent's `subprocess.stdio[1]` is a stream, all other values in the array are `null`. ```js -const assert = require('assert'); -const fs = require('fs'); -const child_process = require('child_process'); +const assert = require('node:assert'); +const fs = require('node:fs'); +const child_process = require('node:child_process'); const subprocess = child_process.spawn('ls', { stdio: [ @@ -1766,7 +1766,7 @@ then this will be `null`. refer to the same value. ```js -const { spawn } = require('child_process'); +const { spawn } = require('node:child_process'); const subprocess = spawn('ls'); @@ -1792,7 +1792,7 @@ independently of the child, unless there is an established IPC channel between the child and the parent. ```js -const { spawn } = require('child_process'); +const { spawn } = require('node:child_process'); const subprocess = spawn(process.argv[0], ['child_program.js'], { detached: true, @@ -1833,7 +1833,7 @@ added: --> Child processes support a serialization mechanism for IPC that is based on the -[serialization API of the `v8` module][v8.serdes], based on the +[serialization API of the `node:v8` module][v8.serdes], based on the [HTML structured clone algorithm][]. This is generally more powerful and supports more built-in JavaScript object types, such as `BigInt`, `Map` and `Set`, `ArrayBuffer` and `TypedArray`, `Buffer`, `Error`, `RegExp` etc. diff --git a/doc/api/cli.md b/doc/api/cli.md index 74d300e368a010..302367273db0d1 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` @@ -364,7 +364,7 @@ See [customizing ESM specifier resolution][] for example usage. added: v9.6.0 --> -Enable experimental ES Module support in the `vm` module. +Enable experimental ES Module support in the `node:vm` module. ### `--experimental-wasi-unstable-preview1` diff --git a/doc/api/cluster.md b/doc/api/cluster.md index 202082ed5c9ce0..ce38048678c689 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`); @@ -982,7 +982,7 @@ The defaults above apply to the first call only; the defaults for later calls are the current values at the time of `cluster.setupPrimary()` is called. ```mjs -import cluster from 'cluster'; +import cluster from 'node:cluster'; cluster.setupPrimary({ exec: 'worker.js', @@ -998,7 +998,7 @@ cluster.fork(); // http worker ``` ```cjs -const cluster = require('cluster'); +const cluster = require('node:cluster'); cluster.setupPrimary({ exec: 'worker.js', @@ -1026,7 +1026,7 @@ added: v0.7.0 A reference to the current worker object. Not available in the primary process. ```mjs -import cluster from 'cluster'; +import cluster from 'node:cluster'; if (cluster.isPrimary) { console.log('I am primary'); @@ -1038,7 +1038,7 @@ if (cluster.isPrimary) { ``` ```cjs -const cluster = require('cluster'); +const cluster = require('node:cluster'); if (cluster.isPrimary) { console.log('I am primary'); @@ -1067,7 +1067,7 @@ advance. However, it is guaranteed that the removal from the `cluster.workers` list happens before the last `'disconnect'` or `'exit'` event is emitted. ```mjs -import cluster from 'cluster'; +import cluster from 'node:cluster'; for (const worker of Object.values(cluster.workers)) { worker.send('big announcement to all workers'); @@ -1075,7 +1075,7 @@ for (const worker of Object.values(cluster.workers)) { ``` ```cjs -const cluster = require('cluster'); +const cluster = require('node:cluster'); for (const worker of Object.values(cluster.workers)) { worker.send('big announcement to all workers'); diff --git a/doc/api/console.md b/doc/api/console.md index bd890e20a79a59..685fe370a04028 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 b51a1abee0b011..930ca11c04c2de 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 ...}'); @@ -2859,7 +2859,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` @@ -3310,10 +3310,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]; @@ -3335,11 +3335,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]; @@ -3396,10 +3396,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]; @@ -3421,11 +3421,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]; @@ -3638,7 +3638,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; @@ -3649,7 +3649,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; @@ -3727,7 +3727,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, @@ -3749,7 +3749,7 @@ generateKeyPair('rsa', { ```cjs const { generateKeyPair, -} = require('crypto'); +} = require('node:crypto'); generateKeyPair('rsa', { modulusLength: 4096, @@ -3839,7 +3839,7 @@ and to keep the passphrase confidential. ```mjs const { generateKeyPairSync -} = await import('crypto'); +} = await import('node:crypto'); const { publicKey, @@ -3862,7 +3862,7 @@ const { ```cjs const { generateKeyPairSync, -} = require('crypto'); +} = require('node:crypto'); const { publicKey, @@ -3908,7 +3908,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 @@ -3917,7 +3917,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 @@ -4055,7 +4055,7 @@ added: v0.9.3 ```mjs const { getCiphers -} = await import('crypto'); +} = await import('node:crypto'); console.log(getCiphers()); // ['aes-128-cbc', 'aes-128-ccm', ...] ``` @@ -4063,7 +4063,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', ...] ``` @@ -4079,7 +4079,7 @@ added: v2.3.0 ```mjs const { getCurves -} = await import('crypto'); +} = await import('node:crypto'); console.log(getCurves()); // ['Oakley-EC2N-3', 'Oakley-EC2N-4', ...] ``` @@ -4087,7 +4087,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', ...] ``` @@ -4117,7 +4117,7 @@ Example (obtaining a shared secret): ```mjs const { getDiffieHellman -} = await import('crypto'); +} = await import('node:crypto'); const alice = getDiffieHellman('modp14'); const bob = getDiffieHellman('modp14'); @@ -4134,7 +4134,7 @@ console.log(aliceSecret === bobSecret); ```cjs const { getDiffieHellman, -} = require('crypto'); +} = require('node:crypto'); const alice = getDiffieHellman('modp14'); const bob = getDiffieHellman('modp14'); @@ -4171,7 +4171,7 @@ added: v0.9.3 ```mjs const { getHashes -} = await import('crypto'); +} = await import('node:crypto'); console.log(getHashes()); // ['DSA', 'DSA-SHA', 'DSA-SHA1', ...] ``` @@ -4179,7 +4179,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', ...] ``` @@ -4234,10 +4234,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; @@ -4248,8 +4248,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; @@ -4286,10 +4286,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' @@ -4298,8 +4298,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' @@ -4372,7 +4372,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; @@ -4383,7 +4383,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; @@ -4396,7 +4396,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; @@ -4405,7 +4405,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; @@ -4470,7 +4470,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' @@ -4479,7 +4479,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' @@ -4490,14 +4490,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' @@ -4726,7 +4726,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; @@ -4738,7 +4738,7 @@ randomBytes(256, (err, buf) => { // Asynchronous const { randomBytes, -} = require('crypto'); +} = require('node:crypto'); randomBytes(256, (err, buf) => { if (err) throw err; @@ -4754,7 +4754,7 @@ there is a problem generating the bytes. // Synchronous const { randomBytes -} = await import('crypto'); +} = await import('node:crypto'); const buf = randomBytes(256); console.log( @@ -4765,7 +4765,7 @@ console.log( // Synchronous const { randomBytes, -} = require('crypto'); +} = require('node:crypto'); const buf = randomBytes(256); console.log( @@ -4810,8 +4810,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')); @@ -4825,8 +4825,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')); @@ -4843,8 +4843,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, @@ -4859,8 +4859,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, @@ -4905,8 +4905,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) => { @@ -4927,8 +4927,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) => { @@ -4958,8 +4958,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) => { @@ -4983,8 +4983,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) => { @@ -5047,7 +5047,7 @@ generated synchronously. // Asynchronous const { randomInt -} = await import('crypto'); +} = await import('node:crypto'); randomInt(3, (err, n) => { if (err) throw err; @@ -5059,7 +5059,7 @@ randomInt(3, (err, n) => { // Asynchronous const { randomInt, -} = require('crypto'); +} = require('node:crypto'); randomInt(3, (err, n) => { if (err) throw err; @@ -5071,7 +5071,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}`); @@ -5081,7 +5081,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}`); @@ -5091,7 +5091,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}`); @@ -5101,7 +5101,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}`); @@ -5188,7 +5188,7 @@ or types. ```mjs const { scrypt -} = await import('crypto'); +} = await import('node:crypto'); // Using the factory defaults. scrypt('password', 'salt', 64, (err, derivedKey) => { @@ -5205,7 +5205,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) => { @@ -5269,7 +5269,7 @@ or types. ```mjs const { scryptSync -} = await import('crypto'); +} = await import('node:crypto'); // Using the factory defaults. const key1 = scryptSync('password', 'salt', 64); @@ -5282,7 +5282,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); @@ -5591,7 +5591,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. @@ -5647,12 +5647,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); @@ -5691,12 +5691,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); @@ -5737,7 +5737,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 f223577f84f75a..88027bea7c9de4 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) => { @@ -569,8 +569,8 @@ This method throws [`ERR_SOCKET_BAD_PORT`][] if called on an unbound socket. Example of sending a UDP packet to a port on `localhost`; ```mjs -import dgram from 'dgram'; -import { Buffer } from 'buffer'; +import dgram from 'node:dgram'; +import { Buffer } from 'node:buffer'; const message = Buffer.from('Some bytes'); const client = dgram.createSocket('udp4'); @@ -580,8 +580,8 @@ client.send(message, 41234, 'localhost', (err) => { ``` ```cjs -const dgram = require('dgram'); -const { Buffer } = require('buffer'); +const dgram = require('node:dgram'); +const { Buffer } = require('node:buffer'); const message = Buffer.from('Some bytes'); const client = dgram.createSocket('udp4'); @@ -594,8 +594,8 @@ Example of sending a UDP packet composed of multiple buffers to a port on `127.0.0.1`; ```mjs -import dgram from 'dgram'; -import { Buffer } from 'buffer'; +import dgram from 'node:dgram'; +import { Buffer } from 'node:buffer'; const buf1 = Buffer.from('Some '); const buf2 = Buffer.from('bytes'); @@ -606,8 +606,8 @@ client.send([buf1, buf2], 41234, (err) => { ``` ```cjs -const dgram = require('dgram'); -const { Buffer } = require('buffer'); +const dgram = require('node:dgram'); +const { Buffer } = require('node:buffer'); const buf1 = Buffer.from('Some '); const buf2 = Buffer.from('bytes'); @@ -626,8 +626,8 @@ Example of sending a UDP packet using a socket connected to a port on `localhost`: ```mjs -import dgram from 'dgram'; -import { Buffer } from 'buffer'; +import dgram from 'node:dgram'; +import { Buffer } from 'node:buffer'; const message = Buffer.from('Some bytes'); const client = dgram.createSocket('udp4'); @@ -639,8 +639,8 @@ client.connect(41234, 'localhost', (err) => { ``` ```cjs -const dgram = require('dgram'); -const { Buffer } = require('buffer'); +const dgram = require('node:dgram'); +const { Buffer } = require('node:buffer'); const message = Buffer.from('Some bytes'); const client = dgram.createSocket('udp4'); @@ -868,7 +868,7 @@ Calling `socket.unref()` multiple times will have no addition effect. The `socket.unref()` method returns a reference to the socket so calls can be chained. -## `dgram` module functions +## `node:dgram` module functions ### `dgram.createSocket(options[, callback])` diff --git a/doc/api/diagnostics_channel.md b/doc/api/diagnostics_channel.md index fc13f0d38e4393..eff642f96743b4 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'); @@ -280,7 +280,7 @@ Remove a message handler previously registered to this channel with [`channel.subscribe(onMessage)`][]. ```mjs -import diagnostics_channel from 'diagnostics_channel'; +import diagnostics_channel from 'node:diagnostics_channel'; const channel = diagnostics_channel.channel('my-channel'); @@ -294,7 +294,7 @@ channel.unsubscribe(onMessage); ``` ```cjs -const diagnostics_channel = require('diagnostics_channel'); +const diagnostics_channel = require('node:diagnostics_channel'); const channel = diagnostics_channel.channel('my-channel'); diff --git a/doc/api/dns.md b/doc/api/dns.md index 86f92205c38ba7..c150c8a8abb8eb 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()`] @@ -241,7 +241,7 @@ time to consult the [Implementation considerations section][] before using Example usage: ```js -const dns = require('dns'); +const dns = require('node:dns'); const options = { family: 6, hints: dns.ADDRCONFIG | dns.V4MAPPED, @@ -312,7 +312,7 @@ will be thrown. On an error, `err` is an [`Error`][] object, where `err.code` is the error code. ```js -const dns = require('dns'); +const dns = require('node:dns'); dns.lookupService('127.0.0.1', 22, (err, hostname, service) => { console.log(hostname, service); // Prints: localhost ssh @@ -826,7 +826,7 @@ added: v10.6.0 changes: - version: v15.0.0 pr-url: https://github.com/nodejs/node/pull/32953 - description: Exposed as `require('dns/promises')`. + description: Exposed as `require('node:dns/promises')`. - version: - v11.14.0 - v10.17.0 @@ -836,7 +836,7 @@ changes: The `dns.promises` API provides an alternative set of asynchronous DNS methods that return `Promise` objects rather than using callbacks. The API is accessible -via `require('dns').promises` or `require('dns/promises')`. +via `require('node:dns').promises` or `require('node:dns/promises')`. ### Class: `dnsPromises.Resolver` @@ -852,7 +852,7 @@ the servers used for a resolver using other resolvers: ```js -const { Resolver } = require('dns').promises; +const { Resolver } = require('node:dns').promises; const resolver = new Resolver(); resolver.setServers(['4.4.4.4']); @@ -967,7 +967,7 @@ using `dnsPromises.lookup()`. Example usage: ```js -const dns = require('dns'); +const dns = require('node:dns'); const dnsPromises = dns.promises; const options = { family: 6, @@ -1007,7 +1007,7 @@ On error, the `Promise` is rejected with an [`Error`][] object, where `err.code` is the error code. ```js -const dnsPromises = require('dns').promises; +const dnsPromises = require('node:dns').promises; dnsPromises.lookupService('127.0.0.1', 22).then((result) => { console.log(result.hostname, result.service); // Prints: localhost ssh 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 c4707b4caf956b..d07bec744df2e5 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 94afa6116086cb..3f7e8a4b165943 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. @@ -818,14 +818,14 @@ key lies outside of the elliptic curve. ### `ERR_CRYPTO_ENGINE_UNKNOWN` An invalid crypto engine identifier was passed to -[`require('crypto').setEngine()`][]. +[`require('node:crypto').setEngine()`][]. ### `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. @@ -1164,8 +1164,8 @@ ongoing asynchronous operations. ### `ERR_DOMAIN_CALLBACK_NOT_AVAILABLE` -The `domain` module was not usable since it could not establish the required -error handling hooks, because +The `node:domain` module was not usable since it could not establish the +required error handling hooks, because [`process.setUncaughtExceptionCaptureCallback()`][] had been called at an earlier point in time. @@ -1174,10 +1174,10 @@ earlier point in time. ### `ERR_DOMAIN_CANNOT_SET_UNCAUGHT_EXCEPTION_CAPTURE` [`process.setUncaughtExceptionCaptureCallback()`][] could not be called -because the `domain` module has been loaded at an earlier point in time. +because the `node:domain` module has been loaded at an earlier point in time. The stack trace is extended to include the point in time at which the -`domain` module had been loaded. +`node:domain` module had been loaded. @@ -1750,7 +1750,7 @@ only be used with input via `--eval`, `--print` or `STDIN`. ### `ERR_INSPECTOR_ALREADY_ACTIVATED` -While using the `inspector` module, an attempt was made to activate the +While using the `node:inspector` module, an attempt was made to activate the inspector when it already started to listen on a port. Use `inspector.close()` before activating it on a different address. @@ -1758,21 +1758,21 @@ before activating it on a different address. ### `ERR_INSPECTOR_ALREADY_CONNECTED` -While using the `inspector` module, an attempt was made to connect when the +While using the `node:inspector` module, an attempt was made to connect when the inspector was already connected. ### `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. @@ -1784,14 +1784,14 @@ The `inspector` is not active when `inspector.waitForDebugger()` is called. ### `ERR_INSPECTOR_NOT_AVAILABLE` -The `inspector` module is not available for use. +The `node:inspector` module is not available for use. ### `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. @@ -2523,7 +2523,7 @@ Prevents an abort if a string decoder was set on the Socket or if the decoder is in `objectMode`. ```js -const Socket = require('net').Socket; +const Socket = require('node:net').Socket; const instance = new Socket(); instance.setEncoding('utf8'); @@ -2685,8 +2685,8 @@ category. ### `ERR_TRACE_EVENTS_UNAVAILABLE` -The `trace_events` module could not be loaded because Node.js was compiled with -the `--without-v8-platform` flag. +The `node:trace_events` module could not be loaded because Node.js was compiled +with the `--without-v8-platform` flag. @@ -3198,7 +3198,7 @@ added: v9.0.0 removed: v10.0.0 --> -The `repl` module was unable to parse data from the REPL history file. +The `node:repl` module was unable to parse data from the REPL history file. @@ -3426,7 +3426,7 @@ The native call from `process.cpuUsage` could not be processed. [`process.send()`]: process.md#processsendmessage-sendhandle-options-callback [`process.setUncaughtExceptionCaptureCallback()`]: process.md#processsetuncaughtexceptioncapturecallbackfn [`readable._read()`]: stream.md#readable_readsize -[`require('crypto').setEngine()`]: crypto.md#cryptosetengineengine-flags +[`require('node:crypto').setEngine()`]: crypto.md#cryptosetengineengine-flags [`require()`]: modules.md#requireid [`server.close()`]: net.md#serverclosecallback [`server.listen()`]: net.md#serverlisten diff --git a/doc/api/esm.md b/doc/api/esm.md index bea63a9d20c5aa..e531a61416eb6d 100644 --- a/doc/api/esm.md +++ b/doc/api/esm.md @@ -116,7 +116,7 @@ This section was moved to [Modules: Packages](packages.md). ### Terminology The _specifier_ of an `import` statement is the string after the `from` keyword, -e.g. `'path'` in `import { sep } from 'path'`. Specifiers are also used in +e.g. `'path'` in `import { sep } from 'node:path'`. Specifiers are also used in `export from` statements, and as the argument to an `import()` expression. There are three types of specifiers: @@ -260,12 +260,12 @@ exports. Named exports of builtin modules are updated only by calling [`module.syncBuiltinESMExports()`][]. ```js -import EventEmitter from 'events'; +import EventEmitter from 'node:events'; const e = new EventEmitter(); ``` ```js -import { readFile } from 'fs'; +import { readFile } from 'node:fs'; readFile('./foo.txt', (err, source) => { if (err) { console.error(err); @@ -276,9 +276,9 @@ readFile('./foo.txt', (err, source) => { ``` ```js -import fs, { readFileSync } from 'fs'; -import { syncBuiltinESMExports } from 'module'; -import { Buffer } from 'buffer'; +import fs, { readFileSync } from 'node:fs'; +import { syncBuiltinESMExports } from 'node:module'; +import { Buffer } from 'node:buffer'; fs.readFileSync = () => Buffer.from('Hello, ESM'); syncBuiltinESMExports(); @@ -308,7 +308,7 @@ current module file. This enables useful patterns such as relative file loading: ```js -import { readFileSync } from 'fs'; +import { readFileSync } from 'node:fs'; const buffer = readFileSync(new URL('./data.proto', import.meta.url)); ``` @@ -592,8 +592,8 @@ If a top level `await` expression never resolves, the `node` process will exit with a `13` [status code][]. ```js -import { spawn } from 'child_process'; -import { execPath } from 'process'; +import { spawn } from 'node:child_process'; +import { execPath } from 'node:process'; spawn(execPath, [ '--input-type=module', @@ -646,7 +646,7 @@ references to the local dependencies: ```mjs // file.mjs -import worker_threads from 'worker_threads'; +import worker_threads from 'node:worker_threads'; import { configure, resize } from 'https://example.com/imagelib.mjs'; configure({ worker_threads }); ``` @@ -948,7 +948,7 @@ and there is no security. ```js // https-loader.mjs -import { get } from 'https'; +import { get } from 'node:https'; export function resolve(specifier, context, defaultResolve) { const { parentURL = null } = context; @@ -1118,7 +1118,7 @@ async function getPackageType(url) { import { scream } from './scream.coffee' console.log scream 'hello, world' -import { version } from 'process' +import { version } from 'node:process' console.log "Brought to you by Node.js version #{version}" ``` diff --git a/doc/api/events.md b/doc/api/events.md index 2fd0a4287285fc..839b076a74438d 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', () => {}); @@ -758,7 +758,7 @@ It is possible to use [`events.captureRejectionSymbol`][rejectionsymbol] in place of `Symbol.for('nodejs.rejection')`. ```js -const { EventEmitter, captureRejectionSymbol } = require('events'); +const { EventEmitter, captureRejectionSymbol } = require('node:events'); class MyClass extends EventEmitter { constructor() { @@ -854,7 +854,7 @@ For `EventTarget`s this is the only way to get the event listeners for the event target. This is useful for debugging and diagnostic purposes. ```js -const { getEventListeners, EventEmitter } = require('events'); +const { getEventListeners, EventEmitter } = require('node:events'); { const ee = new EventEmitter(); @@ -898,7 +898,7 @@ This method is intentionally generic and works with the web platform `'error'` event semantics and does not listen to the `'error'` event. ```js -const { once, EventEmitter } = require('events'); +const { once, EventEmitter } = require('node:events'); async function run() { const ee = new EventEmitter(); @@ -931,7 +931,7 @@ is used to wait for another event. If `events.once()` is used to wait for the special handling: ```js -const { EventEmitter, once } = require('events'); +const { EventEmitter, once } = require('node:events'); const ee = new EventEmitter(); @@ -947,7 +947,7 @@ ee.emit('error', new Error('boom')); An {AbortSignal} can be used to cancel waiting for the event: ```js -const { EventEmitter, once } = require('events'); +const { EventEmitter, once } = require('node:events'); const ee = new EventEmitter(); const ac = new AbortController(); @@ -980,7 +980,7 @@ queue, and because `EventEmitter` emits all events synchronously, it is possible for `events.once()` to miss an event. ```js -const { EventEmitter, once } = require('events'); +const { EventEmitter, once } = require('node:events'); const myEE = new EventEmitter(); @@ -1007,7 +1007,7 @@ of them, then it becomes possible to use `Promise.all()`, `Promise.race()`, or `Promise.allSettled()`: ```js -const { EventEmitter, once } = require('events'); +const { EventEmitter, once } = require('node:events'); const myEE = new EventEmitter(); @@ -1076,7 +1076,7 @@ A class method that returns the number of listeners for the given `eventName` registered on the given `emitter`. ```js -const { EventEmitter, listenerCount } = require('events'); +const { EventEmitter, listenerCount } = require('node:events'); const myEmitter = new EventEmitter(); myEmitter.on('event', () => {}); myEmitter.on('event', () => {}); @@ -1099,7 +1099,7 @@ added: * Returns: {AsyncIterator} that iterates `eventName` events emitted by the `emitter` ```js -const { on, EventEmitter } = require('events'); +const { on, EventEmitter } = require('node:events'); (async () => { const ee = new EventEmitter(); @@ -1128,7 +1128,7 @@ composed of the emitted event arguments. An {AbortSignal} can be used to cancel waiting on events: ```js -const { on, EventEmitter } = require('events'); +const { on, EventEmitter } = require('node:events'); const ac = new AbortController(); (async () => { @@ -1168,7 +1168,7 @@ added: v15.4.0 const { setMaxListeners, EventEmitter -} = require('events'); +} = require('node:events'); const target = new EventTarget(); const emitter = new EventEmitter(); @@ -1189,9 +1189,9 @@ require manual async tracking. Specifically, all events emitted by instances of `events.EventEmitterAsyncResource` will run within its [async context][]. ```js -const { EventEmitterAsyncResource } = require('events'); -const { notStrictEqual, strictEqual } = require('assert'); -const { executionAsyncId } = require('async_hooks'); +const { EventEmitterAsyncResource } = require('node:events'); +const { notStrictEqual, strictEqual } = require('node:assert'); +const { executionAsyncId } = require('node:async_hooks'); // Async tracking tooling will identify this as 'Q'. const ee1 = new EventEmitterAsyncResource({ name: 'Q' }); diff --git a/doc/api/fs.md b/doc/api/fs.md index d584d1f20a019e..246b369f318f53 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 }); @@ -448,7 +448,7 @@ await file.close(); ```cjs const { open, -} = require('fs/promises'); +} = require('node:fs/promises'); (async () => { const file = await open('./some/file/to/read'); @@ -552,7 +552,7 @@ retained in the file. The following example retains only the first four bytes of the file: ```mjs -import { open } from 'fs/promises'; +import { open } from 'node:fs/promises'; let filehandle = null; try { @@ -743,8 +743,8 @@ with an {Error} object. The following example checks if the file `/etc/passwd` can be read and written by the current process. ```mjs -import { access } from 'fs/promises'; -import { constants } from 'fs'; +import { access } from 'node:fs/promises'; +import { constants } from 'node:fs'; try { await access('/etc/passwd', constants.R_OK | constants.W_OK); @@ -846,8 +846,8 @@ error occurs after the destination file has been opened for writing, an attempt will be made to remove the destination. ```mjs -import { constants } from 'fs'; -import { copyFile } from 'fs/promises'; +import { constants } from 'node:fs'; +import { copyFile } from 'node:fs/promises'; try { await copyFile('source.txt', 'destination.txt'); @@ -1037,7 +1037,7 @@ The optional `options` argument can be a string specifying an encoding, or an object with an `encoding` property specifying the character encoding to use. ```mjs -import { mkdtemp } from 'fs/promises'; +import { mkdtemp } from 'node:fs/promises'; try { await mkdtemp(path.join(os.tmpdir(), 'foo-')); @@ -1050,7 +1050,7 @@ The `fsPromises.mkdtemp()` method will append the six randomly selected characters directly to the `prefix` string. For instance, given a directory `/tmp`, if the intention is to create a temporary directory _within_ `/tmp`, the `prefix` must end with a trailing platform-specific path separator -(`require('path').sep`). +(`require('node:path').sep`). ### `fsPromises.open(path, flags[, mode])` @@ -1110,7 +1110,7 @@ directory and subsequent read operations. Example using async iteration: ```mjs -import { opendir } from 'fs/promises'; +import { opendir } from 'node:fs/promises'; try { const dir = await opendir('./'); @@ -1152,7 +1152,7 @@ If `options.withFileTypes` is set to `true`, the resolved array will contain {fs.Dirent} objects. ```mjs -import { readdir } from 'fs/promises'; +import { readdir } from 'node:fs/promises'; try { const files = await readdir(path); @@ -1199,7 +1199,7 @@ It is possible to abort an ongoing `readFile` using an {AbortSignal}. If a request is aborted the promise returned is rejected with an `AbortError`: ```mjs -import { readFile } from 'fs/promises'; +import { readFile } from 'node:fs/promises'; try { const controller = new AbortController(); @@ -1474,7 +1474,7 @@ Returns an async iterator that watches for changes on `filename`, where `filenam is either a file or a directory. ```js -const { watch } = require('fs/promises'); +const { watch } = require('node:fs/promises'); const ac = new AbortController(); const { signal } = ac; @@ -1554,8 +1554,8 @@ Cancelation is "best effort", and some amount of data is likely still to be written. ```mjs -import { writeFile } from 'fs/promises'; -import { Buffer } from 'buffer'; +import { writeFile } from 'node:fs/promises'; +import { Buffer } from 'node:buffer'; try { const controller = new AbortController(); @@ -1629,7 +1629,7 @@ argument will be an `Error` object. The following examples check if `package.json` exists, and if it is readable or writable. ```mjs -import { access, constants } from 'fs'; +import { access, constants } from 'node:fs'; const file = 'package.json'; @@ -1663,7 +1663,7 @@ file directly and handle the error raised if the file is not accessible. **write (NOT RECOMMENDED)** ```mjs -import { access, open, close } from 'fs'; +import { access, open, close } from 'node:fs'; access('myfile', (err) => { if (!err) { @@ -1688,7 +1688,7 @@ access('myfile', (err) => { **write (RECOMMENDED)** ```mjs -import { open, close } from 'fs'; +import { open, close } from 'node:fs'; open('myfile', 'wx', (err, fd) => { if (err) { @@ -1713,7 +1713,7 @@ open('myfile', 'wx', (err, fd) => { **read (NOT RECOMMENDED)** ```mjs -import { access, open, close } from 'fs'; +import { access, open, close } from 'node:fs'; access('myfile', (err) => { if (err) { if (err.code === 'ENOENT') { @@ -1741,7 +1741,7 @@ access('myfile', (err) => { **read (RECOMMENDED)** ```mjs -import { open, close } from 'fs'; +import { open, close } from 'node:fs'; open('myfile', 'r', (err, fd) => { if (err) { @@ -1818,7 +1818,7 @@ The `mode` option only affects the newly created file. See [`fs.open()`][] for more details. ```mjs -import { appendFile } from 'fs'; +import { appendFile } from 'node:fs'; appendFile('message.txt', 'data to append', (err) => { if (err) throw err; @@ -1829,7 +1829,7 @@ appendFile('message.txt', 'data to append', (err) => { If `options` is a string, then it specifies the encoding: ```mjs -import { appendFile } from 'fs'; +import { appendFile } from 'node:fs'; appendFile('message.txt', 'data to append', 'utf8', callback); ``` @@ -1839,7 +1839,7 @@ for appending (using `fs.open()` or `fs.openSync()`). The file descriptor will not be closed automatically. ```mjs -import { open, close, appendFile } from 'fs'; +import { open, close, appendFile } from 'node:fs'; function closeFd(fd) { close(fd, (err) => { @@ -1897,7 +1897,7 @@ possible exception are given to the completion callback. See the POSIX chmod(2) documentation for more detail. ```mjs -import { chmod } from 'fs'; +import { chmod } from 'node:fs'; chmod('my_file.txt', 0o775, (err) => { if (err) throw err; @@ -2069,7 +2069,7 @@ OR of two or more values (e.g. copy-on-write, then the operation will fail. ```mjs -import { copyFile, constants } from 'fs'; +import { copyFile, constants } from 'node:fs'; function callback(err) { if (err) throw err; @@ -2217,7 +2217,7 @@ an override for `read` is required. If no `fd` is provided, an override for also required. ```mjs -import { createReadStream } from 'fs'; +import { createReadStream } from 'node:fs'; // Create a stream from some character device. const stream = createReadStream('/dev/input/event0'); @@ -2245,7 +2245,7 @@ file was created. An example to read the last 10 bytes of a file which is 100 bytes long: ```mjs -import { createReadStream } from 'fs'; +import { createReadStream } from 'node:fs'; createReadStream('sample.txt', { start: 90, end: 99 }); ``` @@ -2364,7 +2364,7 @@ Test whether or not the given path exists by checking with the file system. Then call the `callback` argument with either true or false: ```mjs -import { exists } from 'fs'; +import { exists } from 'node:fs'; exists('/etc/passwd', (e) => { console.log(e ? 'it exists' : 'no passwd!'); @@ -2386,7 +2386,7 @@ file directly and handle the error raised if the file does not exist. **write (NOT RECOMMENDED)** ```mjs -import { exists, open, close } from 'fs'; +import { exists, open, close } from 'node:fs'; exists('myfile', (e) => { if (e) { @@ -2410,7 +2410,7 @@ exists('myfile', (e) => { **write (RECOMMENDED)** ```mjs -import { open, close } from 'fs'; +import { open, close } from 'node:fs'; open('myfile', 'wx', (err, fd) => { if (err) { if (err.code === 'EEXIST') { @@ -2434,7 +2434,7 @@ open('myfile', 'wx', (err, fd) => { **read (NOT RECOMMENDED)** ```mjs -import { open, close, exists } from 'fs'; +import { open, close, exists } from 'node:fs'; exists('myfile', (e) => { if (e) { @@ -2458,7 +2458,7 @@ exists('myfile', (e) => { **read (RECOMMENDED)** ```mjs -import { open, close } from 'fs'; +import { open, close } from 'node:fs'; open('myfile', 'r', (err, fd) => { if (err) { @@ -2680,7 +2680,7 @@ For example, the following program retains only the first four bytes of the file: ```mjs -import { open, close, ftruncate } from 'fs'; +import { open, close, ftruncate } from 'node:fs'; function closeFd(fd) { close(fd, (err) => { @@ -2972,7 +2972,7 @@ property indicating whether parent directories should be created. Calling when `recursive` is false. ```mjs -import { mkdir } from 'fs'; +import { mkdir } from 'node:fs'; // Creates /tmp/a/apple, regardless of whether `/tmp` and /tmp/a exist. mkdir('/tmp/a/apple', { recursive: true }, (err) => { @@ -2984,7 +2984,7 @@ On Windows, using `fs.mkdir()` on the root directory even with recursion will result in an error: ```mjs -import { mkdir } from 'fs'; +import { mkdir } from 'node:fs'; mkdir('/', { recursive: true }, (err) => { // => [Error: EPERM: operation not permitted, mkdir 'C:\'] @@ -3043,7 +3043,7 @@ The optional `options` argument can be a string specifying an encoding, or an object with an `encoding` property specifying the character encoding to use. ```mjs -import { mkdtemp } from 'fs'; +import { mkdtemp } from 'node:fs'; mkdtemp(path.join(os.tmpdir(), 'foo-'), (err, directory) => { if (err) throw err; @@ -3056,11 +3056,11 @@ The `fs.mkdtemp()` method will append the six randomly selected characters directly to the `prefix` string. For instance, given a directory `/tmp`, if the intention is to create a temporary directory _within_ `/tmp`, the `prefix` must end with a trailing platform-specific path separator -(`require('path').sep`). +(`require('node:path').sep`). ```mjs -import { tmpdir } from 'os'; -import { mkdtemp } from 'fs'; +import { tmpdir } from 'node:os'; +import { mkdtemp } from 'node:fs'; // The parent directory for the new temporary directory const tmpDir = tmpdir(); @@ -3075,7 +3075,7 @@ mkdtemp(tmpDir, (err, directory) => { }); // This method is *CORRECT*: -import { sep } from 'path'; +import { sep } from 'node:path'; mkdtemp(`${tmpDir}${sep}`, (err, directory) => { if (err) throw err; console.log(directory); @@ -3348,7 +3348,7 @@ changes: Asynchronously reads the entire contents of a file. ```mjs -import { readFile } from 'fs'; +import { readFile } from 'node:fs'; readFile('/etc/passwd', (err, data) => { if (err) throw err; @@ -3364,7 +3364,7 @@ If no encoding is specified, then the raw buffer is returned. If `options` is a string, then it specifies the encoding: ```mjs -import { readFile } from 'fs'; +import { readFile } from 'node:fs'; readFile('/etc/passwd', 'utf8', callback); ``` @@ -3375,7 +3375,7 @@ error will be returned. On FreeBSD, a representation of the directory's contents will be returned. ```mjs -import { readFile } from 'fs'; +import { readFile } from 'node:fs'; // macOS, Linux, and Windows readFile('', (err, data) => { @@ -3392,7 +3392,7 @@ It is possible to abort an ongoing request using an `AbortSignal`. If a request is aborted the callback is called with an `AbortError`: ```mjs -import { readFile } from 'fs'; +import { readFile } from 'node:fs'; const controller = new AbortController(); const signal = controller.signal; @@ -3657,7 +3657,7 @@ given to the completion callback. See also: rename(2). ```mjs -import { rename } from 'fs'; +import { rename } from 'node:fs'; rename('oldFile.txt', 'newFile.txt', (err) => { if (err) throw err; @@ -3838,7 +3838,7 @@ For example, given the following directory structure: The next program will check for the stats of the given paths: ```mjs -import { stat } from 'fs'; +import { stat } from 'node:fs'; const pathsToCheck = ['./txtDir', './txtDir/file.txt']; @@ -3939,7 +3939,7 @@ require the destination path to be absolute. When using `'junction'`, the Relative targets are relative to the link’s parent directory. ```mjs -import { symlink } from 'fs'; +import { symlink } from 'node:fs'; symlink('./mew', './mewtwo', callback); ``` @@ -3988,7 +3988,7 @@ given to the completion callback. A file descriptor can also be passed as the first argument. In this case, `fs.ftruncate()` is called. ```mjs -import { truncate } from 'fs'; +import { truncate } from 'node:fs'; // Assuming that 'path/file.txt' is a regular file. truncate('path/file.txt', (err) => { if (err) throw err; @@ -3997,7 +3997,7 @@ truncate('path/file.txt', (err) => { ``` ```cjs -const { truncate } = require('fs'); +const { truncate } = require('node:fs'); // Assuming that 'path/file.txt' is a regular file. truncate('path/file.txt', (err) => { if (err) throw err; @@ -4042,7 +4042,7 @@ Asynchronously removes a file or symbolic link. No arguments other than a possible exception are given to the completion callback. ```mjs -import { unlink } from 'fs'; +import { unlink } from 'node:fs'; // Assuming that 'path/file.txt' is a regular file. unlink('path/file.txt', (err) => { if (err) throw err; @@ -4241,7 +4241,7 @@ guaranteed to be provided. Therefore, don't assume that `filename` argument is always provided in the callback, and have some fallback logic if it is `null`. ```mjs -import { watch } from 'fs'; +import { watch } from 'node:fs'; watch('somedir', (eventType, filename) => { console.log(`event type is: ${eventType}`); if (filename) { @@ -4289,7 +4289,7 @@ The `listener` gets two arguments the current stat object and the previous stat object: ```mjs -import { watchFile } from 'fs'; +import { watchFile } from 'node:fs'; watchFile('message.text', (curr, prev) => { console.log(`the current mtime is: ${curr.mtime}`); @@ -4533,8 +4533,8 @@ The `mode` option only affects the newly created file. See [`fs.open()`][] for more details. ```mjs -import { writeFile } from 'fs'; -import { Buffer } from 'buffer'; +import { writeFile } from 'node:fs'; +import { Buffer } from 'node:buffer'; const data = new Uint8Array(Buffer.from('Hello Node.js')); writeFile('message.txt', data, (err) => { @@ -4546,7 +4546,7 @@ writeFile('message.txt', data, (err) => { If `options` is a string, then it specifies the encoding: ```mjs -import { writeFile } from 'fs'; +import { writeFile } from 'node:fs'; writeFile('message.txt', 'Hello Node.js', 'utf8', callback); ``` @@ -4564,8 +4564,8 @@ Cancelation is "best effort", and some amount of data is likely still to be written. ```mjs -import { writeFile } from 'fs'; -import { Buffer } from 'buffer'; +import { writeFile } from 'node:fs'; +import { Buffer } from 'node:buffer'; const controller = new AbortController(); const { signal } = controller; @@ -4586,8 +4586,8 @@ When `file` is a file descriptor, the behavior is almost identical to directly calling `fs.write()` like: ```mjs -import { write } from 'fs'; -import { Buffer } from 'buffer'; +import { write } from 'node:fs'; +import { Buffer } from 'node:buffer'; write(fd, Buffer.from(data, options.encoding), callback); ``` @@ -4680,7 +4680,7 @@ If any of the accessibility checks fail, an `Error` will be thrown. Otherwise, the method will return `undefined`. ```mjs -import { accessSync, constants } from 'fs'; +import { accessSync, constants } from 'node:fs'; try { accessSync('etc/passwd', constants.R_OK | constants.W_OK); @@ -4717,7 +4717,7 @@ The `mode` option only affects the newly created file. See [`fs.open()`][] for more details. ```mjs -import { appendFileSync } from 'fs'; +import { appendFileSync } from 'node:fs'; try { appendFileSync('message.txt', 'data to append'); @@ -4730,7 +4730,7 @@ try { If `options` is a string, then it specifies the encoding: ```mjs -import { appendFileSync } from 'fs'; +import { appendFileSync } from 'node:fs'; appendFileSync('message.txt', 'data to append', 'utf8'); ``` @@ -4740,7 +4740,7 @@ for appending (using `fs.open()` or `fs.openSync()`). The file descriptor will not be closed automatically. ```mjs -import { openSync, closeSync, appendFileSync } from 'fs'; +import { openSync, closeSync, appendFileSync } from 'node:fs'; let fd; @@ -4844,7 +4844,7 @@ OR of two or more values (e.g. copy-on-write, then the operation will fail. ```mjs -import { copyFileSync, constants } from 'fs'; +import { copyFileSync, constants } from 'node:fs'; // destination.txt will be created or overwritten by default. copyFileSync('source.txt', 'destination.txt'); @@ -4915,7 +4915,7 @@ parameter to `fs.exists()` accepts parameters that are inconsistent with other Node.js callbacks. `fs.existsSync()` does not use a callback. ```mjs -import { existsSync } from 'fs'; +import { existsSync } from 'node:fs'; if (existsSync('/etc/passwd')) console.log('The path exists.'); @@ -5303,7 +5303,7 @@ Similar to [`fs.readFile()`][], when the path is a directory, the behavior of `fs.readFileSync()` is platform-specific. ```mjs -import { readFileSync } from 'fs'; +import { readFileSync } from 'node:fs'; // macOS, Linux, and Windows readFileSync(''); @@ -5823,7 +5823,7 @@ Created by [`fs.opendir()`][], [`fs.opendirSync()`][], or [`fsPromises.opendir()`][]. ```mjs -import { opendir } from 'fs/promises'; +import { opendir } from 'node:fs/promises'; try { const dir = await opendir('./'); @@ -6100,7 +6100,7 @@ support. If `filename` is provided, it will be provided as a {Buffer} if `filename` will be a UTF-8 string. ```mjs -import { watch } from 'fs'; +import { watch } from 'node:fs'; // Example when handled through fs.watch() listener watch('./tmp', { encoding: 'buffer' }, (eventType, filename) => { if (filename) { @@ -6778,7 +6778,7 @@ To use more than one constant, use the bitwise OR `|` operator. Example: ```mjs -import { open, constants } from 'fs'; +import { open, constants } from 'node:fs'; const { O_RDWR, @@ -7076,7 +7076,7 @@ It is important to correctly order the operations by awaiting the results of one before invoking the other: ```mjs -import { rename, stat } from 'fs/promises'; +import { rename, stat } from 'node:fs/promises'; const from = '/tmp/hello'; const to = '/tmp/world'; @@ -7091,7 +7091,7 @@ try { ``` ```cjs -const { rename, stat } = require('fs/promises'); +const { rename, stat } = require('node:fs/promises'); (async function(from, to) { try { @@ -7108,7 +7108,7 @@ Or, when using the callback APIs, move the `fs.stat()` call into the callback of the `fs.rename()` operation: ```mjs -import { rename, stat } from 'fs'; +import { rename, stat } from 'node:fs'; rename('/tmp/hello', '/tmp/world', (err) => { if (err) throw err; @@ -7120,7 +7120,7 @@ rename('/tmp/hello', '/tmp/world', (err) => { ``` ```cjs -const { rename, stat } = require('fs/promises'); +const { rename, stat } = require('node:fs/promises'); rename('/tmp/hello', '/tmp/world', (err) => { if (err) throw err; @@ -7145,7 +7145,7 @@ to the current working directory as determined by calling `process.cwd()`. Example using an absolute path on POSIX: ```mjs -import { open } from 'fs/promises'; +import { open } from 'node:fs/promises'; let fd; try { @@ -7159,7 +7159,7 @@ try { Example using a relative path on POSIX (relative to `process.cwd()`): ```mjs -import { open } from 'fs/promises'; +import { open } from 'node:fs/promises'; let fd; try { @@ -7176,11 +7176,11 @@ try { added: v7.6.0 --> -For most `fs` module functions, the `path` or `filename` argument may be passed -as a {URL} object using the `file:` protocol. +For most `node:fs` module functions, the `path` or `filename` argument may be +passed as a {URL} object using the `file:` protocol. ```mjs -import { readFileSync } from 'fs'; +import { readFileSync } from 'node:fs'; readFileSync(new URL('file:///tmp/hello')); ``` @@ -7194,7 +7194,7 @@ On Windows, `file:` {URL}s with a host name convert to UNC paths, while `file:` with no host name and no drive letter will result in an error: ```mjs -import { readFileSync } from 'fs'; +import { readFileSync } from 'node:fs'; // On Windows : // - WHATWG file URLs with hostname convert to UNC path @@ -7218,7 +7218,7 @@ On all other platforms, `file:` {URL}s with a host name are unsupported and will result in an error: ```mjs -import { readFileSync } from 'fs'; +import { readFileSync } from 'node:fs'; // On other platforms: // - WHATWG file URLs with hostname are unsupported @@ -7235,7 +7235,7 @@ A `file:` {URL} having encoded slash characters will result in an error on all platforms: ```mjs -import { readFileSync } from 'fs'; +import { readFileSync } from 'node:fs'; // On Windows readFileSync(new URL('file:///C:/p/a/t/h/%2F')); @@ -7253,7 +7253,7 @@ readFileSync(new URL('file:///p/a/t/h/%2f')); On Windows, `file:` {URL}s having encoded backslash will result in an error: ```mjs -import { readFileSync } from 'fs'; +import { readFileSync } from 'node:fs'; // On Windows readFileSync(new URL('file:///C:/path/%5C')); @@ -7273,8 +7273,8 @@ be relative or absolute: Example using an absolute path on POSIX: ```mjs -import { open } from 'fs/promises'; -import { Buffer } from 'buffer'; +import { open } from 'node:fs/promises'; +import { Buffer } from 'node:buffer'; let fd; try { @@ -7314,7 +7314,7 @@ are completed. Failure to do so will result in a memory leak that will eventually cause an application to crash. ```mjs -import { open, close, fstat } from 'fs'; +import { open, close, fstat } from 'node:fs'; function closeFd(fd) { close(fd, (err) => { @@ -7348,7 +7348,7 @@ that resources are not leaked. However, it is still required that they are closed when operations are completed: ```mjs -import { open } from 'fs/promises'; +import { open } from 'node:fs/promises'; let file; try { diff --git a/doc/api/globals.md b/doc/api/globals.md index 58f95e8af99c76..4aef31aa24ac91 100644 --- a/doc/api/globals.md +++ b/doc/api/globals.md @@ -348,7 +348,7 @@ added: v17.6.0 A browser-compatible implementation of {Crypto}. This global is available only if the Node.js binary was compiled with including support for the -`crypto` module. +`node:crypto` module. ## `crypto` @@ -372,7 +372,7 @@ added: v17.6.0 A browser-compatible implementation of {CryptoKey}. This global is available only if the Node.js binary was compiled with including support for the -`crypto` module. +`node:crypto` module. ## Class: `DecompressionStream` @@ -693,7 +693,7 @@ added: v17.6.0 A browser-compatible implementation of {SubtleCrypto}. This global is available only if the Node.js binary was compiled with including support for the -`crypto` module. +`node:crypto` module. ## `DOMException` diff --git a/doc/api/http.md b/doc/api/http.md index c98eac6e024672..543a25dfdf80c2 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. @@ -188,7 +188,7 @@ of these values set to their respective defaults. To configure any of them, a custom [`http.Agent`][] instance must be created. ```js -const http = require('http'); +const http = require('node:http'); const keepAliveAgent = new http.Agent({ keepAlive: true }); options.agent = keepAliveAgent; http.request(options, onResponseCallback); @@ -468,9 +468,9 @@ type other than {net.Socket}. A client and server pair demonstrating how to listen for the `'connect'` event: ```js -const http = require('http'); -const net = require('net'); -const { URL } = require('url'); +const http = require('node:http'); +const net = require('node:net'); +const { URL } = require('node:url'); // Create an HTTP tunneling proxy const proxy = http.createServer((req, res) => { @@ -564,7 +564,7 @@ HTTP version, status code, status message, key-value headers object, and array with the raw header names followed by their respective values. ```js -const http = require('http'); +const http = require('node:http'); const options = { host: '127.0.0.1', @@ -642,7 +642,7 @@ type other than {net.Socket}. A client server pair demonstrating how to listen for the `'upgrade'` event. ```js -const http = require('http'); +const http = require('node:http'); // Create an HTTP server const server = http.createServer((req, res) => { @@ -1010,7 +1010,7 @@ might be reused. But if server closes connection at unfortunate time, client may run into a 'ECONNRESET' error. ```js -const http = require('http'); +const http = require('node:http'); // Server has a 5 seconds keep-alive timeout by default http @@ -1034,7 +1034,7 @@ By marking a request whether it reused socket or not, we can do automatic error retry base on it. ```js -const http = require('http'); +const http = require('node:http'); const agent = new http.Agent({ keepAlive: true }); function retriableRequest() { @@ -1144,7 +1144,7 @@ this property. In particular, the socket will not emit `'readable'` events because of how the protocol parser attaches to the socket. ```js -const http = require('http'); +const http = require('node:http'); const options = { host: 'www.google.com', }; @@ -1311,7 +1311,7 @@ written data it is immediately destroyed. `socket` is the [`net.Socket`][] object that the error originated from. ```js -const http = require('http'); +const http = require('node:http'); const server = http.createServer((req, res) => { res.end(); @@ -1957,7 +1957,7 @@ because of how the protocol parser attaches to the socket. After `response.end()`, the property is nulled. ```js -const http = require('http'); +const http = require('node:http'); const server = http.createServer((req, res) => { const ip = res.socket.remoteAddress; const port = res.socket.remotePort; @@ -2058,7 +2058,7 @@ it will switch to implicit header mode and flush the implicit headers. This sends a chunk of the response body. This method may be called multiple times to provide successive parts of the body. -In the `http` module, the response body is omitted when the +In the `node:http` module, the response body is omitted when the request is a HEAD request. Similarly, the `204` and `304` responses _must not_ include a message body. @@ -3020,7 +3020,7 @@ The `requestListener` is a function which is automatically added to the [`'request'`][] event. ```cjs -const http = require('http'); +const http = require('node:http'); // Create a local server to receive data from const server = http.createServer((req, res) => { @@ -3034,7 +3034,7 @@ server.listen(8000); ``` ```cjs -const http = require('http'); +const http = require('node:http'); // Create a local server to receive data from const server = http.createServer(); @@ -3272,7 +3272,7 @@ class. The `ClientRequest` instance is a writable stream. If one needs to upload a file with a POST request, then write to the `ClientRequest` object. ```js -const http = require('http'); +const http = require('node:http'); const postData = JSON.stringify({ 'msg': 'Hello World!' @@ -3471,7 +3471,7 @@ Examples: Example: ```js -const { validateHeaderName } = require('http'); +const { validateHeaderName } = require('node:http'); try { validateHeaderName(''); @@ -3505,7 +3505,7 @@ or response. The HTTP module will automatically validate such headers. Examples: ```js -const { validateHeaderValue } = require('http'); +const { validateHeaderValue } = require('node:http'); try { validateHeaderValue('x-my-header', undefined); diff --git a/doc/api/http2.md b/doc/api/http2.md index 09f37f36f73b71..0da93a540eccca 100644 --- a/doc/api/http2.md +++ b/doc/api/http2.md @@ -23,25 +23,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!'); } @@ -59,7 +59,7 @@ of Node.js where crypto support is not enabled, consider using the ```mjs let http2; try { - http2 = await import('http2'); + http2 = await import('node:http2'); } catch (err) { console.log('http2 support is disabled!'); } @@ -85,8 +85,8 @@ Since there are no browsers known that support with browser clients. ```js -const http2 = require('http2'); -const fs = require('fs'); +const http2 = require('node:http2'); +const fs = require('node:fs'); const server = http2.createSecureServer({ key: fs.readFileSync('localhost-privkey.pem'), @@ -118,8 +118,8 @@ openssl req -x509 -newkey rsa:2048 -nodes -sha256 -subj '/CN=localhost' \ The following illustrates an HTTP/2 client: ```js -const http2 = require('http2'); -const fs = require('fs'); +const http2 = require('node:http2'); +const fs = require('node:fs'); const client = http2.connect('https://localhost:8443', { ca: fs.readFileSync('localhost-cert.pem') }); @@ -320,7 +320,7 @@ added: v8.4.0 The `'stream'` event is emitted when a new `Http2Stream` is created. ```js -const http2 = require('http2'); +const http2 = require('node:http2'); session.on('stream', (stream, headers, flags) => { const method = headers[':method']; const path = headers[':path']; @@ -340,7 +340,7 @@ and would instead register a handler for the `'stream'` event emitted by the `http2.createSecureServer()`, respectively, as in the example below: ```js -const http2 = require('http2'); +const http2 = require('node:http2'); // Create an unencrypted HTTP/2 server const server = http2.createServer(); @@ -607,7 +607,7 @@ The `windowSize` is the total window size to set, not the delta. ```js -const http2 = require('http2'); +const http2 = require('node:http2'); const server = http2.createServer(); const expectedWindowSize = 2 ** 20; @@ -763,7 +763,7 @@ added: v9.4.0 Submits an `ALTSVC` frame (as defined by [RFC 7838][]) to the connected client. ```js -const http2 = require('http2'); +const http2 = require('node:http2'); const server = http2.createServer(); server.on('session', (session) => { @@ -829,7 +829,7 @@ to advertise the set of origins for which the server is capable of providing authoritative responses. ```js -const http2 = require('http2'); +const http2 = require('node:http2'); const options = getSecureOptionsSomehow(); const server = http2.createSecureServer(options); server.on('stream', (stream) => { @@ -856,7 +856,7 @@ Alternatively, the `origins` option may be used when creating a new HTTP/2 server using the `http2.createSecureServer()` method: ```js -const http2 = require('http2'); +const http2 = require('node:http2'); const options = getSecureOptionsSomehow(); options.origins = ['https://example.com', 'https://example.org']; const server = http2.createSecureServer(options); @@ -890,7 +890,7 @@ ID. If no `origin` is provided in the `ALTSVC` frame, `origin` will be an empty string. ```js -const http2 = require('http2'); +const http2 = require('node:http2'); const client = http2.connect('https://example.org'); client.on('altsvc', (alt, origin, streamId) => { @@ -914,7 +914,7 @@ the client. The event is emitted with an array of `origin` strings. The origins. ```js -const http2 = require('http2'); +const http2 = require('node:http2'); const client = http2.connect('https://example.org'); client.on('origin', (origins) => { @@ -967,7 +967,7 @@ This method is only available if `http2session.type` is equal to `http2.constants.NGHTTP2_SESSION_CLIENT`. ```js -const http2 = require('http2'); +const http2 = require('node:http2'); const clientSession = http2.connect('https://localhost:1234'); const { HTTP2_HEADER_PATH, @@ -1387,7 +1387,7 @@ changes: * `callback` {Function} ```js -const http2 = require('http2'); +const http2 = require('node:http2'); const client = http2.connect('http://example.org:8000'); const { NGHTTP2_CANCEL } = http2.constants; const req = client.request({ ':path': '/' }); @@ -1436,7 +1436,7 @@ in order to keep the `Http2Stream` open after the final `DATA` frame so that trailers can be sent. ```js -const http2 = require('http2'); +const http2 = require('node:http2'); const server = http2.createServer(); server.on('stream', (stream) => { stream.respond(undefined, { waitForTrailers: true }); @@ -1518,7 +1518,7 @@ invoked with two arguments: an `Object` containing the received [HTTP/2 Headers Object][], and flags associated with the headers. ```js -const http2 = require('http2'); +const http2 = require('node:http2'); const client = http2.connect('https://localhost'); const req = client.request({ ':path': '/' }); req.on('response', (headers, flags) => { @@ -1604,7 +1604,7 @@ instance created for the push stream passed as the second argument, or an `Error` passed as the first argument. ```js -const http2 = require('http2'); +const http2 = require('node:http2'); const server = http2.createServer(); server.on('stream', (stream) => { stream.respond({ ':status': 200 }); @@ -1644,7 +1644,7 @@ changes: `'wantTrailers'` event after the final `DATA` frame has been sent. ```js -const http2 = require('http2'); +const http2 = require('node:http2'); const server = http2.createServer(); server.on('stream', (stream) => { stream.respond({ ':status': 200 }); @@ -1663,7 +1663,7 @@ close when the final `DATA` frame is transmitted. User code must call either `Http2Stream`. ```js -const http2 = require('http2'); +const http2 = require('node:http2'); const server = http2.createServer(); server.on('stream', (stream) => { stream.respond({ ':status': 200 }, { waitForTrailers: true }); @@ -1711,8 +1711,8 @@ When used, the `Http2Stream` object's `Duplex` interface will be closed automatically. ```js -const http2 = require('http2'); -const fs = require('fs'); +const http2 = require('node:http2'); +const fs = require('node:fs'); const server = http2.createServer(); server.on('stream', (stream) => { @@ -1756,8 +1756,8 @@ close when the final `DATA` frame is transmitted. User code _must_ call either `Http2Stream`. ```js -const http2 = require('http2'); -const fs = require('fs'); +const http2 = require('node:http2'); +const fs = require('node:fs'); const server = http2.createServer(); server.on('stream', (stream) => { @@ -1823,7 +1823,7 @@ the stream will be destroyed. Example using a file path: ```js -const http2 = require('http2'); +const http2 = require('node:http2'); const server = http2.createServer(); server.on('stream', (stream) => { function statCheck(stat, headers) { @@ -1858,7 +1858,7 @@ results to determine if the file has been modified to return an appropriate `304` response: ```js -const http2 = require('http2'); +const http2 = require('node:http2'); const server = http2.createServer(); server.on('stream', (stream) => { function statCheck(stat, headers) { @@ -1893,7 +1893,7 @@ close when the final `DATA` frame is transmitted. User code must call either `Http2Stream`. ```js -const http2 = require('http2'); +const http2 = require('node:http2'); const server = http2.createServer(); server.on('stream', (stream) => { stream.respondWithFile('/some/file', @@ -1914,8 +1914,8 @@ added: v8.4.0 * Extends: {net.Server} Instances of `Http2Server` are created using the `http2.createServer()` -function. The `Http2Server` class is not exported directly by the `http2` -module. +function. The `Http2Server` class is not exported directly by the +`node:http2` module. #### Event: `'checkContinue'` @@ -2003,7 +2003,7 @@ an `Http2Session` associated with the server. See also [`Http2Session`'s `'stream'` event][]. ```js -const http2 = require('http2'); +const http2 = require('node:http2'); const { HTTP2_HEADER_METHOD, HTTP2_HEADER_PATH, @@ -2130,7 +2130,7 @@ added: v8.4.0 Instances of `Http2SecureServer` are created using the `http2.createSecureServer()` function. The `Http2SecureServer` class is not -exported directly by the `http2` module. +exported directly by the `node:http2` module. #### Event: `'checkContinue'` @@ -2218,7 +2218,7 @@ an `Http2Session` associated with the server. See also [`Http2Session`'s `'stream'` event][]. ```js -const http2 = require('http2'); +const http2 = require('node:http2'); const { HTTP2_HEADER_METHOD, HTTP2_HEADER_PATH, @@ -2481,7 +2481,7 @@ Since there are no browsers known that support with browser clients. ```js -const http2 = require('http2'); +const http2 = require('node:http2'); // Create an unencrypted HTTP/2 server. // Since there are no browsers known that support @@ -2619,8 +2619,8 @@ Returns a `tls.Server` instance that creates and manages `Http2Session` instances. ```js -const http2 = require('http2'); -const fs = require('fs'); +const http2 = require('node:http2'); +const fs = require('node:fs'); const options = { key: fs.readFileSync('server-key.pem'), @@ -2747,7 +2747,7 @@ changes: Returns a `ClientHttp2Session` instance. ```js -const http2 = require('http2'); +const http2 = require('node:http2'); const client = http2.connect('https://localhost:1234'); /* Use the client */ @@ -2809,7 +2809,7 @@ HTTP/2 settings as specified in the [HTTP/2][] specification. This is intended for use with the `HTTP2-Settings` header field. ```js -const http2 = require('http2'); +const http2 = require('node:http2'); const packed = http2.getPackedSettings({ enablePush: false }); @@ -2883,7 +2883,7 @@ For incoming headers: * For all other headers, the values are joined together with ', '. ```js -const http2 = require('http2'); +const http2 = require('node:http2'); const server = http2.createServer(); server.on('stream', (stream, headers) => { console.log(headers[':path']); @@ -2970,7 +2970,7 @@ All additional properties on the settings object are ignored. ### Error handling There are several types of error conditions that may arise when using the -`http2` module: +`node:http2` module: Validation errors occur when an incorrect argument, option, or setting value is passed in. These will always be reported by a synchronous `throw`. @@ -3016,7 +3016,7 @@ To receive pushed streams on the client, set a listener for the `'stream'` event on the `ClientHttp2Session`: ```js -const http2 = require('http2'); +const http2 = require('node:http2'); const client = http2.connect('http://localhost'); @@ -3038,7 +3038,7 @@ for TCP/IP connections. A simple TCP Server: ```js -const net = require('net'); +const net = require('node:net'); const server = net.createServer((socket) => { let name = ''; @@ -3053,9 +3053,9 @@ server.listen(8000); An HTTP/2 CONNECT proxy: ```js -const http2 = require('http2'); +const http2 = require('node:http2'); const { NGHTTP2_REFUSED_STREAM } = http2.constants; -const net = require('net'); +const net = require('node:net'); const proxy = http2.createServer(); proxy.on('stream', (stream, headers) => { @@ -3083,7 +3083,7 @@ proxy.listen(8001); An HTTP/2 CONNECT client: ```js -const http2 = require('http2'); +const http2 = require('node:http2'); const client = http2.connect('http://localhost:8001'); @@ -3117,7 +3117,7 @@ The use of the Extended CONNECT Protocol is enabled by HTTP/2 servers by using the `enableConnectProtocol` setting: ```js -const http2 = require('http2'); +const http2 = require('node:http2'); const settings = { enableConnectProtocol: true }; const server = http2.createServer({ settings }); ``` @@ -3127,7 +3127,7 @@ the extended CONNECT may be used, it may send `CONNECT` requests that use the `':protocol'` HTTP/2 pseudo-header: ```js -const http2 = require('http2'); +const http2 = require('node:http2'); const client = http2.connect('http://localhost:8080'); client.on('remoteSettings', (settings) => { if (settings.enableConnectProtocol) { @@ -3150,7 +3150,7 @@ The following example creates an HTTP/2 server using the compatibility API: ```js -const http2 = require('http2'); +const http2 = require('node:http2'); const server = http2.createServer((req, res) => { res.setHeader('Content-Type', 'text/html'); res.setHeader('X-Foo', 'bar'); @@ -3179,8 +3179,8 @@ features of HTTP/2. The following example creates a server that supports both protocols: ```js -const { createSecureServer } = require('http2'); -const { readFileSync } = require('fs'); +const { createSecureServer } = require('node:http2'); +const { readFileSync } = require('node:fs'); const cert = readFileSync('./cert.pem'); const key = readFileSync('./key.pem'); @@ -3861,7 +3861,7 @@ more information. All other interactions will be routed directly to the socket. ```js -const http2 = require('http2'); +const http2 = require('node:http2'); const server = http2.createServer((req, res) => { const ip = req.socket.remoteAddress; const port = req.socket.remotePort; @@ -3938,7 +3938,7 @@ it will switch to implicit header mode and flush the implicit headers. This sends a chunk of the response body. This method may be called multiple times to provide successive parts of the body. -In the `http` module, the response body is omitted when the +In the `node:http` module, the response body is omitted when the request is a HEAD request. Similarly, the `204` and `304` responses _must not_ include a message body. @@ -4042,7 +4042,7 @@ The [Performance Observer][] API can be used to collect basic performance metrics for each `Http2Session` and `Http2Stream` instance. ```js -const { PerformanceObserver } = require('perf_hooks'); +const { PerformanceObserver } = require('node:perf_hooks'); const obs = new PerformanceObserver((items) => { const entry = items.getEntries()[0]; diff --git a/doc/api/https.md b/doc/api/https.md index d7d47cf07bc965..c022bc7ee30a1b 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); @@ -353,7 +353,7 @@ class. The `ClientRequest` instance is a writable stream. If one needs to upload a file with a POST request, then write to the `ClientRequest` object. ```js -const https = require('https'); +const https = require('node:https'); const options = { hostname: 'encrypted.google.com', @@ -427,9 +427,9 @@ Example pinning on certificate fingerprint, or the public key (similar to `pin-sha256`): ```js -const tls = require('tls'); -const https = require('https'); -const crypto = require('crypto'); +const tls = require('node:tls'); +const https = require('node:https'); +const crypto = require('node:crypto'); function sha256(s) { return crypto.createHash('sha256').update(s).digest('base64'); diff --git a/doc/api/index.md b/doc/api/index.md index 03d2185f21d154..c999258769c95b 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 fad9e0603fad9b..90bc90e2d12226 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 @@ -209,8 +210,8 @@ protocol. Here's an example showing how to use the [CPU Profiler][]: ```js -const inspector = require('inspector'); -const fs = require('fs'); +const inspector = require('node:inspector'); +const fs = require('node:fs'); const session = new inspector.Session(); session.connect(); @@ -234,8 +235,8 @@ session.post('Profiler.enable', () => { Here's an example showing how to use the [Heap Profiler][]: ```js -const inspector = require('inspector'); -const fs = require('fs'); +const inspector = require('node:inspector'); +const fs = require('node:fs'); const session = new inspector.Session(); const fd = fs.openSync('profile.heapsnapshot', 'w'); 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 66764d5905c165..0c860af60d1446 100644 --- a/doc/api/modules.md +++ b/doc/api/modules.md @@ -690,7 +690,7 @@ const myLocalModule = require('./path/myLocalModule'); const jsonData = require('./path/filename.json'); // Importing a module from node_modules or Node.js built-in module: -const crypto = require('crypto'); +const crypto = require('node:crypto'); ``` #### `require.cache` @@ -714,13 +714,13 @@ Use with care! ```js -const assert = require('assert'); -const realFs = require('fs'); +const assert = require('node:assert'); +const realFs = require('node:fs'); const fakeFs = {}; require.cache.fs = { exports: fakeFs }; -assert.strictEqual(require('fs'), fakeFs); +assert.strictEqual(require('node:fs'), fakeFs); assert.strictEqual(require('node:fs'), realFs); ``` @@ -873,7 +873,7 @@ which is probably not what is desired. For example, suppose we were making a module called `a.js`: ```js -const EventEmitter = require('events'); +const EventEmitter = require('node:events'); module.exports = new EventEmitter(); diff --git a/doc/api/net.md b/doc/api/net.md index 0489c13a7a5288..9bf34d55086992 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 @@ -892,7 +892,7 @@ For both types, available `options` include: Following is an example of a client using the `onread` option: ```js -const net = require('net'); +const net = require('node:net'); net.connect({ port: 80, onread: { @@ -1348,7 +1348,7 @@ Following is an example of a client of the echo server described in the [`net.createServer()`][] section: ```js -const net = require('net'); +const net = require('node:net'); const client = net.createConnection({ port: 8124 }, () => { // 'connect' listener. console.log('connected to server!'); @@ -1464,7 +1464,7 @@ Here is an example of a TCP echo server which listens for connections on port 8124: ```js -const net = require('net'); +const net = require('node:net'); const server = net.createServer((c) => { // 'connection' listener. console.log('client connected'); diff --git a/doc/api/os.md b/doc/api/os.md index 30a3faf6eb5947..d0bef604d96053 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 3851cfc13c20ed..2271a1621b3fcd 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 b30111c1d563ba..8c398a3aee71eb 100644 --- a/doc/api/perf_hooks.md +++ b/doc/api/perf_hooks.md @@ -17,7 +17,7 @@ Node.js supports the following [Web Performance APIs][]: * [User Timing][] ```js -const { PerformanceObserver, performance } = require('perf_hooks'); +const { PerformanceObserver, performance } = require('node:perf_hooks'); const obs = new PerformanceObserver((items) => { console.log(items.getEntries()[0].duration); @@ -111,8 +111,8 @@ of how a mostly idle process will have a high ELU. ```js 'use strict'; -const { eventLoopUtilization } = require('perf_hooks').performance; -const { spawnSync } = require('child_process'); +const { eventLoopUtilization } = require('node:perf_hooks').performance; +const { spawnSync } = require('node:child_process'); setImmediate(() => { const elu = eventLoopUtilization(); @@ -312,7 +312,7 @@ event type in order for the timing details to be accessed. const { performance, PerformanceObserver -} = require('perf_hooks'); +} = require('node:perf_hooks'); function someFunction() { console.log('hello world'); @@ -678,7 +678,7 @@ changes: const { performance, PerformanceObserver -} = require('perf_hooks'); +} = require('node:perf_hooks'); const obs = new PerformanceObserver((list, observer) => { console.log(list.getEntries()); @@ -744,7 +744,7 @@ or `options.type`: const { performance, PerformanceObserver -} = require('perf_hooks'); +} = require('node:perf_hooks'); const obs = new PerformanceObserver((list, observer) => { // Called once asynchronously. `list` contains three items. @@ -780,7 +780,7 @@ with respect to `performanceEntry.startTime`. const { performance, PerformanceObserver -} = require('perf_hooks'); +} = require('node:perf_hooks'); const obs = new PerformanceObserver((perfObserverList, observer) => { console.log(perfObserverList.getEntries()); @@ -830,7 +830,7 @@ equal to `name`, and optionally, whose `performanceEntry.entryType` is equal to const { performance, PerformanceObserver -} = require('perf_hooks'); +} = require('node:perf_hooks'); const obs = new PerformanceObserver((perfObserverList, observer) => { console.log(perfObserverList.getEntriesByName('meow')); @@ -886,7 +886,7 @@ is equal to `type`. const { performance, PerformanceObserver -} = require('perf_hooks'); +} = require('node:perf_hooks'); const obs = new PerformanceObserver((perfObserverList, observer) => { console.log(perfObserverList.getEntriesByType('mark')); @@ -959,7 +959,7 @@ of the timer, and those delays are specifically what this API is intended to detect. ```js -const { monitorEventLoopDelay } = require('perf_hooks'); +const { monitorEventLoopDelay } = require('node:perf_hooks'); const h = monitorEventLoopDelay({ resolution: 20 }); h.enable(); // Do something. @@ -1228,11 +1228,11 @@ to execute the callback). ```js 'use strict'; -const async_hooks = require('async_hooks'); +const async_hooks = require('node:async_hooks'); const { performance, PerformanceObserver -} = require('perf_hooks'); +} = require('node:perf_hooks'); const set = new Set(); const hook = async_hooks.createHook({ @@ -1277,8 +1277,8 @@ dependencies: const { performance, PerformanceObserver -} = require('perf_hooks'); -const mod = require('module'); +} = require('node:perf_hooks'); +const mod = require('node:module'); // Monkey patch the require function mod.Module.prototype.require = @@ -1310,8 +1310,8 @@ the request and sending the response: ```js 'use strict'; -const { PerformanceObserver } = require('perf_hooks'); -const http = require('http'); +const { PerformanceObserver } = require('node:perf_hooks'); +const http = require('node:http'); const obs = new PerformanceObserver((items) => { items.getEntries().forEach((item) => { @@ -1334,8 +1334,8 @@ http.createServer((req, res) => { ```js 'use strict'; -const { PerformanceObserver } = require('perf_hooks'); -const net = require('net'); +const { PerformanceObserver } = require('node:perf_hooks'); +const net = require('node:net'); const obs = new PerformanceObserver((items) => { items.getEntries().forEach((item) => { console.log(item); @@ -1354,8 +1354,8 @@ net.createServer((socket) => { ```js 'use strict'; -const { PerformanceObserver } = require('perf_hooks'); -const dns = require('dns'); +const { PerformanceObserver } = require('node:perf_hooks'); +const dns = require('node:dns'); const obs = new PerformanceObserver((items) => { items.getEntries().forEach((item) => { console.log(item); 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 0ae3256a5312fa..f5e105ce43d581 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 @@ -704,7 +704,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(); @@ -723,7 +723,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(); @@ -830,7 +830,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 @@ -841,7 +841,7 @@ allowedNodeEnvironmentFlags.forEach((flag) => { ``` ```cjs -const { allowedNodeEnvironmentFlags } = require('process'); +const { allowedNodeEnvironmentFlags } = require('node:process'); allowedNodeEnvironmentFlags.forEach((flag) => { // -r @@ -872,13 +872,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}`); ``` @@ -901,7 +901,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) => { @@ -910,7 +910,7 @@ argv.forEach((val, index) => { ``` ```cjs -const { argv } = require('process'); +const { argv } = require('node:process'); // print process.argv argv.forEach((val, index) => { @@ -1009,7 +1009,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 { @@ -1021,7 +1021,7 @@ try { ``` ```cjs -const { chdir, cwd } = require('process'); +const { chdir, cwd } = require('node:process'); console.log(`Starting directory: ${cwd()}`); try { @@ -1129,7 +1129,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 } @@ -1143,7 +1143,7 @@ console.log(cpuUsage(startUsage)); ``` ```cjs -const { cpuUsage } = require('process'); +const { cpuUsage } = require('node:process'); const startUsage = cpuUsage(); // { user: 38579, system: 6986 } @@ -1168,13 +1168,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()}`); ``` @@ -1190,13 +1190,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; ``` @@ -1251,9 +1251,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)), @@ -1262,9 +1262,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); @@ -1292,7 +1292,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!', { @@ -1305,7 +1305,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!', { @@ -1322,7 +1322,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' @@ -1334,7 +1334,7 @@ process.on('warning', (warning) => { ``` ```cjs -const process = require('process'); +const process = require('node:process'); process.on('warning', (warning) => { console.warn(warning.name); // 'Warning' @@ -1366,7 +1366,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!'); @@ -1374,7 +1374,7 @@ emitWarning('Something happened!'); ``` ```cjs -const { emitWarning } = require('process'); +const { emitWarning } = require('node:process'); // Emit a warning using a string. emitWarning('Something happened!'); @@ -1382,7 +1382,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'); @@ -1390,7 +1390,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'); @@ -1398,14 +1398,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! @@ -1416,7 +1416,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); @@ -1427,7 +1427,7 @@ process.on('warning', (warning) => { ``` ```cjs -const process = require('process'); +const process = require('node:process'); process.on('warning', (warning) => { console.warn(warning.name); @@ -1442,7 +1442,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!'); @@ -1455,7 +1455,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!'); @@ -1489,7 +1489,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) { @@ -1504,7 +1504,7 @@ emitMyWarning(); ``` ```cjs -const { emitWarning } = require('process'); +const { emitWarning } = require('node:process'); function emitMyWarning() { if (!emitMyWarning.warned) { @@ -1569,14 +1569,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); @@ -1587,7 +1587,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); @@ -1598,7 +1598,7 @@ console.log(env.test); ``` ```cjs -const { env } = require('process'); +const { env } = require('node:process'); env.test = null; console.log(env.test); @@ -1611,7 +1611,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; @@ -1620,7 +1620,7 @@ console.log(env.TEST); ``` ```cjs -const { env } = require('process'); +const { env } = require('node:process'); env.TEST = 1; delete env.TEST; @@ -1631,7 +1631,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); @@ -1639,7 +1639,7 @@ console.log(env.test); ``` ```cjs -const { env } = require('process'); +const { env } = require('node:process'); env.TEST = 1; console.log(env.test); @@ -1725,13 +1725,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); ``` @@ -1753,7 +1753,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()) { @@ -1763,7 +1763,7 @@ if (someConditionNotMet()) { ``` ```cjs -const { exit } = require('process'); +const { exit } = require('node:process'); // This is an example of what *not* to do: if (someConditionNotMet()) { @@ -1782,7 +1782,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. @@ -1793,7 +1793,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. @@ -1842,8 +1842,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); @@ -1854,8 +1854,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); @@ -1875,7 +1875,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()}`); @@ -1883,7 +1883,7 @@ if (process.getegid) { ``` ```cjs -const process = require('process'); +const process = require('node:process'); if (process.getegid) { console.log(`Current gid: ${process.getegid()}`); @@ -1905,7 +1905,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()}`); @@ -1913,7 +1913,7 @@ if (process.geteuid) { ``` ```cjs -const process = require('process'); +const process = require('node:process'); if (process.geteuid) { console.log(`Current uid: ${process.geteuid()}`); @@ -1935,7 +1935,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()}`); @@ -1943,7 +1943,7 @@ if (process.getgid) { ``` ```cjs -const process = require('process'); +const process = require('node:process'); if (process.getgid) { console.log(`Current gid: ${process.getgid()}`); @@ -1966,7 +1966,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 ] @@ -1974,7 +1974,7 @@ if (process.getgroups) { ``` ```cjs -const process = require('process'); +const process = require('node:process'); if (process.getgroups) { console.log(process.getgroups()); // [ 16, 21, 297 ] @@ -1996,7 +1996,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()}`); @@ -2004,7 +2004,7 @@ if (process.getuid) { ``` ```cjs -const process = require('process'); +const process = require('node:process'); if (process.getuid) { console.log(`Current uid: ${process.getuid()}`); @@ -2054,7 +2054,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(); @@ -2070,7 +2070,7 @@ setTimeout(() => { ``` ```cjs -const { hrtime } = require('process'); +const { hrtime } = require('node:process'); const NS_PER_SEC = 1e9; const time = hrtime(); @@ -2101,7 +2101,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 @@ -2116,7 +2116,7 @@ setTimeout(() => { ``` ```cjs -const { hrtime } = require('process'); +const { hrtime } = require('node:process'); const start = hrtime.bigint(); // 191051479007711n @@ -2147,7 +2147,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 @@ -2157,7 +2157,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 @@ -2196,7 +2196,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.'); @@ -2211,7 +2211,7 @@ kill(process.pid, 'SIGHUP'); ``` ```cjs -const process = require('process'); +const process = require('node:process'); process.on('SIGHUP', () => { console.log('Got SIGHUP signal.'); @@ -2274,7 +2274,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: @@ -2288,7 +2288,7 @@ console.log(memoryUsage()); ``` ```cjs -const { memoryUsage } = require('process'); +const { memoryUsage } = require('node:process'); console.log(memoryUsage()); // Prints: @@ -2341,14 +2341,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 @@ -2379,7 +2379,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(() => { @@ -2393,7 +2393,7 @@ console.log('scheduled'); ``` ```cjs -const { nextTick } = require('process'); +const { nextTick } = require('node:process'); console.log('start'); nextTick(() => { @@ -2411,7 +2411,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); @@ -2428,7 +2428,7 @@ thing.getReadyForStuff(); ``` ```cjs -const { nextTick } = require('process'); +const { nextTick } = require('node:process'); function MyThing(options) { this.setupOptions(options); @@ -2476,7 +2476,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) { @@ -2489,7 +2489,7 @@ function definitelyAsync(arg, cb) { ``` ```cjs -const { nextTick } = require('process'); +const { nextTick } = require('node:process'); function definitelyAsync(arg, cb) { if (arg) { @@ -2510,7 +2510,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)); @@ -2522,7 +2522,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)); @@ -2604,13 +2604,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}`); ``` @@ -2637,13 +2637,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}`); ``` @@ -2667,13 +2667,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}`); ``` @@ -2765,13 +2765,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}`); ``` @@ -2795,13 +2795,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}`); ``` @@ -2825,13 +2825,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}`); ``` @@ -2856,24 +2856,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'); ``` @@ -2897,13 +2897,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}`); ``` @@ -2926,13 +2926,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}`); ``` @@ -2954,13 +2954,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}`); ``` @@ -2983,13 +2983,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}`); ``` @@ -3020,13 +3020,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(); ``` @@ -3083,7 +3083,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()); /* @@ -3110,7 +3110,7 @@ console.log(resourceUsage()); ``` ```cjs -const { resourceUsage } = require('process'); +const { resourceUsage } = require('node:process'); console.log(resourceUsage()); /* @@ -3176,7 +3176,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()}`); @@ -3190,7 +3190,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()}`); @@ -3221,7 +3221,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()}`); @@ -3235,7 +3235,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()}`); @@ -3266,7 +3266,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()}`); @@ -3280,7 +3280,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()}`); @@ -3312,7 +3312,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 { @@ -3325,7 +3325,7 @@ if (process.getgroups && process.setgroups) { ``` ```cjs -const process = require('process'); +const process = require('node:process'); if (process.getgroups && process.setgroups) { try { @@ -3355,7 +3355,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()}`); @@ -3369,7 +3369,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()}`); @@ -3492,13 +3492,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); ``` @@ -3665,7 +3665,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); @@ -3675,7 +3675,7 @@ console.log( ``` ```cjs -const { umask } = require('process'); +const { umask } = require('node:process'); const newmask = 0o022; const oldmask = umask(newmask); @@ -3711,14 +3711,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 @@ -3748,13 +3748,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 b378cba20bcdcd..443d89f8b49390 100644 --- a/doc/api/readline.md +++ b/doc/api/readline.md @@ -6,8 +6,8 @@ -The `readline` module provides an interface for reading data from a [Readable][] -stream (such as [`process.stdin`][]) one line at a time. +The `node:readline` module provides an interface for reading data from a +[Readable][] stream (such as [`process.stdin`][]) one line at a time. To use the promise-based APIs: @@ -16,7 +16,7 @@ import * as readline from 'node:readline/promises'; ``` ```cjs -const readline = require('readline/promises'); +const readline = require('node:readline/promises'); ``` To use the callback and sync APIs: @@ -26,10 +26,11 @@ import * as readline from 'node:readline'; ``` ```cjs -const readline = require('readline'); +const readline = require('node:readline'); ``` -The following simple example illustrates the basic use of the `readline` module. +The following simple example illustrates the basic use of the `node:readline` +module. ```mjs import * as readline from 'node:readline/promises'; @@ -45,8 +46,8 @@ rl.close(); ``` ```cjs -const readline = require('readline'); -const { stdin: input, stdout: output } = require('process'); +const readline = require('node:readline'); +const { stdin: input, stdout: output } = require('node:process'); const rl = readline.createInterface({ input, output }); @@ -758,7 +759,7 @@ The `readlinePromises.createInterface()` method creates a new `readlinePromises. instance. ```js -const readlinePromises = require('readline/promises'); +const readlinePromises = require('node:readline/promises'); const rl = readlinePromises.createInterface({ input: process.stdin, output: process.stdout @@ -1015,7 +1016,7 @@ The `readline.createInterface()` method creates a new `readline.Interface` instance. ```js -const readline = require('readline'); +const readline = require('node:readline'); const rl = readline.createInterface({ input: process.stdin, output: process.stdout @@ -1153,7 +1154,7 @@ The following example illustrates the use of `readline.Interface` class to implement a small command-line interface: ```js -const readline = require('readline'); +const readline = require('node:readline'); const rl = readline.createInterface({ input: process.stdin, output: process.stdout, @@ -1185,8 +1186,8 @@ time. The easiest way to do so is leveraging the [`fs.ReadStream`][] API as well as a `for await...of` loop: ```js -const fs = require('fs'); -const readline = require('readline'); +const fs = require('node:fs'); +const readline = require('node:readline'); async function processLineByLine() { const fileStream = fs.createReadStream('input.txt'); @@ -1210,8 +1211,8 @@ processLineByLine(); Alternatively, one could use the [`'line'`][] event: ```js -const fs = require('fs'); -const readline = require('readline'); +const fs = require('node:fs'); +const readline = require('node:readline'); const rl = readline.createInterface({ input: fs.createReadStream('sample.txt'), @@ -1227,9 +1228,9 @@ Currently, `for await...of` loop can be a bit slower. If `async` / `await` flow and speed are both essential, a mixed approach can be applied: ```js -const { once } = require('events'); -const { createReadStream } = require('fs'); -const { createInterface } = require('readline'); +const { once } = require('node:events'); +const { createReadStream } = require('node:fs'); +const { createInterface } = require('node:readline'); (async function processLineByLine() { try { 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 9ba920f7795318..cd8e7e6e7f5c80 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(); @@ -477,7 +477,7 @@ added: v8.0.0 Is `true` after [`writable.destroy()`][writable-destroy] has been called. ```cjs -const { Writable } = require('stream'); +const { Writable } = require('node:stream'); const myStream = new Writable(); @@ -523,7 +523,7 @@ Calling the [`stream.write()`][stream-write] method after calling ```js // Write 'hello, ' and then end with 'world!'. -const fs = require('fs'); +const fs = require('node:fs'); const file = fs.createWriteStream('example.txt'); file.write('hello, '); file.end('world!'); @@ -871,7 +871,7 @@ data. While in this state, attaching a listener for the `'data'` event will not switch `readable.readableFlowing` to `true`. ```js -const { PassThrough, Writable } = require('stream'); +const { PassThrough, Writable } = require('node:stream'); const pass = new PassThrough(); const writable = new Writable(); @@ -1041,7 +1041,7 @@ event. This is also true if there never was any data to be read. For instance, in the following example, `foo.txt` is an empty file: ```js -const fs = require('fs'); +const fs = require('node:fs'); const rr = fs.createReadStream('foo.txt'); rr.on('readable', () => { console.log(`readable: ${rr.read()}`); @@ -1200,7 +1200,7 @@ The following example pipes all of the data from the `readable` into a file named `file.txt`: ```js -const fs = require('fs'); +const fs = require('node:fs'); const readable = getReadableStreamSomehow(); const writable = fs.createWriteStream('file.txt'); // All the data from readable goes into 'file.txt'. @@ -1214,7 +1214,7 @@ The `readable.pipe()` method returns a reference to the _destination_ stream making it possible to set up chains of piped streams: ```js -const fs = require('fs'); +const fs = require('node:fs'); const r = fs.createReadStream('file.txt'); const z = zlib.createGzip(); const w = fs.createWriteStream('file.txt.gz'); @@ -1518,7 +1518,7 @@ If the `destination` is specified, but no pipe is set up for it, then the method does nothing. ```js -const fs = require('fs'); +const fs = require('node:fs'); const readable = getReadableStreamSomehow(); const writable = fs.createWriteStream('file.txt'); // All the data from readable goes into 'file.txt', @@ -1570,7 +1570,7 @@ section for more information. // Pull off a header delimited by \n\n. // Use unshift() if we get too much. // Call the callback with (error, header, stream). -const { StringDecoder } = require('string_decoder'); +const { StringDecoder } = require('node:string_decoder'); function parseHeader(stream, callback) { stream.on('error', callback); stream.on('readable', onReadable); @@ -1620,8 +1620,9 @@ added: v0.9.4 * `stream` {Stream} An "old style" readable stream * Returns: {this} -Prior to Node.js 0.10, streams did not implement the entire `stream` module API -as it is currently defined. (See [Compatibility][] for more information.) +Prior to Node.js 0.10, streams did not implement the entire `node:stream` +module API as it is currently defined. (See [Compatibility][] for more +information.) When using an older Node.js library that emits [`'data'`][] events and has a [`stream.pause()`][stream-pause] method that is advisory only, the @@ -1634,7 +1635,7 @@ libraries. ```js const { OldReader } = require('./old-api-module.js'); -const { Readable } = require('stream'); +const { Readable } = require('node:stream'); const oreader = new OldReader(); const myReader = new Readable().wrap(oreader); @@ -1656,7 +1657,7 @@ changes: * Returns: {AsyncIterator} to fully consume the stream. ```js -const fs = require('fs'); +const fs = require('node:fs'); async function print(readable) { readable.setEncoding('utf8'); @@ -1697,7 +1698,7 @@ destruction of the stream if the `for await...of` loop is exited by `return`, emitted an error during iteration. ```js -const { Readable } = require('stream'); +const { Readable } = require('node:stream'); async function printIterator(readable) { for await (const chunk of readable.iterator({ destroyOnReturn: false })) { @@ -1759,8 +1760,8 @@ for every chunk in the stream. If the `fn` function returns a promise - that promise will be `await`ed before being passed to the result stream. ```mjs -import { Readable } from 'stream'; -import { Resolver } from 'dns/promises'; +import { Readable } from 'node:stream'; +import { Resolver } from 'node:dns/promises'; // With a synchronous mapper. for await (const chunk of Readable.from([1, 2, 3, 4]).map((x) => x * 2)) { @@ -1806,8 +1807,8 @@ passed to the result stream. If the `fn` function returns a promise - that promise will be `await`ed. ```mjs -import { Readable } from 'stream'; -import { Resolver } from 'dns/promises'; +import { Readable } from 'node:stream'; +import { Resolver } from 'node:dns/promises'; // With a synchronous predicate. for await (const chunk of Readable.from([1, 2, 3, 4]).filter((x) => x > 2)) { @@ -1864,8 +1865,8 @@ uses the [`readable`][] event in the underlying machinary and can limit the number of concurrent `fn` calls. ```mjs -import { Readable } from 'stream'; -import { Resolver } from 'dns/promises'; +import { Readable } from 'node:stream'; +import { Resolver } from 'node:dns/promises'; // With a synchronous predicate. for await (const chunk of Readable.from([1, 2, 3, 4]).filter((x) => x > 2)) { @@ -1909,8 +1910,8 @@ streams. It's intended for interoperability and convenience, not as the primary way to consume streams. ```mjs -import { Readable } from 'stream'; -import { Resolver } from 'dns/promises'; +import { Readable } from 'node:stream'; +import { Resolver } from 'node:dns/promises'; await Readable.from([1, 2, 3, 4]).toArray(); // [1, 2, 3, 4] @@ -1955,8 +1956,8 @@ calls on the chunks return a truthy value, the promise is fulfilled with `false`. ```mjs -import { Readable } from 'stream'; -import { stat } from 'fs/promises'; +import { Readable } from 'node:stream'; +import { stat } from 'node:fs/promises'; // With a synchronous predicate. await Readable.from([1, 2, 3, 4]).some((x) => x > 2); // true @@ -2004,8 +2005,8 @@ fulfilled with value for which `fn` returned a truthy value. If all of the `undefined`. ```mjs -import { Readable } from 'stream'; -import { stat } from 'fs/promises'; +import { Readable } from 'node:stream'; +import { stat } from 'node:fs/promises'; // With a synchronous predicate. await Readable.from([1, 2, 3, 4]).find((x) => x > 2); // 3 @@ -2053,8 +2054,8 @@ destroyed and the promise is fulfilled with `false`. If all of the `fn` calls on the chunks return a truthy value, the promise is fulfilled with `true`. ```mjs -import { Readable } from 'stream'; -import { stat } from 'fs/promises'; +import { Readable } from 'node:stream'; +import { stat } from 'node:fs/promises'; // With a synchronous predicate. await Readable.from([1, 2, 3, 4]).every((x) => x > 2); // false @@ -2103,8 +2104,8 @@ It is possible to return a stream or another iterable or async iterable from stream. ```mjs -import { Readable } from 'stream'; -import { createReadStream } from 'fs'; +import { Readable } from 'node:stream'; +import { createReadStream } from 'node:fs'; // With a synchronous mapper. for await (const chunk of Readable.from([1, 2, 3, 4]).flatMap((x) => [x, x])) { @@ -2140,7 +2141,7 @@ added: v17.5.0 This method returns a new stream with the first `limit` chunks dropped. ```mjs -import { Readable } from 'stream'; +import { Readable } from 'node:stream'; await Readable.from([1, 2, 3, 4]).drop(2).toArray(); // [3, 4] ``` @@ -2162,7 +2163,7 @@ added: v17.5.0 This method returns a new stream with the first `limit` chunks. ```mjs -import { Readable } from 'stream'; +import { Readable } from 'node:stream'; await Readable.from([1, 2, 3, 4]).take(2).toArray(); // [1, 2] ``` @@ -2185,7 +2186,7 @@ with a counter in the form `[index, chunk]`. The first index value is 0 and it increases by 1 for each chunk produced. ```mjs -import { Readable } from 'stream'; +import { Readable } from 'node:stream'; const pairs = await Readable.from(['a', 'b', 'c']).asIndexedPairs().toArray(); console.log(pairs); // [[0, 'a'], [1, 'b'], [2, 'c']] @@ -2226,7 +2227,7 @@ initial value. If the stream is empty, the promise is rejected with a `TypeError` with the `ERR_INVALID_ARGS` code property. ```mjs -import { Readable } from 'stream'; +import { Readable } from 'node:stream'; const ten = await Readable.from([1, 2, 3, 4]).reduce((previous, data) => { return previous + data; @@ -2361,7 +2362,7 @@ A function to get notified when a stream is no longer readable, writable or has experienced an error or a premature close event. ```js -const { finished } = require('stream'); +const { finished } = require('node:stream'); const rs = fs.createReadStream('archive.tar'); @@ -2383,7 +2384,7 @@ or `'finish'`. The `finished` API provides promise version: ```js -const { finished } = require('stream/promises'); +const { finished } = require('node:stream/promises'); const rs = fs.createReadStream('archive.tar'); @@ -2451,9 +2452,9 @@ A module method to pipe between streams and generators forwarding errors and properly cleaning up and provide a callback when the pipeline is complete. ```js -const { pipeline } = require('stream'); -const fs = require('fs'); -const zlib = require('zlib'); +const { pipeline } = require('node:stream'); +const fs = require('node:fs'); +const zlib = require('node:zlib'); // Use the pipeline API to easily pipe a series of streams // together and get notified when the pipeline is fully done. @@ -2481,7 +2482,7 @@ receive an options argument as the last parameter with a `AbortError`. ```js -const { pipeline } = require('stream/promises'); +const { pipeline } = require('node:stream/promises'); async function run() { await pipeline( @@ -2499,7 +2500,7 @@ To use an `AbortSignal`, pass it inside an options object, as the last argument: ```js -const { pipeline } = require('stream/promises'); +const { pipeline } = require('node:stream/promises'); async function run() { const ac = new AbortController(); @@ -2520,8 +2521,8 @@ run().catch(console.error); // AbortError The `pipeline` API also supports async generators: ```js -const { pipeline } = require('stream/promises'); -const fs = require('fs'); +const { pipeline } = require('node:stream/promises'); +const fs = require('node:fs'); async function run() { await pipeline( @@ -2545,8 +2546,8 @@ Especially in the case where the async generator is the source for the pipeline (i.e. first argument) or the pipeline will never complete. ```js -const { pipeline } = require('stream/promises'); -const fs = require('fs'); +const { pipeline } = require('node:stream/promises'); +const fs = require('node:fs'); async function run() { await pipeline( @@ -2579,9 +2580,9 @@ once it would destroy the socket without sending the expected response. See the example below: ```js -const fs = require('fs'); -const http = require('http'); -const { pipeline } = require('stream'); +const fs = require('node:fs'); +const http = require('node:http'); +const { pipeline } = require('node:stream'); const server = http.createServer((req, res) => { const fileStream = fs.createReadStream('./fileNotExist.txt'); @@ -2621,7 +2622,7 @@ If passed a `Function` it must be a factory method taking a `source` `Iterable`. ```mjs -import { compose, Transform } from 'stream'; +import { compose, Transform } from 'node:stream'; const removeSpaces = new Transform({ transform(chunk, encoding, callback) { @@ -2655,8 +2656,8 @@ functions into streams. either `null` or `undefined`. ```mjs -import { compose } from 'stream'; -import { finished } from 'stream/promises'; +import { compose } from 'node:stream'; +import { finished } from 'node:stream/promises'; // Convert AsyncIterable into readable Duplex. const s1 = compose(async function*() { @@ -2704,7 +2705,7 @@ added: A utility method for creating readable streams out of iterators. ```js -const { Readable } = require('stream'); +const { Readable } = require('node:stream'); async function * generate() { yield 'hello'; @@ -2898,7 +2899,7 @@ Calling `abort` on the `AbortController` corresponding to the passed on the stream. ```js -const fs = require('fs'); +const fs = require('node:fs'); const controller = new AbortController(); const read = addAbortSignal( @@ -2937,7 +2938,7 @@ const stream = addAbortSignal( -The `stream` module API has been designed to make it possible to easily +The `node:stream` module API has been designed to make it possible to easily implement streams using JavaScript's prototypal inheritance model. First, a stream developer would declare a new JavaScript class that extends one @@ -2948,7 +2949,7 @@ parent class constructor: ```js -const { Writable } = require('stream'); +const { Writable } = require('node:stream'); class MyWritable extends Writable { constructor({ highWaterMark, ...options }) { @@ -2999,7 +3000,7 @@ inheritance. This can be accomplished by directly creating instances of the objects and passing appropriate methods as constructor options. ```js -const { Writable } = require('stream'); +const { Writable } = require('node:stream'); const myWritable = new Writable({ construct(callback) { @@ -3081,7 +3082,7 @@ changes: ```js -const { Writable } = require('stream'); +const { Writable } = require('node:stream'); class MyWritable extends Writable { constructor(options) { @@ -3095,8 +3096,8 @@ class MyWritable extends Writable { Or, when using pre-ES6 style constructors: ```js -const { Writable } = require('stream'); -const util = require('util'); +const { Writable } = require('node:stream'); +const util = require('node:util'); function MyWritable(options) { if (!(this instanceof MyWritable)) @@ -3109,7 +3110,7 @@ util.inherits(MyWritable, Writable); Or, using the simplified constructor approach: ```js -const { Writable } = require('stream'); +const { Writable } = require('node:stream'); const myWritable = new Writable({ write(chunk, encoding, callback) { @@ -3126,7 +3127,7 @@ Calling `abort` on the `AbortController` corresponding to the passed on the writeable stream. ```js -const { Writable } = require('stream'); +const { Writable } = require('node:stream'); const controller = new AbortController(); const myWritable = new Writable({ @@ -3161,8 +3162,8 @@ has returned, delaying any `_write()`, `_final()` and `_destroy()` calls until initialize resources before the stream can be used. ```js -const { Writable } = require('stream'); -const fs = require('fs'); +const { Writable } = require('node:stream'); +const fs = require('node:fs'); class WriteStream extends Writable { constructor(filename) { @@ -3318,7 +3319,7 @@ If a `Readable` stream pipes into a `Writable` stream when `Writable` emits an error, the `Readable` stream will be unpiped. ```js -const { Writable } = require('stream'); +const { Writable } = require('node:stream'); const myWritable = new Writable({ write(chunk, encoding, callback) { @@ -3339,7 +3340,7 @@ is not of any real particular usefulness, the example illustrates each of the required elements of a custom [`Writable`][] stream instance: ```js -const { Writable } = require('stream'); +const { Writable } = require('node:stream'); class MyWritable extends Writable { _write(chunk, encoding, callback) { @@ -3360,8 +3361,8 @@ characters encoding, such as UTF-8. The following example shows how to decode multi-byte strings using `StringDecoder` and [`Writable`][]. ```js -const { Writable } = require('stream'); -const { StringDecoder } = require('string_decoder'); +const { Writable } = require('node:stream'); +const { StringDecoder } = require('node:string_decoder'); class StringWritable extends Writable { constructor(options) { @@ -3441,7 +3442,7 @@ changes: ```js -const { Readable } = require('stream'); +const { Readable } = require('node:stream'); class MyReadable extends Readable { constructor(options) { @@ -3455,8 +3456,8 @@ class MyReadable extends Readable { Or, when using pre-ES6 style constructors: ```js -const { Readable } = require('stream'); -const util = require('util'); +const { Readable } = require('node:stream'); +const util = require('node:util'); function MyReadable(options) { if (!(this instanceof MyReadable)) @@ -3469,7 +3470,7 @@ util.inherits(MyReadable, Readable); Or, using the simplified constructor approach: ```js -const { Readable } = require('stream'); +const { Readable } = require('node:stream'); const myReadable = new Readable({ read(size) { @@ -3483,7 +3484,7 @@ Calling `abort` on the `AbortController` corresponding to the passed on the readable created. ```js -const { Readable } = require('stream'); +const { Readable } = require('node:stream'); const controller = new AbortController(); const read = new Readable({ read(size) { @@ -3514,8 +3515,8 @@ called. This is useful to initialize state or asynchronously initialize resources before the stream can be used. ```js -const { Readable } = require('stream'); -const fs = require('fs'); +const { Readable } = require('node:stream'); +const fs = require('node:fs'); class ReadStream extends Readable { constructor(filename) { @@ -3687,7 +3688,7 @@ Throwing an `Error` from within [`readable._read()`][] or manually emitting an `'error'` event results in undefined behavior. ```js -const { Readable } = require('stream'); +const { Readable } = require('node:stream'); const myReadable = new Readable({ read(size) { @@ -3709,7 +3710,7 @@ The following is a basic example of a `Readable` stream that emits the numerals from 1 to 1,000,000 in ascending order, and then ends. ```js -const { Readable } = require('stream'); +const { Readable } = require('node:stream'); class Counter extends Readable { constructor(opt) { @@ -3780,7 +3781,7 @@ changes: ```js -const { Duplex } = require('stream'); +const { Duplex } = require('node:stream'); class MyDuplex extends Duplex { constructor(options) { @@ -3793,8 +3794,8 @@ class MyDuplex extends Duplex { Or, when using pre-ES6 style constructors: ```js -const { Duplex } = require('stream'); -const util = require('util'); +const { Duplex } = require('node:stream'); +const util = require('node:util'); function MyDuplex(options) { if (!(this instanceof MyDuplex)) @@ -3807,7 +3808,7 @@ util.inherits(MyDuplex, Duplex); Or, using the simplified constructor approach: ```js -const { Duplex } = require('stream'); +const { Duplex } = require('node:stream'); const myDuplex = new Duplex({ read(size) { @@ -3822,8 +3823,8 @@ const myDuplex = new Duplex({ When using pipeline: ```js -const { Transform, pipeline } = require('stream'); -const fs = require('fs'); +const { Transform, pipeline } = require('node:stream'); +const fs = require('node:fs'); pipeline( fs.createReadStream('object.json') @@ -3871,7 +3872,7 @@ incoming written data via the [`Writable`][] interface that is read back out via the [`Readable`][] interface. ```js -const { Duplex } = require('stream'); +const { Duplex } = require('node:stream'); const kSource = Symbol('source'); class MyDuplex extends Duplex { @@ -3912,7 +3913,7 @@ that accepts JavaScript numbers that are converted to hexadecimal strings on the `Readable` side. ```js -const { Transform } = require('stream'); +const { Transform } = require('node:stream'); // All Transform streams are also Duplex Streams. const myTransform = new Transform({ @@ -3977,7 +3978,7 @@ output on the `Readable` side is not consumed. ```js -const { Transform } = require('stream'); +const { Transform } = require('node:stream'); class MyTransform extends Transform { constructor(options) { @@ -3990,8 +3991,8 @@ class MyTransform extends Transform { Or, when using pre-ES6 style constructors: ```js -const { Transform } = require('stream'); -const util = require('util'); +const { Transform } = require('node:stream'); +const util = require('node:util'); function MyTransform(options) { if (!(this instanceof MyTransform)) @@ -4004,7 +4005,7 @@ util.inherits(MyTransform, Transform); Or, using the simplified constructor approach: ```js -const { Transform } = require('stream'); +const { Transform } = require('node:stream'); const myTransform = new Transform({ transform(chunk, encoding, callback) { @@ -4148,7 +4149,7 @@ A Node.js readable stream can be created from an asynchronous generator using the `Readable.from()` utility method: ```js -const { Readable } = require('stream'); +const { Readable } = require('node:stream'); const ac = new AbortController(); const signal = ac.signal; @@ -4177,9 +4178,9 @@ handling of backpressure and errors. [`stream.pipeline()`][] abstracts away the handling of backpressure and backpressure-related errors: ```js -const fs = require('fs'); -const { pipeline } = require('stream'); -const { pipeline: pipelinePromise } = require('stream/promises'); +const fs = require('node:fs'); +const { pipeline } = require('node:stream'); +const { pipeline: pipelinePromise } = require('node:stream/promises'); const writable = fs.createWriteStream('./file'); 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 79b881952475f6..3a4a6f35e1e97f 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 4cddecd24f16e5..d054ad7d419c32 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 @@ -269,7 +269,7 @@ returned Promises will be rejected with an `'AbortError'`. For `setImmediate()`: ```js -const { setImmediate: setImmediatePromise } = require('timers/promises'); +const { setImmediate: setImmediatePromise } = require('node:timers/promises'); const ac = new AbortController(); const signal = ac.signal; @@ -287,7 +287,7 @@ ac.abort(); For `setTimeout()`: ```js -const { setTimeout: setTimeoutPromise } = require('timers/promises'); +const { setTimeout: setTimeoutPromise } = require('node:timers/promises'); const ac = new AbortController(); const signal = ac.signal; @@ -347,7 +347,7 @@ changes: The `timers/promises` API provides an alternative set of timer functions that return `Promise` objects. The API is accessible via -`require('timers/promises')`. +`require('node:timers/promises')`. ```mjs import { @@ -362,7 +362,7 @@ const { setTimeout, setImmediate, setInterval, -} = require('timers/promises'); +} = require('node:timers/promises'); ``` ### `timersPromises.setTimeout([delay[, value[, options]]])` @@ -394,7 +394,7 @@ console.log(res); // Prints 'result' ```cjs const { setTimeout, -} = require('timers/promises'); +} = require('node:timers/promises'); setTimeout(100, 'result').then((res) => { console.log(res); // Prints 'result' @@ -428,7 +428,7 @@ console.log(res); // Prints 'result' ```cjs const { setImmediate, -} = require('timers/promises'); +} = require('node:timers/promises'); setImmediate('result').then((res) => { console.log(res); // Prints 'result' @@ -472,7 +472,7 @@ console.log(Date.now()); ```cjs const { setInterval, -} = require('timers/promises'); +} = require('node:timers/promises'); const interval = 100; (async function() { @@ -511,7 +511,7 @@ to calling `timersPromises.setTimeout(delay, undefined, options)` except that the `ref` option is not supported. ```mjs -import { scheduler } from 'timers/promises'; +import { scheduler } from 'node:timers/promises'; await scheduler.wait(1000); // Wait one second before continuing ``` diff --git a/doc/api/tls.md b/doc/api/tls.md index df77ff80892475..52e0e71f1e03ab 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` @@ -1692,8 +1692,8 @@ The following illustrates a client for the echo server example from ```js // Assumes an echo server that is listening on port 8000. -const tls = require('tls'); -const fs = require('fs'); +const tls = require('node:tls'); +const fs = require('node:fs'); const options = { // Necessary only if the server requires client certificate authentication. @@ -2093,14 +2093,14 @@ changes: Creates a new [`tls.Server`][]. The `secureConnectionListener`, if provided, is automatically set as a listener for the [`'secureConnection'`][] event. -The `ticketKeys` options is automatically shared between `cluster` module +The `ticketKeys` options is automatically shared between `node:cluster` module workers. The following illustrates a simple echo server: ```js -const tls = require('tls'); -const fs = require('fs'); +const tls = require('node:tls'); +const fs = require('node:fs'); const options = { key: fs.readFileSync('server-key.pem'), 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 453ff10a2bb48b..edbfd6829954fe 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); @@ -1014,7 +1014,7 @@ This feature is only available if the `node` executable was compiled with [ICU][] enabled. If not, the domain names are passed through unchanged. ```mjs -import url from 'url'; +import url from 'node:url'; console.log(url.domainToASCII('español.com')); // Prints xn--espaol-zwa.com @@ -1025,7 +1025,7 @@ console.log(url.domainToASCII('xn--iñvalid.com')); ``` ```cjs -const url = require('url'); +const url = require('node:url'); console.log(url.domainToASCII('español.com')); // Prints xn--espaol-zwa.com @@ -1055,7 +1055,7 @@ This feature is only available if the `node` executable was compiled with [ICU][] enabled. If not, the domain names are passed through unchanged. ```mjs -import url from 'url'; +import url from 'node:url'; console.log(url.domainToUnicode('xn--espaol-zwa.com')); // Prints español.com @@ -1066,7 +1066,7 @@ console.log(url.domainToUnicode('xn--iñvalid.com')); ``` ```cjs -const url = require('url'); +const url = require('node:url'); console.log(url.domainToUnicode('xn--espaol-zwa.com')); // Prints español.com @@ -1089,7 +1089,7 @@ This function ensures the correct decodings of percent-encoded characters as well as ensuring a cross-platform valid absolute path string. ```mjs -import { fileURLToPath } from 'url'; +import { fileURLToPath } from 'node:url'; const __filename = fileURLToPath(import.meta.url); @@ -1107,7 +1107,7 @@ fileURLToPath('file:///hello world'); // Correct: /hello world (POSIX) ``` ```cjs -const { fileURLToPath } = require('url'); +const { fileURLToPath } = require('node:url'); new URL('file:///C:/path/').pathname; // Incorrect: /C:/path/ fileURLToPath('file:///C:/path/'); // Correct: C:\path\ (Windows) @@ -1149,7 +1149,7 @@ any way. The `url.format(URL[, options])` method allows for basic customization of the output. ```mjs -import url from 'url'; +import url from 'node:url'; const myURL = new URL('https://a:b@測試?abc#foo'); console.log(myURL.href); @@ -1163,7 +1163,7 @@ console.log(url.format(myURL, { fragment: false, unicode: true, auth: false })); ``` ```cjs -const url = require('url'); +const url = require('node:url'); const myURL = new URL('https://a:b@測試?abc#foo'); console.log(myURL.href); @@ -1189,7 +1189,7 @@ This function ensures that `path` is resolved absolutely, and that the URL control characters are correctly encoded when converting into a File URL. ```mjs -import { pathToFileURL } from 'url'; +import { pathToFileURL } from 'node:url'; new URL('/foo#1', 'file:'); // Incorrect: file:///foo#1 pathToFileURL('/foo#1'); // Correct: file:///foo%231 (POSIX) @@ -1199,7 +1199,7 @@ pathToFileURL('/some/path%.c'); // Correct: file:///some/path%25.c (POSI ``` ```cjs -const { pathToFileURL } = require('url'); +const { pathToFileURL } = require('node:url'); new URL(__filename); // Incorrect: throws (POSIX) new URL(__filename); // Incorrect: C:\... (Windows) pathToFileURL(__filename); // Correct: file:///... (POSIX) @@ -1241,7 +1241,7 @@ This utility function converts a URL object into an ordinary options object as expected by the [`http.request()`][] and [`https.request()`][] APIs. ```mjs -import { urlToHttpOptions } from 'url'; +import { urlToHttpOptions } from 'node:url'; const myURL = new URL('https://a:b@測試?abc#foo'); console.log(urlToHttpOptions(myURL)); @@ -1260,7 +1260,7 @@ console.log(urlToHttpOptions(myURL)); ``` ```cjs -const { urlToHttpOptions } = require('url'); +const { urlToHttpOptions } = require('node:url'); const myURL = new URL('https://a:b@測試?abc#foo'); console.log(urlToHttpOptions(myUrl)); @@ -1310,7 +1310,8 @@ changes: > Stability: 3 - Legacy: Use the WHATWG URL API instead. -The legacy `urlObject` (`require('url').Url` or `import { Url } from 'url'`) is +The legacy `urlObject` (`require('node:url').Url` or +`import { Url } from 'node:url'`) is created and returned by the `url.parse()` function. #### `urlObject.auth` @@ -1446,7 +1447,7 @@ The `url.format()` method returns a formatted URL string derived from `urlObject`. ```js -const url = require('url'); +const url = require('node:url'); url.format({ protocol: 'https', hostname: 'example.com', @@ -1609,7 +1610,7 @@ The `url.resolve()` method resolves a target URL relative to a base URL in a manner similar to that of a web browser resolving an anchor tag. ```js -const url = require('url'); +const url = require('node:url'); url.resolve('/one/two/three', 'four'); // '/one/two/four' url.resolve('http://example.com/', '/one'); // 'http://example.com/one' url.resolve('http://example.com/one', '/two'); // 'http://example.com/two' diff --git a/doc/api/util.md b/doc/api/util.md index e235b8f338e557..1686c08e0fba82 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'); @@ -435,8 +435,8 @@ As an additional convenience, `superConstructor` will be accessible through the `constructor.super_` property. ```js -const util = require('util'); -const EventEmitter = require('events'); +const util = require('node:util'); +const EventEmitter = require('node:events'); function MyStream() { EventEmitter.call(this); @@ -462,7 +462,7 @@ stream.write('It works!'); // Received data: "It works!" ES6 example using `class` and `extends`: ```js -const EventEmitter = require('events'); +const EventEmitter = require('node:events'); class MyStream extends EventEmitter { write(data) { @@ -642,7 +642,7 @@ util.inspect(baz); // '[foo] {}' Circular references point to their anchor by using a reference index: ```js -const { inspect } = require('util'); +const { inspect } = require('node:util'); const obj = {}; obj.a = [obj]; @@ -660,7 +660,7 @@ console.log(inspect(obj)); The following example inspects all properties of the `util` object: ```js -const util = require('util'); +const util = require('node:util'); console.log(util.inspect(util, { showHidden: true, depth: null })); ``` @@ -668,7 +668,7 @@ console.log(util.inspect(util, { showHidden: true, depth: null })); The following example highlights the effect of the `compact` option: ```js -const util = require('util'); +const util = require('node:util'); const o = { a: [1, 2, [[ @@ -724,7 +724,7 @@ guarantee which entries are displayed. That means retrieving the same with no remaining strong references may be garbage collected at any time. ```js -const { inspect } = require('util'); +const { inspect } = require('node:util'); const obj = { a: 1 }; const obj2 = { b: 2 }; @@ -738,8 +738,8 @@ The `sorted` option ensures that an object's property insertion order does not impact the result of `util.inspect()`. ```js -const { inspect } = require('util'); -const assert = require('assert'); +const { inspect } = require('node:util'); +const assert = require('node:assert'); const o1 = { b: [2, 3, 1], @@ -766,7 +766,7 @@ The `numericSeparator` option adds an underscore every three digits to all numbers. ```js -const { inspect } = require('util'); +const { inspect } = require('node:util'); const thousand = 1_000; const million = 1_000_000; @@ -892,7 +892,7 @@ which `util.inspect()` will invoke and use the result of when inspecting the object. ```js -const util = require('util'); +const util = require('node:util'); class Box { constructor(value) { @@ -927,7 +927,7 @@ a string but may return a value of any type that will be formatted accordingly by `util.inspect()`. ```js -const util = require('util'); +const util = require('node:util'); const obj = { foo: 'this will not show up in the inspect() output' }; obj[util.inspect.custom] = (depth) => { @@ -996,7 +996,7 @@ object containing one or more valid [`util.inspect()`][] options. Setting option properties directly is also supported. ```js -const util = require('util'); +const util = require('node:util'); const arr = Array(101).fill(0); console.log(arr); // Logs the truncated array @@ -1034,8 +1034,8 @@ an `(err, value) => ...` callback as the last argument, and returns a version that returns promises. ```js -const util = require('util'); -const fs = require('fs'); +const util = require('node:util'); +const fs = require('node:fs'); const stat = util.promisify(fs.stat); stat('.').then((stats) => { @@ -1048,8 +1048,8 @@ stat('.').then((stats) => { Or, equivalently using `async function`s: ```js -const util = require('util'); -const fs = require('fs'); +const util = require('node:util'); +const fs = require('node:fs'); const stat = util.promisify(fs.stat); @@ -1072,7 +1072,7 @@ Using `promisify()` on class methods or other methods that use `this` may not work as expected unless handled specially: ```js -const util = require('util'); +const util = require('node:util'); class Foo { constructor() { @@ -1102,7 +1102,7 @@ Using the `util.promisify.custom` symbol one can override the return value of [`util.promisify()`][]: ```js -const util = require('util'); +const util = require('node:util'); function doSomething(foo, callback) { // ... @@ -1397,7 +1397,7 @@ added: v10.0.0 changes: - version: v15.3.0 pr-url: https://github.com/nodejs/node/pull/34055 - description: Exposed as `require('util/types')`. + description: Exposed as `require('node:util/types')`. --> `util.types` provides type checks for different kinds of built-in objects. @@ -1409,7 +1409,7 @@ The result generally does not make any guarantees about what kinds of properties or behavior a value exposes in JavaScript. They are primarily useful for addon developers who prefer to do type checking in JavaScript. -The API is accessible via `require('util').types` or `require('util/types')`. +The API is accessible via `require('node:util').types` or `require('node:util/types')`. ### `util.types.isAnyArrayBuffer(value)` @@ -2210,7 +2210,7 @@ Alias for [`Array.isArray()`][]. Returns `true` if the given `object` is an `Array`. Otherwise, returns `false`. ```js -const util = require('util'); +const util = require('node:util'); util.isArray([]); // Returns: true @@ -2235,7 +2235,7 @@ deprecated: v4.0.0 Returns `true` if the given `object` is a `Boolean`. Otherwise, returns `false`. ```js -const util = require('util'); +const util = require('node:util'); util.isBoolean(1); // Returns: false @@ -2260,7 +2260,7 @@ deprecated: v4.0.0 Returns `true` if the given `object` is a `Buffer`. Otherwise, returns `false`. ```js -const util = require('util'); +const util = require('node:util'); util.isBuffer({ length: 0 }); // Returns: false @@ -2285,7 +2285,7 @@ deprecated: v4.0.0 Returns `true` if the given `object` is a `Date`. Otherwise, returns `false`. ```js -const util = require('util'); +const util = require('node:util'); util.isDate(new Date()); // Returns: true @@ -2311,7 +2311,7 @@ Returns `true` if the given `object` is an [`Error`][]. Otherwise, returns `false`. ```js -const util = require('util'); +const util = require('node:util'); util.isError(new Error()); // Returns: true @@ -2326,7 +2326,7 @@ possible to obtain an incorrect result when the `object` argument manipulates `@@toStringTag`. ```js -const util = require('util'); +const util = require('node:util'); const obj = { name: 'Error', message: 'an error occurred' }; util.isError(obj); @@ -2352,7 +2352,7 @@ Returns `true` if the given `object` is a `Function`. Otherwise, returns `false`. ```js -const util = require('util'); +const util = require('node:util'); function Foo() {} const Bar = () => {}; @@ -2381,7 +2381,7 @@ Returns `true` if the given `object` is strictly `null`. Otherwise, returns `false`. ```js -const util = require('util'); +const util = require('node:util'); util.isNull(0); // Returns: false @@ -2408,7 +2408,7 @@ Returns `true` if the given `object` is `null` or `undefined`. Otherwise, returns `false`. ```js -const util = require('util'); +const util = require('node:util'); util.isNullOrUndefined(0); // Returns: false @@ -2433,7 +2433,7 @@ deprecated: v4.0.0 Returns `true` if the given `object` is a `Number`. Otherwise, returns `false`. ```js -const util = require('util'); +const util = require('node:util'); util.isNumber(false); // Returns: false @@ -2463,7 +2463,7 @@ Returns `true` if the given `object` is strictly an `Object` **and** not a Otherwise, returns `false`. ```js -const util = require('util'); +const util = require('node:util'); util.isObject(5); // Returns: false @@ -2493,7 +2493,7 @@ Returns `true` if the given `object` is a primitive type. Otherwise, returns `false`. ```js -const util = require('util'); +const util = require('node:util'); util.isPrimitive(5); // Returns: true @@ -2530,7 +2530,7 @@ deprecated: v4.0.0 Returns `true` if the given `object` is a `RegExp`. Otherwise, returns `false`. ```js -const util = require('util'); +const util = require('node:util'); util.isRegExp(/some regexp/); // Returns: true @@ -2555,7 +2555,7 @@ deprecated: v4.0.0 Returns `true` if the given `object` is a `string`. Otherwise, returns `false`. ```js -const util = require('util'); +const util = require('node:util'); util.isString(''); // Returns: true @@ -2582,7 +2582,7 @@ deprecated: v4.0.0 Returns `true` if the given `object` is a `Symbol`. Otherwise, returns `false`. ```js -const util = require('util'); +const util = require('node:util'); util.isSymbol(5); // Returns: false @@ -2607,7 +2607,7 @@ deprecated: v4.0.0 Returns `true` if the given `object` is `undefined`. Otherwise, returns `false`. ```js -const util = require('util'); +const util = require('node:util'); const foo = undefined; util.isUndefined(5); @@ -2633,7 +2633,7 @@ The `util.log()` method prints the given `string` to `stdout` with an included timestamp. ```js -const util = require('util'); +const util = require('node:util'); util.log('Timestamped message.'); ``` diff --git a/doc/api/v8.md b/doc/api/v8.md index 2689b6813feb7a..2126a0bd5e6449 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); ``` @@ -233,7 +233,7 @@ Usage: ```js // Print GC events to stdout for one minute. -const v8 = require('v8'); +const v8 = require('node:v8'); v8.setFlagsFromString('--trace_gc'); setTimeout(() => { v8.setFlagsFromString('--notrace_gc'); }, 60e3); ``` @@ -308,12 +308,12 @@ Generating a snapshot is a synchronous operation which blocks the event loop for a duration depending on the heap size. ```js -const { writeHeapSnapshot } = require('v8'); +const { writeHeapSnapshot } = require('node:v8'); const { Worker, isMainThread, parentPort -} = require('worker_threads'); +} = require('node:worker_threads'); if (isMainThread) { const worker = new Worker(__filename); @@ -593,7 +593,7 @@ module to produce promise lifecycle events in addition to events for other async resources. For request context management, see [`AsyncLocalStorage`][]. ```mjs -import { promiseHooks } from 'v8'; +import { promiseHooks } from 'node:v8'; // There are four lifecycle events produced by promises: @@ -662,13 +662,13 @@ added: throw as it would produce an infinite microtask loop.** ```mjs -import { promiseHooks } from 'v8'; +import { promiseHooks } from 'node:v8'; const stop = promiseHooks.onInit((promise, parent) => {}); ``` ```cjs -const { promiseHooks } = require('v8'); +const { promiseHooks } = require('node:v8'); const stop = promiseHooks.onInit((promise, parent) => {}); ``` @@ -689,13 +689,13 @@ added: throw as it would produce an infinite microtask loop.** ```mjs -import { promiseHooks } from 'v8'; +import { promiseHooks } from 'node:v8'; const stop = promiseHooks.onSettled((promise) => {}); ``` ```cjs -const { promiseHooks } = require('v8'); +const { promiseHooks } = require('node:v8'); const stop = promiseHooks.onSettled((promise) => {}); ``` @@ -716,13 +716,13 @@ added: throw as it would produce an infinite microtask loop.** ```mjs -import { promiseHooks } from 'v8'; +import { promiseHooks } from 'node:v8'; const stop = promiseHooks.onBefore((promise) => {}); ``` ```cjs -const { promiseHooks } = require('v8'); +const { promiseHooks } = require('node:v8'); const stop = promiseHooks.onBefore((promise) => {}); ``` @@ -743,13 +743,13 @@ added: throw as it would produce an infinite microtask loop.** ```mjs -import { promiseHooks } from 'v8'; +import { promiseHooks } from 'node:v8'; const stop = promiseHooks.onAfter((promise) => {}); ``` ```cjs -const { promiseHooks } = require('v8'); +const { promiseHooks } = require('node:v8'); const stop = promiseHooks.onAfter((promise) => {}); ``` @@ -783,7 +783,7 @@ specifics of all functions that can be passed to `callbacks` is in the [Hook Callbacks][] section. ```mjs -import { promiseHooks } from 'v8'; +import { promiseHooks } from 'node:v8'; const stopAll = promiseHooks.createHook({ init(promise, parent) {} @@ -791,7 +791,7 @@ const stopAll = promiseHooks.createHook({ ``` ```cjs -const { promiseHooks } = require('v8'); +const { promiseHooks } = require('node:v8'); const stopAll = promiseHooks.createHook({ init(promise, parent) {} diff --git a/doc/api/vm.md b/doc/api/vm.md index 1938b9008afeb4..bc2e520f38f300 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; @@ -177,7 +177,7 @@ the value of another global variable, then execute the code multiple times. The globals are contained in the `context` object. ```js -const vm = require('vm'); +const vm = require('node:vm'); const context = { animal: 'cat', @@ -259,7 +259,7 @@ the code multiple times in different contexts. The globals are set on and contained within each individual `context`. ```js -const vm = require('vm'); +const vm = require('node:vm'); const script = new vm.Script('globalVar = "set"'); @@ -304,7 +304,7 @@ The following example compiles code that increments a `global` variable then executes that code multiple times: ```js -const vm = require('vm'); +const vm = require('node:vm'); global.globalVar = 0; @@ -351,7 +351,7 @@ loader][]. There is also no way to interact with the Loader yet, though support is planned. ```mjs -import vm from 'vm'; +import vm from 'node:vm'; const contextifiedObject = vm.createContext({ secret: 42, @@ -422,7 +422,7 @@ await bar.evaluate(); ``` ```cjs -const vm = require('vm'); +const vm = require('node:vm'); const contextifiedObject = vm.createContext({ secret: 42, @@ -712,7 +712,7 @@ allow the module to access information outside the specified `context`. Use `vm.runInContext()` to create objects in a specific context. ```mjs -import vm from 'vm'; +import vm from 'node:vm'; const contextifiedObject = vm.createContext({ secret: 42 }); @@ -740,7 +740,7 @@ await module.evaluate(); ``` ```cjs -const vm = require('vm'); +const vm = require('node:vm'); const contextifiedObject = vm.createContext({ secret: 42 }); (async () => { const module = new vm.SourceTextModule( @@ -812,7 +812,7 @@ provide a generic interface for exposing non-JavaScript sources to ECMAScript module graphs. ```js -const vm = require('vm'); +const vm = require('node:vm'); const source = '{ "a": 1 }'; const module = new vm.SyntheticModule(['default'], function() { @@ -863,7 +863,7 @@ it is called before the module is linked, an [`ERR_VM_MODULE_STATUS`][] error will be thrown. ```mjs -import vm from 'vm'; +import vm from 'node:vm'; const m = new vm.SyntheticModule(['x'], () => { m.setExport('x', 1); @@ -876,7 +876,7 @@ assert.strictEqual(m.namespace.x, 1); ``` ```cjs -const vm = require('vm'); +const vm = require('node:vm'); (async () => { const m = new vm.SyntheticModule(['x'], () => { m.setExport('x', 1); @@ -999,7 +999,7 @@ properties but also having the built-in objects and functions any standard will remain unchanged. ```js -const vm = require('vm'); +const vm = require('node:vm'); global.globalVar = 3; @@ -1075,7 +1075,7 @@ the V8 engine, while the result of `v8.getHeapSpaceStatistics()` measure the memory occupied by each heap space in the current V8 instance. ```js -const vm = require('vm'); +const vm = require('node:vm'); // Measure the memory used by the main context. vm.measureMemory({ mode: 'summary' }) // This is the same as vm.measureMemory() @@ -1190,7 +1190,7 @@ The following example compiles and executes different scripts using a single [contextified][] object: ```js -const vm = require('vm'); +const vm = require('node:vm'); const contextObject = { globalVar: 1 }; vm.createContext(contextObject); @@ -1302,7 +1302,7 @@ The following example compiles and executes code that increments a global variable and sets a new one. These globals are contained in the `contextObject`. ```js -const vm = require('vm'); +const vm = require('node:vm'); const contextObject = { animal: 'cat', @@ -1388,7 +1388,7 @@ the JavaScript [`eval()`][] function to run the same code: ```js -const vm = require('vm'); +const vm = require('node:vm'); let localVar = 'initial value'; const vmResult = vm.runInThisContext('localVar = "vm";'); @@ -1412,17 +1412,17 @@ When using either [`script.runInThisContext()`][] or [`vm.runInThisContext()`][], the code is executed within the current V8 global context. The code passed to this VM context will have its own isolated scope. -In order to run a simple web server using the `http` module the code passed to -the context must either call `require('http')` on its own, or have a reference -to the `http` module passed to it. For instance: +In order to run a simple web server using the `node:http` module the code passed +to the context must either call `require('node:http')` on its own, or have a +reference to the `node:http` module passed to it. For instance: ```js 'use strict'; -const vm = require('vm'); +const vm = require('node:vm'); const code = ` ((require) => { - const http = require('http'); + const http = require('node:http'); http.createServer((request, response) => { response.writeHead(200, { 'Content-Type': 'text/plain' }); @@ -1451,9 +1451,9 @@ According to the [V8 Embedder's Guide][]: When the method `vm.createContext()` is called, the `contextObject` argument (or a newly-created object if `contextObject` is `undefined`) is associated internally with a new instance of a V8 Context. This V8 Context provides the -`code` run using the `vm` module's methods with an isolated global environment -within which it can operate. The process of creating the V8 Context and -associating it with the `contextObject` is what this document refers to as +`code` run using the `node:vm` module's methods with an isolated global +environment within which it can operate. The process of creating the V8 Context +and associating it with the `contextObject` is what this document refers to as "contextifying" the object. ## Timeout interactions with asynchronous tasks and Promises @@ -1469,7 +1469,7 @@ timeout of 5 milliseconds schedules an infinite loop to run after a promise resolves. The scheduled loop is never interrupted by the timeout: ```js -const vm = require('vm'); +const vm = require('node:vm'); function loop() { console.log('entering loop'); @@ -1489,7 +1489,7 @@ This can be addressed by passing `microtaskMode: 'afterEvaluate'` to the code that creates the `Context`: ```js -const vm = require('vm'); +const vm = require('node:vm'); function loop() { while (1) console.log(Date.now()); 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 f902a10934dff0..93effbdf0e4f9d 100644 --- a/doc/api/webstreams.md +++ b/doc/api/webstreams.md @@ -62,15 +62,15 @@ for await (const value of stream) ```cjs const { ReadableStream -} = require('stream/web'); +} = require('node:stream/web'); const { setInterval: every -} = require('timers/promises'); +} = require('node:timers/promises'); const { performance -} = require('perf_hooks'); +} = require('node:perf_hooks'); const SECOND = 1000; @@ -179,7 +179,7 @@ console.log(await reader.read()); ``` ```cjs -const { ReadableStream } = require('stream/web'); +const { ReadableStream } = require('node:stream/web'); const stream = new ReadableStream(); @@ -251,7 +251,7 @@ for await (const chunk of transformedStream) const { ReadableStream, TransformStream, -} = require('stream/web'); +} = require('node:stream/web'); const stream = new ReadableStream({ start(controller) { @@ -342,7 +342,7 @@ The {ReadableStream} object supports the async iterator protocol using `for await` syntax. ```mjs -import { Buffer } from 'buffer'; +import { Buffer } from 'node:buffer'; const stream = new ReadableStream(getSomeSource()); @@ -577,7 +577,7 @@ available. Do not pass a pooled {Buffer} object instance in to this method. Pooled `Buffer` objects are created using `Buffer.allocUnsafe()`, -or `Buffer.from()`, or are often returned by various `fs` module +or `Buffer.from()`, or are often returned by various `node:fs` module callbacks. These types of `Buffer`s use a shared underlying {ArrayBuffer} object that contains all of the data from all of the pooled `Buffer` instances. When a `Buffer`, {TypedArray}, @@ -1445,7 +1445,7 @@ const { buffer, json, text, -} = require('stream/consumers'); +} = require('node:stream/consumers'); ``` #### `streamConsumers.arrayBuffer(stream)` diff --git a/doc/api/worker_threads.md b/doc/api/worker_threads.md index 58e9003ccfe95f..bbb35aa3ca5410 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!' }); @@ -367,7 +367,7 @@ const { isMainThread, BroadcastChannel, Worker -} = require('worker_threads'); +} = require('node:worker_threads'); const bc = new BroadcastChannel('hello'); @@ -462,7 +462,7 @@ yields an object with `port1` and `port2` properties, which refer to linked [`MessagePort`][] instances. ```js -const { MessageChannel } = require('worker_threads'); +const { MessageChannel } = require('node:worker_threads'); const { port1, port2 } = new MessageChannel(); port1.on('message', (message) => console.log('received', message)); @@ -501,7 +501,7 @@ The `'close'` event is emitted once either side of the channel has been disconnected. ```js -const { MessageChannel } = require('worker_threads'); +const { MessageChannel } = require('node:worker_threads'); const { port1, port2 } = new MessageChannel(); // Prints: @@ -618,7 +618,7 @@ In particular, the significant differences to `JSON` are: * {X509Certificate}s. ```js -const { MessageChannel } = require('worker_threads'); +const { MessageChannel } = require('node:worker_threads'); const { port1, port2 } = new MessageChannel(); port1.on('message', (message) => console.log(message)); @@ -643,7 +643,7 @@ from either thread. They cannot be listed in `transferList`. `transferList`; in that case, the underlying memory is copied rather than moved. ```js -const { MessageChannel } = require('worker_threads'); +const { MessageChannel } = require('node:worker_threads'); const { port1, port2 } = new MessageChannel(); port1.on('message', (message) => console.log(message)); @@ -670,7 +670,7 @@ The message object is cloned immediately, and can be modified after posting without having side effects. For more information on the serialization and deserialization mechanisms -behind this API, see the [serialization API of the `v8` module][v8.serdes]. +behind this API, see the [serialization API of the `node:v8` module][v8.serdes]. #### Considerations when transferring TypedArrays and Buffers @@ -822,8 +822,8 @@ Notable differences inside a Worker environment are: * The [`process.stdin`][], [`process.stdout`][] and [`process.stderr`][] may be redirected by the parent thread. -* The [`require('worker_threads').isMainThread`][] property is set to `false`. -* The [`require('worker_threads').parentPort`][] message port is available. +* The [`require('node:worker_threads').isMainThread`][] property is set to `false`. +* The [`require('node:worker_threads').parentPort`][] message port is available. * [`process.exit()`][] does not stop the whole program, just the single thread, and [`process.abort()`][] is not available. * [`process.chdir()`][] and `process` methods that set group or user ids @@ -844,11 +844,11 @@ Notable differences inside a Worker environment are: Creating `Worker` instances inside of other `Worker`s is possible. -Like [Web Workers][] and the [`cluster` module][], two-way communication can be -achieved through inter-thread message passing. Internally, a `Worker` has a -built-in pair of [`MessagePort`][]s that are already associated with each other -when the `Worker` is created. While the `MessagePort` object on the parent side -is not directly exposed, its functionalities are exposed through +Like [Web Workers][] and the [`node:cluster` module][], two-way communication +can be achieved through inter-thread message passing. Internally, a `Worker` has +a built-in pair of [`MessagePort`][]s that are already associated with each +other when the `Worker` is created. While the `MessagePort` object on the parent +side is not directly exposed, its functionalities are exposed through [`worker.postMessage()`][] and the [`worker.on('message')`][] event on the `Worker` object for the parent thread. @@ -863,10 +863,10 @@ and what kind of JavaScript values can be successfully transported through the thread barrier. ```js -const assert = require('assert'); +const assert = require('node:assert'); const { Worker, MessageChannel, MessagePort, isMainThread, parentPort -} = require('worker_threads'); +} = require('node:worker_threads'); if (isMainThread) { const worker = new Worker(__filename); const subChannel = new MessageChannel(); @@ -957,7 +957,7 @@ changes: * `stderr` {boolean} If this is set to `true`, then `worker.stderr` is not automatically piped through to `process.stderr` in the parent. * `workerData` {any} Any JavaScript value that is cloned and made - available as [`require('worker_threads').workerData`][]. The cloning + available as [`require('node:worker_threads').workerData`][]. The cloning occurs as described in the [HTML structured clone algorithm][], and an error is thrown if the object cannot be cloned (e.g. because it contains `function`s). @@ -1019,7 +1019,7 @@ added: v10.5.0 * `value` {any} The transmitted value The `'message'` event is emitted when the worker thread has invoked -[`require('worker_threads').parentPort.postMessage()`][]. +[`require('node:worker_threads').parentPort.postMessage()`][]. See the [`port.on('message')`][] event for more details. All messages sent from the worker thread are emitted before the @@ -1107,7 +1107,7 @@ lifetime never accumulates any `idle` time, but is still be able to process messages. ```js -const { Worker, isMainThread, parentPort } = require('worker_threads'); +const { Worker, isMainThread, parentPort } = require('node:worker_threads'); if (isMainThread) { const worker = new Worker(__filename); @@ -1141,7 +1141,7 @@ added: v10.5.0 * `transferList` {Object\[]} Send a message to the worker that is received via -[`require('worker_threads').parentPort.on('message')`][]. +[`require('node:worker_threads').parentPort.on('message')`][]. See [`port.postMessage()`][] for more details. ### `worker.ref()` @@ -1241,7 +1241,7 @@ added: v10.5.0 * {integer} An integer identifier for the referenced thread. Inside the worker thread, -it is available as [`require('worker_threads').threadId`][]. +it is available as [`require('node:worker_threads').threadId`][]. This value is unique for each `Worker` instance inside a single process. ### `worker.unref()` @@ -1286,7 +1286,7 @@ if (isMainThread) { const { Worker, isMainThread, -} = require('worker_threads'); +} = require('node:worker_threads'); if (isMainThread) { new Worker(__filename); @@ -1330,11 +1330,11 @@ thread spawned will spawn another until the application crashes. [`WebAssembly.Module`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/Module [`Worker constructor options`]: #new-workerfilename-options [`Worker`]: #class-worker -[`cluster` module]: cluster.md [`data:` URL]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URIs [`fs.close()`]: fs.md#fsclosefd-callback [`fs.open()`]: fs.md#fsopenpath-flags-mode-callback [`markAsUntransferable()`]: #workermarkasuntransferableobject +[`node:cluster` module]: cluster.md [`perf_hooks.performance`]: perf_hooks.md#perf_hooksperformance [`perf_hooks` `eventLoopUtilization()`]: perf_hooks.md#performanceeventlooputilizationutilization1-utilization2 [`port.on('message')`]: #event-message @@ -1349,12 +1349,12 @@ thread spawned will spawn another until the application crashes. [`process.stdin`]: process.md#processstdin [`process.stdout`]: process.md#processstdout [`process.title`]: process.md#processtitle -[`require('worker_threads').isMainThread`]: #workerismainthread -[`require('worker_threads').parentPort.on('message')`]: #event-message -[`require('worker_threads').parentPort.postMessage()`]: #workerpostmessagevalue-transferlist -[`require('worker_threads').parentPort`]: #workerparentport -[`require('worker_threads').threadId`]: #workerthreadid -[`require('worker_threads').workerData`]: #workerworkerdata +[`require('node:worker_threads').isMainThread`]: #workerismainthread +[`require('node:worker_threads').parentPort.on('message')`]: #event-message +[`require('node:worker_threads').parentPort.postMessage()`]: #workerpostmessagevalue-transferlist +[`require('node:worker_threads').parentPort`]: #workerparentport +[`require('node:worker_threads').threadId`]: #workerthreadid +[`require('node:worker_threads').workerData`]: #workerworkerdata [`trace_events`]: tracing.md [`v8.getHeapSnapshot()`]: v8.md#v8getheapsnapshot [`vm`]: vm.md diff --git a/doc/api/zlib.md b/doc/api/zlib.md index 0b1a7cc7ca47ba..ee54973e5d366a 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 a5c52eafb8a3d7..e61b5ea898c7de 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 9884408af8553a..6241cb68c9624f 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 8ebc3003da3150..0b961979d2aae1 100644 --- a/src/crypto/README.md +++ b/src/crypto/README.md @@ -312,12 +312,12 @@ crypto.randomFill(buf, (err, buf) => { For the legacy Node.js crypto API, asynchronous single-call operations use the traditional Node.js callback pattern, as illustrated in the previous `randomFill()` example. In the -Web Crypto API (accessible via `require('crypto').webcrypto`), +Web Crypto API (accessible via `require('node:crypto').webcrypto`), all asynchronous single-call operations are Promise-based. ```js // Example Web Crypto API asynchronous single-call operation -const { subtle } = require('crypto').webcrypto; +const { subtle } = require('node:crypto').webcrypto; subtle.generateKeys({ name: 'HMAC', length: 256 }, true, ['sign']) .then((key) => { diff --git a/test/common/README.md b/test/common/README.md index af29f2e1bf19f6..136f4b68d518ae 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'] }); ```