From a4fec8917825f1d0b10b1feb7f131750eb310712 Mon Sep 17 00:00:00 2001 From: "Jerome T.K. Covington" Date: Sun, 9 May 2021 14:25:18 -0400 Subject: [PATCH 1/4] doc: use node protocol in ESM examples --- doc/api/assert.md | 78 +++++++++++------------ doc/api/crypto.md | 18 +++--- doc/api/esm.md | 28 ++++---- doc/api/fs.md | 152 ++++++++++++++++++++++---------------------- doc/api/module.md | 6 +- doc/api/packages.md | 4 +- doc/api/timers.md | 8 +-- doc/api/vm.md | 6 +- doc/api/wasi.md | 4 +- 9 files changed, 152 insertions(+), 152 deletions(-) diff --git a/doc/api/assert.md b/doc/api/assert.md index 7eb952ace7be71..887f3e92a02a99 100644 --- a/doc/api/assert.md +++ b/doc/api/assert.md @@ -41,7 +41,7 @@ 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 @@ -49,7 +49,7 @@ const assert = require('assert').strict; ``` ```mjs -import assert from 'assert/strict'; +import assert from 'node:assert/strict'; ``` ```cjs @@ -59,7 +59,7 @@ const assert = require('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: @@ -113,7 +113,7 @@ Legacy assertion mode uses the [Abstract Equality Comparison][] in: To use legacy assertion mode: ```mjs -import assert from 'assert'; +import assert from 'node:assert'; ``` ```cjs @@ -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({ @@ -239,7 +239,7 @@ 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 assert from 'node:assert'; const tracker = new assert.CallTracker(); @@ -293,7 +293,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(); @@ -339,7 +339,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(); @@ -406,7 +406,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(); @@ -533,7 +533,7 @@ primitives are considered equal by the [Abstract Equality Comparison][] ( `==` ). ```mjs -import assert from 'assert'; +import assert from 'node:assert'; // WARNING: This does not throw an AssertionError! assert.deepEqual('+00000000', false); @@ -550,7 +550,7 @@ assert.deepEqual('+00000000', false); are evaluated also: ```mjs -import assert from 'assert'; +import assert from 'node:assert'; const obj1 = { a: { @@ -686,7 +686,7 @@ are recursively evaluated also by the following rules. below for further details. ```mjs -import assert from 'assert/strict'; +import assert from 'node:assert/strict'; // This fails because 1 !== '1'. deepStrictEqual({ a: 1 }, { a: '1' }); @@ -893,7 +893,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 ... @@ -957,7 +957,7 @@ Besides the async nature to await the completion behaves identically to ```mjs -import assert from 'assert/strict'; +import assert from 'node:assert/strict'; await assert.doesNotReject( async () => { @@ -982,7 +982,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(() => { @@ -1041,7 +1041,7 @@ matching error type in the assertion: ```mjs -import assert from 'assert/strict'; +import assert from 'node:assert/strict'; assert.doesNotThrow( () => { @@ -1068,7 +1068,7 @@ However, the following will result in an [`AssertionError`][] with the message ```mjs -import assert from 'assert/strict'; +import assert from 'node:assert/strict'; assert.doesNotThrow( () => { @@ -1096,7 +1096,7 @@ message: ```mjs -import assert from 'assert/strict'; +import assert from 'node:assert/strict'; assert.doesNotThrow( () => { @@ -1153,7 +1153,7 @@ using the [Abstract Equality Comparison][] ( `==` ). `NaN` is special handled and treated as being identical in case both sides are `NaN`. ```mjs -import assert from 'assert'; +import assert from 'node:assert'; assert.equal(1, 1); // OK, 1 == 1 @@ -1202,7 +1202,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 @@ -1259,7 +1259,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' @@ -1302,7 +1302,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); @@ -1349,7 +1349,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 @@ -1418,7 +1418,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 ... @@ -1500,7 +1500,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: { @@ -1611,7 +1611,7 @@ 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 @@ -1661,7 +1661,7 @@ Tests shallow, coercive inequality with the [Abstract Equality Comparison][] sides are `NaN`. ```mjs -import assert from 'assert'; +import assert from 'node:assert'; assert.notEqual(1, 2); // OK @@ -1709,7 +1709,7 @@ Tests strict inequality between the `actual` and `expected` parameters as determined by the [SameValue Comparison][]. ```mjs -import assert from 'assert/strict'; +import assert from 'node:assert/strict'; assert.notStrictEqual(1, 2); // OK @@ -1772,7 +1772,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 @@ -1842,7 +1842,7 @@ assert.ok(0); ``` ```mjs -import assert from 'assert/strict'; +import assert from 'node:assert/strict'; // Using `assert()` works the same: assert(0); @@ -1892,7 +1892,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 () => { @@ -1922,7 +1922,7 @@ const assert = require('assert/strict'); ``` ```mjs -import assert from 'assert/strict'; +import assert from 'node:assert/strict'; await assert.rejects( async () => { @@ -1954,7 +1954,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')), @@ -1998,7 +1998,7 @@ Tests strict equality between the `actual` and `expected` parameters as determined by the [SameValue Comparison][]. ```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: @@ -2095,7 +2095,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; @@ -2235,7 +2235,7 @@ throws( Validate instanceof using constructor: ```mjs -import assert from 'assert/strict'; +import assert from 'node:assert/strict'; assert.throws( () => { @@ -2262,7 +2262,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( () => { @@ -2289,7 +2289,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( () => { @@ -2339,7 +2339,7 @@ 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'); diff --git a/doc/api/crypto.md b/doc/api/crypto.md index e9a2be8f26ef90..5bea45274b2335 100644 --- a/doc/api/crypto.md +++ b/doc/api/crypto.md @@ -10,7 +10,7 @@ The `crypto` module provides cryptographic functionality that includes a set of wrappers for OpenSSL's hash, HMAC, cipher, decipher, sign, and verify functions. ```mjs -import { createHmac } from 'crypto'; +import { createHmac } from 'node:crypto'; const secret = 'abcdefg'; const hash = createHmac('sha256', secret) @@ -376,11 +376,11 @@ Example: Using `Cipher` and piped streams: import { createReadStream, createWriteStream, -} from 'fs'; +} from 'node:fs'; import { pipeline -} from 'stream'; +} from 'node:stream'; const { scrypt, @@ -701,7 +701,7 @@ Example: Using `Decipher` and piped streams: import { createReadStream, createWriteStream, -} from 'fs'; +} from 'node:fs'; const { scryptSync, @@ -939,7 +939,7 @@ 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, @@ -1156,7 +1156,7 @@ 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, @@ -1735,7 +1735,7 @@ hmac.end(); Example: Using `Hmac` and piped streams: ```mjs -import { createReadStream } from 'fs'; +import { createReadStream } from 'node:fs'; const { createHmac, @@ -3027,7 +3027,7 @@ Example: generating the sha256 sum of a file ```mjs import { createReadStream -} from 'fs'; +} from 'node:fs'; const { createHash, @@ -3113,7 +3113,7 @@ Example: generating the sha256 HMAC of a file ```mjs import { createReadStream -} from 'fs'; +} from 'node:fs'; const { createHmac, diff --git a/doc/api/esm.md b/doc/api/esm.md index 32168c29dd0faf..a8b044b6b28c1d 100644 --- a/doc/api/esm.md +++ b/doc/api/esm.md @@ -113,7 +113,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: @@ -229,12 +229,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); @@ -245,8 +245,8 @@ readFile('./foo.txt', (err, source) => { ``` ```js -import fs, { readFileSync } from 'fs'; -import { syncBuiltinESMExports } from 'module'; +import fs, { readFileSync } from 'node:fs'; +import { syncBuiltinESMExports } from 'node:module'; fs.readFileSync = () => Buffer.from('Hello, ESM'); syncBuiltinESMExports(); @@ -276,7 +276,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)); ``` @@ -350,11 +350,11 @@ module default import or its corresponding sugar syntax: ```js -import { default as cjs } from 'cjs'; +import { default as cjs } from 'node:cjs'; // The following import statement is "syntax sugar" (equivalent but sweeter) // for `{ default as cjsSugar }` in the above import statement: -import cjsSugar from 'cjs'; +import cjsSugar from 'node:cjs'; console.log(cjs); console.log(cjs === cjsSugar); @@ -368,11 +368,11 @@ a namespace with a `default` export key pointing to the CommonJS `module.exports` value. This Module Namespace Exotic Object can be directly observed either when using -`import * as m from 'cjs'` or a dynamic import: +`import * as m from 'node:cjs'` or a dynamic import: ```js -import * as m from 'cjs'; +import * as m from 'node:cjs'; console.log(m); console.log(m === await import('cjs')); // Prints: @@ -449,7 +449,7 @@ Local JSON files can be loaded relative to `import.meta.url` with `fs` directly: ```js -import { readFile } from 'fs/promises'; +import { readFile } from 'node:fs/promises'; const json = JSON.parse(await readFile(new URL('./dat.json', import.meta.url))); ``` @@ -842,7 +842,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; @@ -919,7 +919,7 @@ purposes. ```js // coffeescript-loader.mjs -import { URL, pathToFileURL } from 'url'; +import { URL, pathToFileURL } from 'node:url'; import CoffeeScript from 'coffeescript'; const baseURL = pathToFileURL(`${process.cwd()}/`).href; @@ -975,7 +975,7 @@ export function transformSource(source, context, defaultTransformSource) { 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/fs.md b/doc/api/fs.md index f4d1c555ff890e..58af0fed472091 100644 --- a/doc/api/fs.md +++ b/doc/api/fs.md @@ -15,7 +15,7 @@ To use the promise-based APIs: ```mjs // Using ESM Module syntax: -import * as fs from 'fs/promises'; +import * as fs from 'node:fs/promises'; ``` ```cjs @@ -27,7 +27,7 @@ To use the callback and sync APIs: ```mjs // Using ESM Module syntax: -import * as fs from 'fs'; +import * as fs from 'node:fs'; ``` ```cjs @@ -45,7 +45,7 @@ asynchronous operation is complete. ```mjs // Using ESM Module syntax: -import { unlink } from 'fs/promises'; +import { unlink } from 'node:fs/promises'; try { await unlink('/tmp/hello'); @@ -79,7 +79,7 @@ the first argument is `null` or `undefined`. ```mjs // Using ESM syntax -import { unlink } from 'fs'; +import { unlink } from 'node:fs'; unlink('/tmp/hello', (err) => { if (err) throw err; @@ -109,7 +109,7 @@ and can be handled using `try…catch`, or can be allowed to bubble up. ```mjs // Using ESM syntax -import { unlinkSync } from 'fs'; +import { unlinkSync } from 'node:fs'; try { unlinkSync('/tmp/hello'); @@ -230,7 +230,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 { @@ -395,7 +395,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 { @@ -585,8 +585,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); @@ -681,8 +681,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'); @@ -820,7 +820,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-')); @@ -891,7 +891,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('./'); @@ -932,7 +932,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); @@ -976,7 +976,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(); @@ -1312,7 +1312,7 @@ Cancelation is "best effort", and some amount of data is likely still to be written. ```mjs -import { writeFile } from 'fs/promises'; +import { writeFile } from 'node:fs/promises'; try { const controller = new AbortController(); @@ -1378,7 +1378,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'; @@ -1417,7 +1417,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) { @@ -1442,7 +1442,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) { @@ -1467,7 +1467,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') { @@ -1495,7 +1495,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) { @@ -1563,7 +1563,7 @@ Asynchronously append data to a file, creating the file if it does not yet exist. `data` can be a string or a {Buffer}. ```mjs -import { appendFile } from 'fs'; +import { appendFile } from 'node:fs'; appendFile('message.txt', 'data to append', (err) => { if (err) throw err; @@ -1574,7 +1574,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); ``` @@ -1584,7 +1584,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) => { @@ -1636,7 +1636,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; @@ -1790,7 +1790,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; @@ -1886,7 +1886,7 @@ implementations for `open`, `read`, and `close`. When providing the `fs` option, overrides for `open`, `read`, and `close` are required. ```mjs -import { createReadStream } from 'fs'; +import { createReadStream } from 'node:fs'; // Create a stream from some character device. const stream = createReadStream('/dev/input/event0'); @@ -1914,7 +1914,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 }); ``` @@ -2019,7 +2019,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!'); @@ -2041,7 +2041,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) { @@ -2065,7 +2065,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') { @@ -2089,7 +2089,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) { @@ -2113,7 +2113,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) { @@ -2299,7 +2299,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) => { @@ -2548,7 +2548,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) => { @@ -2560,7 +2560,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:\'] @@ -2608,7 +2608,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; @@ -2624,8 +2624,8 @@ must end with a trailing platform-specific path separator (`require('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(); @@ -2640,7 +2640,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); @@ -2883,7 +2883,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; @@ -2899,7 +2899,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); ``` @@ -2910,7 +2910,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) => { @@ -2927,7 +2927,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; @@ -3160,7 +3160,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; @@ -3318,7 +3318,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']; @@ -3413,7 +3413,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', './example/mewtwo', callback); ``` @@ -3486,7 +3486,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; @@ -3677,7 +3677,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) { @@ -3724,7 +3724,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}`); @@ -3950,7 +3950,7 @@ The `encoding` option is ignored if `data` is a buffer. If `data` is a normal object, it must have an own `toString` function property. ```mjs -import { writeFile } from 'fs'; +import { writeFile } from 'node:fs'; const data = new Uint8Array(Buffer.from('Hello Node.js')); writeFile('message.txt', data, (err) => { @@ -3962,7 +3962,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); ``` @@ -3980,7 +3980,7 @@ Cancelation is "best effort", and some amount of data is likely still to be written. ```mjs -import { writeFile } from 'fs'; +import { writeFile } from 'node:fs'; const controller = new AbortController(); const { signal } = controller; @@ -4001,7 +4001,7 @@ When `file` is a file descriptor, the behavior is almost identical to directly calling `fs.write()` like: ```mjs -import { write } from 'fs'; +import { write } from 'node:fs'; write(fd, Buffer.from(data, options.encoding), callback); ``` @@ -4085,7 +4085,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); @@ -4118,7 +4118,7 @@ Synchronously append data to a file, creating the file if it does not yet exist. `data` can be a string or a {Buffer}. ```mjs -import { appendFileSync } from 'fs'; +import { appendFileSync } from 'node:fs'; try { appendFileSync('message.txt', 'data to append'); @@ -4131,7 +4131,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'); ``` @@ -4141,7 +4141,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; @@ -4241,7 +4241,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'); @@ -4274,7 +4274,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.'); @@ -4636,7 +4636,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(''); @@ -5126,7 +5126,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('./'); @@ -5378,7 +5378,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) { @@ -6027,7 +6027,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, @@ -6325,7 +6325,7 @@ of one before invoking the other: ```mjs // Using ESM syntax -import { rename, stat } from 'fs/promises'; +import { rename, stat } from 'node:fs/promises'; const from = '/tmp/hello'; const to = '/tmp/world'; @@ -6358,7 +6358,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; @@ -6395,7 +6395,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 { @@ -6409,7 +6409,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 { @@ -6428,7 +6428,7 @@ For most `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')); ``` @@ -6442,7 +6442,7 @@ On Windows, `file:` {URL}s with a host name convert to UNC paths, while `file:` without a host name nor a 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 @@ -6466,7 +6466,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 @@ -6483,7 +6483,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')); @@ -6501,7 +6501,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')); @@ -6521,7 +6521,7 @@ be relative or absolute: Example using an absolute path on POSIX: ```mjs -import { open } from 'fs/promises'; +import { open } from 'node:fs/promises'; let fd; try { @@ -6561,7 +6561,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) => { @@ -6595,7 +6595,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/module.md b/doc/api/module.md index 307d08360c4e8b..b377d74e1edadf 100644 --- a/doc/api/module.md +++ b/doc/api/module.md @@ -32,7 +32,7 @@ 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 @@ -52,7 +52,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. @@ -117,7 +117,7 @@ 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 diff --git a/doc/api/packages.md b/doc/api/packages.md index f91184208af43e..c18d6d5600f259 100644 --- a/doc/api/packages.md +++ b/doc/api/packages.md @@ -147,9 +147,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/timers.md b/doc/api/timers.md index 8f6144e9445478..4b3ec8d5e79e80 100644 --- a/doc/api/timers.md +++ b/doc/api/timers.md @@ -338,7 +338,7 @@ import { setTimeout, setImmediate, setInterval, -} from 'timers/promises'; +} from 'node:timers/promises'; ``` ```cjs @@ -367,7 +367,7 @@ added: v15.0.0 ```mjs import { setTimeout, -} from 'timers/promises'; +} from 'node:timers/promises'; const res = await setTimeout(100, 'result'); @@ -400,7 +400,7 @@ added: v15.0.0 ```mjs import { setImmediate, -} from 'timers/promises'; +} from 'node:timers/promises'; const res = await setImmediate('result'); @@ -438,7 +438,7 @@ Returns an async iterator that generates values in an interval of `delay` ms. ```mjs import { setInterval, -} from 'timers/promises'; +} from 'node:timers/promises'; const interval = 100; for await (const startTime of setInterval(interval, Date.now())) { diff --git a/doc/api/vm.md b/doc/api/vm.md index 8177a7b38556be..acb07299399440 100644 --- a/doc/api/vm.md +++ b/doc/api/vm.md @@ -409,7 +409,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, @@ -754,7 +754,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 }); @@ -900,7 +900,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); diff --git a/doc/api/wasi.md b/doc/api/wasi.md index d5213b9c9eb460..b246ad3aae7ffa 100644 --- a/doc/api/wasi.md +++ b/doc/api/wasi.md @@ -11,8 +11,8 @@ specification. WASI gives sandboxed WebAssembly applications access to the underlying operating system via a collection of POSIX-like functions. ```mjs -import fs from 'fs'; -import { WASI } from 'wasi'; +import fs from 'node:fs'; +import { WASI } from 'node:wasi'; const wasi = new WASI({ args: process.argv, From ebb4ff04251838bb15f4eacad3d1577c89347117 Mon Sep 17 00:00:00 2001 From: "Jerome T.K. Covington" Date: Sun, 9 May 2021 14:26:15 -0400 Subject: [PATCH 2/4] doc: use node protocol in CommonJS examples --- doc/api/assert.md | 78 +++++++++--------- doc/api/async_hooks.md | 48 +++++------ doc/api/buffer.md | 6 +- doc/api/child_process.md | 68 ++++++++-------- doc/api/cluster.md | 24 +++--- doc/api/console.md | 2 +- doc/api/crypto.md | 144 ++++++++++++++++----------------- doc/api/deprecations.md | 4 +- doc/api/dgram.md | 14 ++-- doc/api/diagnostics_channel.md | 16 ++-- doc/api/dns.md | 16 ++-- doc/api/domain.md | 16 ++-- doc/api/errors.md | 12 +-- doc/api/events.md | 34 ++++---- doc/api/fs.md | 16 ++-- doc/api/http.md | 26 +++--- doc/api/http2.md | 94 ++++++++++----------- doc/api/https.md | 18 ++--- doc/api/inspector.md | 10 +-- doc/api/module.md | 10 +-- doc/api/modules.md | 8 +- doc/api/net.md | 8 +- doc/api/os.md | 2 +- doc/api/path.md | 2 +- doc/api/perf_hooks.md | 28 +++---- doc/api/policy.md | 2 +- doc/api/process.md | 8 +- doc/api/punycode.md | 2 +- doc/api/querystring.md | 2 +- doc/api/readline.md | 24 +++--- doc/api/repl.md | 26 +++--- doc/api/stream.md | 120 +++++++++++++-------------- doc/api/string_decoder.md | 6 +- doc/api/synopsis.md | 2 +- doc/api/timers.md | 16 ++-- doc/api/tls.md | 10 +-- doc/api/tracing.md | 8 +- doc/api/tty.md | 2 +- doc/api/url.md | 24 +++--- doc/api/util.md | 86 ++++++++++---------- doc/api/v8.md | 10 +-- doc/api/vm.md | 34 ++++---- doc/api/wasi.md | 4 +- doc/api/webcrypto.md | 24 +++--- doc/api/worker_threads.md | 34 ++++---- doc/api/zlib.md | 38 ++++----- 46 files changed, 593 insertions(+), 593 deletions(-) diff --git a/doc/api/assert.md b/doc/api/assert.md index 887f3e92a02a99..9e7046c3b81a87 100644 --- a/doc/api/assert.md +++ b/doc/api/assert.md @@ -45,7 +45,7 @@ import { strict as assert } from 'node:assert'; ``` ```cjs -const assert = require('assert').strict; +const assert = require('node:assert').strict; ``` ```mjs @@ -53,7 +53,7 @@ import assert from 'node:assert/strict'; ``` ```cjs -const assert = require('assert/strict'); +const assert = require('node:assert/strict'); ``` Example error diff: @@ -78,7 +78,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: @@ -117,7 +117,7 @@ import assert from 'node:assert'; ``` ```cjs -const assert = require('assert'); +const assert = require('node:assert'); ``` Whenever possible, use the [strict assertion mode][] instead. Otherwise, the @@ -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({ @@ -258,7 +258,7 @@ process.on('exit', () => { ``` ```cjs -const assert = require('assert'); +const assert = require('node:assert'); const tracker = new assert.CallTracker(); @@ -306,7 +306,7 @@ const callsfunc = tracker.calls(func); ``` ```cjs -const assert = require('assert'); +const assert = require('node:assert'); // Creates call tracker. const tracker = new assert.CallTracker(); @@ -367,7 +367,7 @@ tracker.report(); ``` ```cjs -const assert = require('assert'); +const assert = require('node:assert'); // Creates call tracker. const tracker = new assert.CallTracker(); @@ -424,7 +424,7 @@ tracker.verify(); ``` ```cjs -const assert = require('assert'); +const assert = require('node:assert'); // Creates call tracker. const tracker = new assert.CallTracker(); @@ -540,7 +540,7 @@ 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); @@ -585,7 +585,7 @@ assert.deepEqual(obj1, obj4); ``` ```cjs -const assert = require('assert'); +const assert = require('node:assert'); const obj1 = { a: { @@ -778,7 +778,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' }); @@ -906,7 +906,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 ... @@ -968,7 +968,7 @@ await assert.doesNotReject( ``` ```cjs -const assert = require('assert/strict'); +const assert = require('node:assert/strict'); (async () => { await assert.doesNotReject( @@ -992,7 +992,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(() => { @@ -1053,7 +1053,7 @@ assert.doesNotThrow( ```cjs -const assert = require('assert/strict'); +const assert = require('node:assert/strict'); assert.doesNotThrow( () => { @@ -1080,7 +1080,7 @@ assert.doesNotThrow( ```cjs -const assert = require('assert/strict'); +const assert = require('node:assert/strict'); assert.doesNotThrow( () => { @@ -1110,7 +1110,7 @@ assert.doesNotThrow( ```cjs -const assert = require('assert/strict'); +const assert = require('node:assert/strict'); assert.doesNotThrow( () => { @@ -1169,7 +1169,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 @@ -1215,7 +1215,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 @@ -1278,7 +1278,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' @@ -1315,7 +1315,7 @@ suppressFrame(); ``` ```cjs -const assert = require('assert/strict'); +const assert = require('node:assert/strict'); function suppressFrame() { assert.fail('a', 'b', undefined, '!==', suppressFrame); @@ -1375,7 +1375,7 @@ let err; ``` ```cjs -const assert = require('assert/strict'); +const assert = require('node:assert/strict'); assert.ifError(null); // OK @@ -1431,7 +1431,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 ... @@ -1533,7 +1533,7 @@ assert.notDeepEqual(obj1, obj4); ``` ```cjs -const assert = require('assert'); +const assert = require('node:assert'); const obj1 = { a: { @@ -1618,7 +1618,7 @@ assert.notDeepStrictEqual({ a: 1 }, { a: '1' }); ``` ```cjs -const assert = require('assert/strict'); +const assert = require('node:assert/strict'); assert.notDeepStrictEqual({ a: 1 }, { a: '1' }); // OK @@ -1674,7 +1674,7 @@ assert.notEqual(1, '1'); ``` ```cjs -const assert = require('assert'); +const assert = require('node:assert'); assert.notEqual(1, 2); // OK @@ -1724,7 +1724,7 @@ assert.notStrictEqual(1, '1'); ``` ```cjs -const assert = require('assert/strict'); +const assert = require('node:assert/strict'); assert.notStrictEqual(1, 2); // OK @@ -1807,7 +1807,7 @@ assert.ok(0); ``` ```cjs -const assert = require('assert/strict'); +const assert = require('node:assert/strict'); assert.ok(true); // OK @@ -1852,7 +1852,7 @@ assert(0); ``` ```cjs -const assert = require('assert'); +const assert = require('node:assert'); // Using `assert()` works the same: assert(0); @@ -1906,7 +1906,7 @@ await assert.rejects( ``` ```cjs -const assert = require('assert/strict'); +const assert = require('node:assert/strict'); (async () => { await assert.rejects( @@ -1937,7 +1937,7 @@ await assert.rejects( ``` ```cjs -const assert = require('assert/strict'); +const assert = require('node:assert/strict'); (async () => { await assert.rejects( @@ -1965,7 +1965,7 @@ assert.rejects( ``` ```cjs -const assert = require('assert/strict'); +const assert = require('node:assert/strict'); assert.rejects( Promise.reject(new Error('Wrong value')), @@ -2026,7 +2026,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: @@ -2164,7 +2164,7 @@ throws( ``` ```cjs -const assert = require('assert/strict'); +const assert = require('node:assert/strict'); const err = new TypeError('Wrong value'); err.code = 404; @@ -2246,7 +2246,7 @@ assert.throws( ``` ```cjs -const assert = require('assert/strict'); +const assert = require('node:assert/strict'); assert.throws( () => { @@ -2273,7 +2273,7 @@ assert.throws( ``` ```cjs -const assert = require('assert/strict'); +const assert = require('node:assert/strict'); assert.throws( () => { @@ -2310,7 +2310,7 @@ assert.throws( ``` ```cjs -const assert = require('assert/strict'); +const assert = require('node:assert/strict'); assert.throws( () => { @@ -2376,7 +2376,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_hooks.md b/doc/api/async_hooks.md index 55cc0542561334..be59b4727abac6 100644 --- a/doc/api/async_hooks.md +++ b/doc/api/async_hooks.md @@ -10,7 +10,7 @@ The `async_hooks` module provides an API to track asynchronous resources. It can be accessed using: ```js -const async_hooks = require('async_hooks'); +const async_hooks = require('node:async_hooks'); ``` ## Terminology @@ -30,7 +30,7 @@ interface, and each thread will use a new set of async IDs. Following is a simple overview of the public API. ```js -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(); @@ -103,7 +103,7 @@ specifics of all functions that can be passed to `callbacks` is in the [Hook Callbacks][] section. ```js -const async_hooks = require('async_hooks'); +const async_hooks = require('node:async_hooks'); const asyncHook = async_hooks.createHook({ init(asyncId, type, triggerAsyncId, resource) { }, @@ -159,8 +159,8 @@ This will print to the file and will not invoke AsyncHooks recursively because it is synchronous. ```js -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 AsyncHooks callback @@ -190,7 +190,7 @@ The `AsyncHook` instance is disabled by default. If the `AsyncHook` instance should be enabled immediately after creation, the following pattern can be used. ```js -const async_hooks = require('async_hooks'); +const async_hooks = require('node:async_hooks'); const hook = async_hooks.createHook(callbacks).enable(); ``` @@ -507,8 +507,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. ```js -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) => { @@ -520,12 +520,12 @@ This can be used to implement continuation local storage without the use of a tracking `Map` to store the metadata: ```js -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({ @@ -559,7 +559,7 @@ changes: track when something calls. ```js -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) => { @@ -617,7 +617,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. ```js -const ah = require('async_hooks'); +const ah = require('node:async_hooks'); Promise.resolve(1729).then(() => { console.log(`eid ${ah.executionAsyncId()} tid ${ah.triggerAsyncId()}`); }); @@ -634,7 +634,7 @@ Installing async hooks via `async_hooks.createHook` enables promise execution tracking: ```js -const ah = require('async_hooks'); +const ah = require('node:async_hooks'); ah.createHook({ init() {} }).enable(); // forces PromiseHooks to be enabled. Promise.resolve(1729).then(() => { console.log(`eid ${ah.executionAsyncId()} tid ${ah.triggerAsyncId()}`); @@ -673,7 +673,7 @@ The `init` hook will trigger when an `AsyncResource` is instantiated. The following is an overview of the `AsyncResource` API. ```js -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 @@ -820,7 +820,7 @@ Assuming that the task is adding two numbers, using a file named `task_processor.js` with the following content: ```js -const { parentPort } = require('worker_threads'); +const { parentPort } = require('node:worker_threads'); parentPort.on('message', (task) => { parentPort.postMessage(task.a + task.b); }); @@ -829,10 +829,10 @@ parentPort.on('message', (task) => { a Worker pool around it could use the following structure: ```js -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'); @@ -928,7 +928,7 @@ This pool could be used as follows: ```js const WorkerPool = require('./worker_pool.js'); -const os = require('os'); +const os = require('node:os'); const pool = new WorkerPool(os.cpus().length); @@ -953,8 +953,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. ```js -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(() => { @@ -989,8 +989,8 @@ that assigns IDs to incoming HTTP requests and includes them in messages logged within each request. ```js -const http = require('http'); -const { AsyncLocalStorage } = require('async_hooks'); +const http = require('node:http'); +const { AsyncLocalStorage } = require('node:async_hooks'); const asyncLocalStorage = new AsyncLocalStorage(); diff --git a/doc/api/buffer.md b/doc/api/buffer.md index dd965bbf226194..9ffa7852897516 100644 --- a/doc/api/buffer.md +++ b/doc/api/buffer.md @@ -379,9 +379,9 @@ contained by the `Blob` is copied only when the `arrayBuffer()` or `text()` methods are called. ```js -const { Blob } = require('buffer'); +const { Blob } = require('node:buffer'); const blob = new Blob(['hello there']); -const { setTimeout: delay } = require('timers/promises'); +const { setTimeout: delay } = require('node:timers/promises'); const mc1 = new MessageChannel(); const mc2 = new MessageChannel(); @@ -3383,7 +3383,7 @@ The transcoding process will use substitution characters if a given byte sequence cannot be adequately represented in the target encoding. For instance: ```js -const buffer = require('buffer'); +const buffer = require('node:buffer'); const newBuf = buffer.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 2ac6f1c35c41b3..9bc3c6ca943954 100644 --- a/doc/api/child_process.md +++ b/doc/api/child_process.md @@ -11,7 +11,7 @@ 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) => { @@ -107,7 +107,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) => { @@ -125,7 +125,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); @@ -188,7 +188,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 @@ -216,7 +216,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}`); @@ -242,7 +242,7 @@ 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 util = require('node:util'); const exec = util.promisify(require('child_process').exec); async function lsExample() { @@ -258,7 +258,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) => { @@ -321,7 +321,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; @@ -345,7 +345,7 @@ 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 util = require('node:util'); const execFile = util.promisify(require('child_process').execFile); async function getVersion() { const { stdout } = await execFile('node', ['--version']); @@ -363,7 +363,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) => { @@ -472,7 +472,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 }); @@ -581,7 +581,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) => { @@ -600,7 +600,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']); @@ -637,7 +637,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) => { @@ -658,7 +658,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 }); @@ -700,7 +700,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, @@ -713,8 +713,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'); @@ -802,7 +802,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' }); @@ -1078,7 +1078,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) => { @@ -1264,7 +1264,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) => { @@ -1298,7 +1298,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', @@ -1341,7 +1341,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}`); @@ -1358,7 +1358,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, @@ -1407,7 +1407,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) => { @@ -1465,10 +1465,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'); }); @@ -1505,13 +1505,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... @@ -1633,9 +1633,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: [ @@ -1674,7 +1674,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'); @@ -1699,7 +1699,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, diff --git a/doc/api/cluster.md b/doc/api/cluster.md index d12c1f12d256d8..4d3963ed8fe4e7 100644 --- a/doc/api/cluster.md +++ b/doc/api/cluster.md @@ -14,9 +14,9 @@ The cluster module allows easy creation of child processes that all share server ports. ```js -const cluster = require('cluster'); -const http = require('http'); -const numCPUs = require('os').cpus().length; +const cluster = require('node:cluster'); +const http = require('node:http'); +const numCPUs = require('node:os').cpus().length; if (cluster.isPrimary) { console.log(`Primary ${process.pid} is running`); @@ -205,8 +205,8 @@ 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: ```js -const cluster = require('cluster'); -const http = require('http'); +const cluster = require('node:cluster'); +const http = require('node:http'); if (cluster.isPrimary) { @@ -224,7 +224,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(); } @@ -316,7 +316,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 }); @@ -388,9 +388,9 @@ This function returns `true` if the worker's process has terminated (either because of exiting or being signaled). Otherwise, it returns `false`. ```js -const cluster = require('cluster'); -const http = require('http'); -const numCPUs = require('os').cpus().length; +const cluster = require('node:cluster'); +const http = require('node:http'); +const numCPUs = require('node:os').cpus().length; if (cluster.isPrimary) { console.log(`Primary ${process.pid} is running`); @@ -818,7 +818,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. ```js -const cluster = require('cluster'); +const cluster = require('node:cluster'); cluster.setupPrimary({ exec: 'worker.js', args: ['--use', 'https'], @@ -844,7 +844,7 @@ added: v0.7.0 A reference to the current worker object. Not available in the primary process. ```js -const cluster = require('cluster'); +const cluster = require('node:cluster'); if (cluster.isPrimary) { console.log('I am primary'); diff --git a/doc/api/console.md b/doc/api/console.md index 9f7581716340c3..89ed14bf6c33ad 100644 --- a/doc/api/console.md +++ b/doc/api/console.md @@ -80,7 +80,7 @@ output streams and can be accessed using either `require('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 5bea45274b2335..74ffa85c066c32 100644 --- a/doc/api/crypto.md +++ b/doc/api/crypto.md @@ -22,7 +22,7 @@ console.log(hash); ``` ```cjs -const crypto = require('crypto'); +const crypto = require('node:crypto'); const secret = 'abcdefg'; const hash = crypto.createHmac('sha256', secret) @@ -44,7 +44,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!'); } @@ -107,7 +107,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')); @@ -138,7 +138,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); @@ -169,7 +169,7 @@ console.log(Certificate.verifySpkac(Buffer.from(spkac))); ``` ```cjs -const { Certificate } = require('crypto'); +const { Certificate } = require('node:crypto'); const spkac = getSpkacSomehow(); console.log(Certificate.verifySpkac(Buffer.from(spkac))); // Prints: true or false @@ -195,7 +195,7 @@ const cert2 = Certificate(); ``` ```cjs -const { Certificate } = require('crypto'); +const { Certificate } = require('node:crypto'); const cert1 = new Certificate(); const cert2 = Certificate(); @@ -221,7 +221,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); @@ -249,7 +249,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); @@ -276,7 +276,7 @@ console.log(cert.verifySpkac(Buffer.from(spkac))); ``` ```cjs -const { Certificate } = require('crypto'); +const { Certificate } = require('node:crypto'); const cert = Certificate(); const spkac = getSpkacSomehow(); console.log(cert.verifySpkac(Buffer.from(spkac))); @@ -342,7 +342,7 @@ const { scrypt, randomFill, createCipheriv -} = require('crypto'); +} = require('node:crypto'); const algorithm = 'aes-192-cbc'; const password = 'Password used to generate key'; @@ -415,17 +415,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'; @@ -484,7 +484,7 @@ const { scrypt, randomFill, createCipheriv, -} = require('crypto'); +} = require('node:crypto'); const algorithm = 'aes-192-cbc'; const password = 'Password used to generate key'; @@ -664,7 +664,7 @@ decipher.end(); const { scryptSync, createDecipheriv, -} = require('crypto'); +} = require('node:crypto'); const algorithm = 'aes-192-cbc'; const password = 'Password used to generate key'; @@ -727,12 +727,12 @@ input.pipe(decipher).pipe(output); const { createReadStream, createWriteStream, -} = require('fs'); +} = require('node:fs'); const { scryptSync, createDecipheriv, -} = require('crypto'); +} = require('node:crypto'); const algorithm = 'aes-192-cbc'; const password = 'Password used to generate key'; @@ -779,7 +779,7 @@ console.log(decrypted); const { scryptSync, createDecipheriv, -} = require('crypto'); +} = require('node:crypto'); const algorithm = 'aes-192-cbc'; const password = 'Password used to generate key'; @@ -962,11 +962,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); @@ -1125,7 +1125,7 @@ const dh = createDiffieHellmanGroup('modp1'); ``` ```cjs -const { createDiffieHellmanGroup } = require('crypto'); +const { createDiffieHellmanGroup } = require('node:crypto'); const dh = createDiffieHellmanGroup('modp1'); ``` @@ -1179,11 +1179,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'); @@ -1256,7 +1256,7 @@ console.log(uncompressedKey === ecdh.getPublicKey('hex')); const { createECDH, ECDH, -} = require('crypto'); +} = require('node:crypto'); const ecdh = createECDH('secp256k1'); ecdh.generateKeys(); @@ -1428,7 +1428,7 @@ console.log(aliceSecret === bobSecret); const { createECDH, createHash, -} = require('crypto'); +} = require('node:crypto'); const alice = createECDH('secp256k1'); const bob = createECDH('secp256k1'); @@ -1496,7 +1496,7 @@ hash.end(); ```cjs const { createHash, -} = require('crypto'); +} = require('node:crypto'); const hash = createHash('sha256'); @@ -1520,7 +1520,7 @@ Example: Using `Hash` and piped streams: ```mjs const { createReadStream, -} = require('fs'); +} = require('node:fs'); const { createHash, @@ -1534,11 +1534,11 @@ input.pipe(hash).setEncoding('hex').pipe(process.stdout); ```cjs const { createReadStream, -} = require('fs'); +} = require('node:fs'); const { createHash, -} = require('crypto'); +} = require('node:crypto'); const hash = createHash('sha256'); @@ -1551,7 +1551,7 @@ Example: Using the [`hash.update()`][] and [`hash.digest()`][] methods: ```mjs const { createHash, -} = require('crypto'); +} = require('node:crypto'); const hash = createHash('sha256'); @@ -1564,7 +1564,7 @@ console.log(hash.digest('hex')); ```cjs const { createHash, -} = require('crypto'); +} = require('node:crypto'); const hash = createHash('sha256'); @@ -1596,7 +1596,7 @@ its [`hash.digest()`][] method has been called. // Calculate a rolling hash. const { createHash, -} = require('crypto'); +} = require('node:crypto'); const hash = createHash('sha256'); @@ -1616,7 +1616,7 @@ console.log(hash.copy().digest('hex')); // Calculate a rolling hash. const { createHash, -} = require('crypto'); +} = require('node:crypto'); const hash = createHash('sha256'); @@ -1691,7 +1691,7 @@ Example: Using `Hmac` objects as streams: ```mjs const { createHmac, -} = require('crypto'); +} = require('node:crypto'); const hmac = createHmac('sha256', 'a secret'); @@ -1713,7 +1713,7 @@ hmac.end(); ```cjs const { createHmac, -} = require('crypto'); +} = require('node:crypto'); const hmac = createHmac('sha256', 'a secret'); @@ -1750,11 +1750,11 @@ input.pipe(hmac).pipe(process.stdout); ```cjs const { createReadStream, -} = require('fs'); +} = require('node:fs'); const { createHmac, -} = require('crypto'); +} = require('node:crypto'); const hmac = createHmac('sha256', 'a secret'); @@ -1780,7 +1780,7 @@ console.log(hmac.digest('hex')); ```cjs const { createHmac, -} = require('crypto'); +} = require('node:crypto'); const hmac = createHmac('sha256', 'a secret'); @@ -1889,7 +1889,7 @@ const { subtle, }, KeyObject, -} = require('crypto'); +} = require('node:crypto'); (async function() { const key = await subtle.generateKey({ @@ -2084,7 +2084,7 @@ const { generateKeyPairSync, createSign, createVerify, -} = require('crypto'); +} = require('node:crypto'); const { privateKey, publicKey } = generateKeyPairSync('ec', { namedCurve: 'sect239k1' @@ -2132,7 +2132,7 @@ const { generateKeyPairSync, createSign, createVerify, -} = require('crypto'); +} = require('node:crypto'); const { privateKey, publicKey } = generateKeyPairSync('rsa', { modulusLength: 2048, @@ -2361,7 +2361,7 @@ console.log(x509.subject); ``` ```cjs -const { X509Certificate } = require('crypto'); +const { X509Certificate } = require('node:crypto'); const x509 = new X509Certificate('{... pem encoded cert ...}'); @@ -3053,11 +3053,11 @@ input.on('readable', () => { ```cjs const { createReadStream, -} = require('fs'); +} = require('node:fs'); const { createHash, -} = require('crypto'); +} = require('node:crypto'); const filename = process.argv[2]; @@ -3139,11 +3139,11 @@ input.on('readable', () => { ```cjs const { createReadStream, -} = require('fs'); +} = require('node:fs'); const { createHmac, -} = require('crypto'); +} = require('node:crypto'); const filename = process.argv[2]; @@ -3350,7 +3350,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; @@ -3433,7 +3433,7 @@ generateKeyPair('rsa', { ```cjs const { generateKeyPair, -} = require('crypto'); +} = require('node:crypto'); generateKeyPair('rsa', { modulusLength: 4096, @@ -3531,7 +3531,7 @@ const { ```cjs const { generateKeyPairSync, -} = require('crypto'); +} = require('node:crypto'); const { publicKey, @@ -3585,7 +3585,7 @@ console.log(key.export().toString('hex')); // e89..........41e ```cjs const { generateKeySync, -} = require('crypto'); +} = require('node:crypto'); const key = generateKeySync('hmac', 64); console.log(key.export().toString('hex')); // e89..........41e @@ -3721,7 +3721,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', ...] ``` @@ -3744,7 +3744,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', ...] ``` @@ -3790,7 +3790,7 @@ console.log(aliceSecret === bobSecret); ```cjs const { getDiffieHellman, -} = require('crypto'); +} = require('node:crypto'); const alice = getDiffieHellman('modp14'); const bob = getDiffieHellman('modp14'); @@ -3833,7 +3833,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', ...] ``` @@ -3881,7 +3881,7 @@ hkdf('sha512', 'key', 'salt', 'info', 64, (err, derivedKey) => { ```cjs const { hkdf, -} = require('crypto'); +} = require('node:crypto'); hkdf('sha512', 'key', 'salt', 'info', 64, (err, derivedKey) => { if (err) throw err; @@ -3928,7 +3928,7 @@ console.log(Buffer.from(derivedKey).toString('hex')); // '24156e2...5391653' ```cjs const { hkdfSync, -} = require('crypto'); +} = require('node:crypto'); const derivedKey = hkdfSync('sha512', 'key', 'salt', 'info', 64); console.log(Buffer.from(derivedKey).toString('hex')); // '24156e2...5391653' @@ -4006,7 +4006,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; @@ -4028,7 +4028,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; @@ -4101,7 +4101,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' @@ -4119,7 +4119,7 @@ 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' @@ -4342,7 +4342,7 @@ randomBytes(256, (err, buf) => { // Asynchronous const { randomBytes, -} = require('crypto'); +} = require('node:crypto'); randomBytes(256, (err, buf) => { if (err) throw err; @@ -4369,7 +4369,7 @@ console.log( // Synchronous const { randomBytes, -} = require('crypto'); +} = require('node:crypto'); const buf = randomBytes(256); console.log( @@ -4431,7 +4431,7 @@ console.log(buf.toString('hex')); ```cjs const { randomFillSync, -} = require('crypto'); +} = require('node:crypto'); const buf = Buffer.alloc(10); console.log(randomFillSync(buf).toString('hex')); @@ -4467,7 +4467,7 @@ console.log(Buffer.from(randomFillSync(c)).toString('hex')); ```cjs const { randomFillSync, -} = require('crypto'); +} = require('node:crypto'); const a = new Uint32Array(10); console.log(Buffer.from(randomFillSync(a).buffer, @@ -4531,7 +4531,7 @@ randomFill(buf, 5, 5, (err, buf) => { ```cjs const { randomFill, -} = require('crypto'); +} = require('node:crypto'); const buf = Buffer.alloc(10); randomFill(buf, (err, buf) => { @@ -4589,7 +4589,7 @@ randomFill(c, (err, buf) => { ```cjs const { randomFill, -} = require('crypto'); +} = require('node:crypto'); const a = new Uint32Array(10); randomFill(a, (err, buf) => { @@ -4657,7 +4657,7 @@ randomInt(3, (err, n) => { // Asynchronous const { randomInt, -} = require('crypto'); +} = require('node:crypto'); randomInt(3, (err, n) => { if (err) throw err; @@ -4679,7 +4679,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}`); @@ -4699,7 +4699,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}`); @@ -4796,7 +4796,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) => { @@ -4872,7 +4872,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); @@ -5262,7 +5262,7 @@ const { createCipheriv, createDecipheriv, randomBytes, -} = require('crypto'); +} = require('node:crypto'); const key = 'keykeykeykeykeykeykeykey'; const nonce = randomBytes(12); diff --git a/doc/api/deprecations.md b/doc/api/deprecations.md index 6ded89adeb2377..86693cec6391cb 100644 --- a/doc/api/deprecations.md +++ b/doc/api/deprecations.md @@ -1532,7 +1532,7 @@ Type: Runtime mistake. This function can usually be replaced with: ```js -const querystring = require('querystring'); +const querystring = require('node:querystring'); querystring.parse(str, '\n', '='); ``` @@ -2523,7 +2523,7 @@ Please ensure that all `fs.FileHandle` objects are explicitly closed using `FileHandle.prototype.close()` when the `fs.FileHandle` is no longer needed: ```js -const fsPromises = require('fs').promises; +const fsPromises = require('node:fs').promises; async function openAndClose() { let filehandle; try { diff --git a/doc/api/dgram.md b/doc/api/dgram.md index 8813f9bffaf384..e9f99d88898ccb 100644 --- a/doc/api/dgram.md +++ b/doc/api/dgram.md @@ -11,7 +11,7 @@ The `dgram` module provides an implementation of UDP datagram sockets. ```js -const dgram = require('dgram'); +const dgram = require('node:dgram'); const server = dgram.createSocket('udp4'); server.on('error', (err) => { @@ -124,8 +124,8 @@ When sharing a UDP socket across multiple `cluster` workers, the `EADDRINUSE` error will occur: ```js -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. cluster.fork(); // Fails with EADDRINUSE. @@ -206,7 +206,7 @@ attempting to bind with a closed socket), an [`Error`][] may be thrown. Example of a UDP server listening on port 41234: ```js -const dgram = require('dgram'); +const dgram = require('node:dgram'); const server = dgram.createSocket('udp4'); server.on('error', (err) => { @@ -481,7 +481,7 @@ This method throws [`ERR_SOCKET_BAD_PORT`][] if called on an unbound socket. Example of sending a UDP packet to a port on `localhost`; ```js -const dgram = require('dgram'); +const dgram = require('node:dgram'); const message = Buffer.from('Some bytes'); const client = dgram.createSocket('udp4'); client.send(message, 41234, 'localhost', (err) => { @@ -493,7 +493,7 @@ Example of sending a UDP packet composed of multiple buffers to a port on `127.0.0.1`; ```js -const dgram = require('dgram'); +const dgram = require('node:dgram'); const buf1 = Buffer.from('Some '); const buf2 = Buffer.from('bytes'); const client = dgram.createSocket('udp4'); @@ -511,7 +511,7 @@ Example of sending a UDP packet using a socket connected to a port on `localhost`: ```js -const dgram = require('dgram'); +const dgram = require('node:dgram'); const message = Buffer.from('Some bytes'); const client = dgram.createSocket('udp4'); client.connect(41234, 'localhost', (err) => { diff --git a/doc/api/diagnostics_channel.md b/doc/api/diagnostics_channel.md index 7a22b2f56eec1d..4b7ca718a7e531 100644 --- a/doc/api/diagnostics_channel.md +++ b/doc/api/diagnostics_channel.md @@ -12,7 +12,7 @@ to report arbitrary message data for diagnostics purposes. It can be accessed using: ```js -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 @@ -34,7 +34,7 @@ other modules. Following is a simple overview of the public API. ```js -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'); @@ -65,7 +65,7 @@ This API is optional but helpful when trying to publish messages from very performance-sensitive code. ```js -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 @@ -82,7 +82,7 @@ channel. It produces a channel object which is optimized to reduce overhead at publish time as much as possible. ```js -const diagnostics_channel = require('diagnostics_channel'); +const diagnostics_channel = require('node:diagnostics_channel'); const channel = diagnostics_channel.channel('my-channel'); ``` @@ -108,7 +108,7 @@ This API is optional but helpful when trying to publish messages from very performance-sensitive code. ```js -const diagnostics_channel = require('diagnostics_channel'); +const diagnostics_channel = require('node:diagnostics_channel'); const channel = diagnostics_channel.channel('my-channel'); @@ -125,7 +125,7 @@ Publish a message to any subscribers to the channel. This will trigger message handlers synchronously so they will execute within the same context. ```js -const diagnostics_channel = require('diagnostics_channel'); +const diagnostics_channel = require('node:diagnostics_channel'); const channel = diagnostics_channel.channel('my-channel'); @@ -145,7 +145,7 @@ will be run synchronously whenever a message is published to the channel. Any errors thrown in the message handler will trigger an [`'uncaughtException'`][]. ```js -const diagnostics_channel = require('diagnostics_channel'); +const diagnostics_channel = require('node:diagnostics_channel'); const channel = diagnostics_channel.channel('my-channel'); @@ -162,7 +162,7 @@ Remove a message handler previously registered to this channel with [`channel.subscribe(onMessage)`][]. ```js -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 a5a4432e2d9940..0f42ff874c904d 100644 --- a/doc/api/dns.md +++ b/doc/api/dns.md @@ -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); @@ -31,7 +31,7 @@ queries. These functions do not use the same set of configuration files used by 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; @@ -64,7 +64,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']); @@ -219,7 +219,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, @@ -282,7 +282,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 @@ -700,7 +700,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']); @@ -810,7 +810,7 @@ using `dnsPromises.lookup()`. Example usage: ```js -const dns = require('dns'); +const dns = require('node:dns'); const dnsPromises = dns.promises; const options = { family: 6, @@ -849,7 +849,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 000878ea70d9fa..5bbd3101fb5835 100644 --- a/doc/api/domain.md +++ b/doc/api/domain.md @@ -65,7 +65,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 @@ -87,7 +87,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) { @@ -116,12 +116,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}`); @@ -245,8 +245,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(() => { @@ -415,8 +415,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/errors.md b/doc/api/errors.md index f199689f2dc432..e3bd291c21b635 100644 --- a/doc/api/errors.md +++ b/doc/api/errors.md @@ -61,7 +61,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); @@ -75,7 +75,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: @@ -107,7 +107,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(() => { @@ -135,7 +135,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) { @@ -155,7 +155,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) => { @@ -2081,7 +2081,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'); diff --git a/doc/api/events.md b/doc/api/events.md index 540b663bd56968..46ad46d38e8387 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 {} @@ -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) => { @@ -211,7 +211,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) => { @@ -239,7 +239,7 @@ changes: The `EventEmitter` class is defined and exposed by the `events` module: ```js -const EventEmitter = require('events'); +const EventEmitter = require('node:events'); ``` All `EventEmitter`s emit the event `'newListener'` when new listeners are @@ -335,7 +335,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 @@ -378,7 +378,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', () => {}); @@ -737,7 +737,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() { @@ -829,7 +829,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(); @@ -872,7 +872,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(); @@ -905,7 +905,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(); @@ -921,7 +921,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(); @@ -954,7 +954,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(); @@ -981,7 +981,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(); @@ -1039,7 +1039,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', () => {}); @@ -1061,7 +1061,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(); @@ -1090,7 +1090,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 () => { @@ -1129,7 +1129,7 @@ added: v15.4.0 const { setMaxListeners, EventEmitter -} = require('events'); +} = require('node:events'); const target = new EventTarget(); const emitter = new EventEmitter(); diff --git a/doc/api/fs.md b/doc/api/fs.md index 58af0fed472091..c6d46486e1d3db 100644 --- a/doc/api/fs.md +++ b/doc/api/fs.md @@ -20,7 +20,7 @@ import * as fs from 'node:fs/promises'; ```cjs // Using CommonJS syntax: -const fs = require('fs/promises'); +const fs = require('node:fs/promises'); ``` To use the callback and sync APIs: @@ -32,7 +32,7 @@ import * as fs from 'node:fs'; ```cjs // Using CommonJS syntax: -const fs = require('fs'); +const fs = require('node:fs'); ``` All file system operations have synchronous, callback, and promise-based @@ -57,7 +57,7 @@ try { ```cjs // Using CommonJS syntax -const { unlink } = require('fs/promises'); +const { unlink } = require('node:fs/promises'); (async function(path) { try { @@ -89,7 +89,7 @@ unlink('/tmp/hello', (err) => { ```cjs // Using CommonJS syntax -const { unlink } = require('fs'); +const { unlink } = require('node:fs'); unlink('/tmp/hello', (err) => { if (err) throw err; @@ -121,7 +121,7 @@ try { ```cjs // Using CommonJS syntax -const { unlinkSync } = require('fs'); +const { unlinkSync } = require('node:fs'); try { unlinkSync('/tmp/hello'); @@ -1234,7 +1234,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; @@ -6341,7 +6341,7 @@ try { ```cjs // Using CommonJS syntax -const { rename, stat } = require('fs/promises'); +const { rename, stat } = require('node:fs/promises'); (async function(from, to) { try { @@ -6370,7 +6370,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; diff --git a/doc/api/http.md b/doc/api/http.md index 5ec542e9011575..d729c2e33ce0c0 100644 --- a/doc/api/http.md +++ b/doc/api/http.md @@ -184,7 +184,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); @@ -432,9 +432,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) => { @@ -515,7 +515,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', @@ -589,7 +589,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) => { @@ -864,7 +864,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 @@ -888,7 +888,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() { @@ -982,7 +982,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', }; @@ -1132,7 +1132,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(); @@ -1726,7 +1726,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; @@ -3093,7 +3093,7 @@ Examples: Example: ```js -const { validateHeaderName } = require('http'); +const { validateHeaderName } = require('node:http'); try { validateHeaderName(''); @@ -3125,7 +3125,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 83b80150ade554..af0ee7bee9b078 100644 --- a/doc/api/http2.md +++ b/doc/api/http2.md @@ -25,7 +25,7 @@ The `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'); ``` ## Core API @@ -48,8 +48,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'), @@ -81,8 +81,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') }); @@ -273,7 +273,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']; @@ -293,7 +293,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(); @@ -536,7 +536,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; @@ -672,7 +672,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) => { @@ -737,7 +737,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) => { @@ -764,7 +764,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); @@ -796,7 +796,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) => { @@ -819,7 +819,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) => { @@ -864,7 +864,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, @@ -1249,7 +1249,7 @@ added: v8.4.0 * `callback` {Function} ```js -const http2 = require('http2'); +const http2 = require('node:http2'); const client = http2.connect('http://example.org:8000'); const { NGHTTP2_CANCEL } = http2.constants; const req = client.request({ ':path': '/' }); @@ -1295,7 +1295,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 }); @@ -1372,7 +1372,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) => { @@ -1447,7 +1447,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 }); @@ -1486,7 +1486,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 }); @@ -1505,7 +1505,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 }); @@ -1552,8 +1552,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) => { @@ -1597,8 +1597,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) => { @@ -1663,7 +1663,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) { @@ -1698,7 +1698,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) { @@ -1733,7 +1733,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', @@ -1836,7 +1836,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, @@ -2034,7 +2034,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, @@ -2281,7 +2281,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 @@ -2418,8 +2418,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'), @@ -2545,7 +2545,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 */ @@ -2604,7 +2604,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 }); @@ -2674,7 +2674,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']); @@ -2805,7 +2805,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'); @@ -2827,7 +2827,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 = ''; @@ -2842,9 +2842,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) => { @@ -2872,7 +2872,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'); @@ -2906,7 +2906,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 }); ``` @@ -2916,7 +2916,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) { @@ -2939,7 +2939,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'); @@ -2968,8 +2968,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'); @@ -3605,7 +3605,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; @@ -3779,7 +3779,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 f4c1f0487a779a..ebb7d8dc4f0539 100644 --- a/doc/api/https.md +++ b/doc/api/https.md @@ -167,8 +167,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'), @@ -184,8 +184,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'), @@ -224,7 +224,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); @@ -294,7 +294,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', @@ -368,9 +368,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/inspector.md b/doc/api/inspector.md index c22dbca03bcbf1..8c3c5b354b06d4 100644 --- a/doc/api/inspector.md +++ b/doc/api/inspector.md @@ -11,7 +11,7 @@ The `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()` @@ -195,8 +195,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(); @@ -220,8 +220,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/module.md b/doc/api/module.md index b377d74e1edadf..eebaaac2955907 100644 --- a/doc/api/module.md +++ b/doc/api/module.md @@ -38,7 +38,7 @@ 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)` @@ -69,9 +69,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; @@ -123,7 +123,7 @@ 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 9bb3bf0c56b812..de1b3457c87c0e 100644 --- a/doc/api/modules.md +++ b/doc/api/modules.md @@ -636,7 +636,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` @@ -658,8 +658,8 @@ 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 }; @@ -807,7 +807,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 5066179046c8c1..83b2dab02775a6 100644 --- a/doc/api/net.md +++ b/doc/api/net.md @@ -14,7 +14,7 @@ TCP or [IPC][] servers ([`net.createServer()`][]) and clients It can be accessed using: ```js -const net = require('net'); +const net = require('node:net'); ``` ## IPC support @@ -811,7 +811,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: { @@ -1237,7 +1237,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!'); @@ -1340,7 +1340,7 @@ Here is an example of an 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 f3d3f2d65249a4..d8671bc198fb68 100644 --- a/doc/api/os.md +++ b/doc/api/os.md @@ -10,7 +10,7 @@ The `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/path.md b/doc/api/path.md index 839c45da906677..ba09397448cd49 100644 --- a/doc/api/path.md +++ b/doc/api/path.md @@ -10,7 +10,7 @@ The `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 diff --git a/doc/api/perf_hooks.md b/doc/api/perf_hooks.md index 80a3c46f36a281..9e7cab2c3c60a7 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); @@ -97,8 +97,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(); @@ -239,7 +239,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'); @@ -554,7 +554,7 @@ added: v8.5.0 const { performance, PerformanceObserver -} = require('perf_hooks'); +} = require('node:perf_hooks'); const obs = new PerformanceObserver((list, observer) => { console.log(list.getEntries()); @@ -606,7 +606,7 @@ or `options.type`: const { performance, PerformanceObserver -} = require('perf_hooks'); +} = require('node:perf_hooks'); const obs = new PerformanceObserver((list, observer) => { // Called three times synchronously. `list` contains one item. @@ -640,7 +640,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()); @@ -686,7 +686,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')); @@ -738,7 +738,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')); @@ -804,7 +804,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. @@ -955,11 +955,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({ @@ -1002,8 +1002,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 = diff --git a/doc/api/policy.md b/doc/api/policy.md index 6cca07f8ba59b2..75a922e6a933f0 100644 --- a/doc/api/policy.md +++ b/doc/api/policy.md @@ -183,7 +183,7 @@ the application. For example, log data about timing of function durations by wrapping the original: ```js -const original = require('fn'); +const original = require('node:fn'); module.exports = function fn(...args) { console.time(); try { diff --git a/doc/api/process.md b/doc/api/process.md index e0ab670747516b..a37bfbae70e949 100644 --- a/doc/api/process.md +++ b/doc/api/process.md @@ -11,7 +11,7 @@ Node.js applications without using `require()`. It can also be explicitly accessed using `require()`: ```js -const process = require('process'); +const process = require('node:process'); ``` ## Process events @@ -942,8 +942,8 @@ the call returns, by passing the `RTLD_NOW` constant. In this example the constant is assumed to be available. ```js -const os = require('os'); -const path = require('path'); +const os = require('node:os'); +const path = require('node:path'); const module = { exports: {} }; process.dlopen(module, path.join(__dirname, 'local.node'), os.constants.dlopen.RTLD_NOW); @@ -2027,7 +2027,7 @@ const data = process.report.getReport(); console.log(data.header.nodejsVersion); // Similar to process.report.writeReport() -const fs = require('fs'); +const fs = require('node:fs'); fs.writeFileSync(util.inspect(data), 'my-report.log', 'utf8'); ``` diff --git a/doc/api/punycode.md b/doc/api/punycode.md index c9c20ce6350c7e..12619e261b56d5 100644 --- a/doc/api/punycode.md +++ b/doc/api/punycode.md @@ -20,7 +20,7 @@ The `punycode` module is a bundled version of the [Punycode.js][] module. It can be accessed using: ```js -const punycode = require('punycode'); +const punycode = require('node:punycode'); ``` [Punycode][] is a character encoding scheme defined by RFC 3492 that is diff --git a/doc/api/querystring.md b/doc/api/querystring.md index 4b7db7afc3b948..780aa4c641d782 100644 --- a/doc/api/querystring.md +++ b/doc/api/querystring.md @@ -12,7 +12,7 @@ The `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 d67beab5d05922..6f99b9de4b0e21 100644 --- a/doc/api/readline.md +++ b/doc/api/readline.md @@ -11,13 +11,13 @@ stream (such as [`process.stdin`][]) one line at a time. It can be accessed using: ```js -const readline = require('readline'); +const readline = require('node:readline'); ``` The following simple example illustrates the basic use of the `readline` module. ```js -const readline = require('readline'); +const readline = require('node:readline'); const rl = readline.createInterface({ input: process.stdin, @@ -313,7 +313,7 @@ Promise that fulfills with the answer. If the question is canceled using an `AbortController` it will reject with an `AbortError`. ```js -const util = require('util'); +const util = require('node:util'); const question = util.promisify(rl.question).bind(rl); async function questionExample() { @@ -614,7 +614,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 @@ -746,7 +746,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, @@ -778,8 +778,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'); @@ -803,8 +803,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'), @@ -820,9 +820,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 075fa91581c428..26a34d602b3d3b 100644 --- a/doc/api/repl.md +++ b/doc/api/repl.md @@ -11,7 +11,7 @@ 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 @@ -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'); @@ -281,8 +281,8 @@ 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 { Translator } = require('translator'); +const repl = require('node:repl'); +const { Translator } = require('node:translator'); const myTranslator = new Translator('en', 'fr'); @@ -352,7 +352,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 }); @@ -377,7 +377,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 }; @@ -419,7 +419,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'; @@ -469,7 +469,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', { @@ -641,7 +641,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('$ '); @@ -713,8 +713,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 cc18b643b7158e..3190d1cb6b12d6 100644 --- a/doc/api/stream.md +++ b/doc/api/stream.md @@ -19,7 +19,7 @@ Streams can be readable, writable, or both. All streams are instances of To access the `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 @@ -133,7 +133,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. @@ -462,7 +462,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!'); @@ -777,7 +777,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(); @@ -949,7 +949,7 @@ available data. In the latter case, [`stream.read()`][stream-read] will return `null`. 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()}`); @@ -1089,7 +1089,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'. @@ -1103,7 +1103,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'); @@ -1359,7 +1359,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', @@ -1410,7 +1410,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); @@ -1473,7 +1473,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); @@ -1494,7 +1494,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'); @@ -1622,7 +1622,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'); @@ -1644,7 +1644,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'); @@ -1705,9 +1705,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. @@ -1735,7 +1735,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( @@ -1753,7 +1753,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(); @@ -1776,8 +1776,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( @@ -1822,7 +1822,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'; @@ -1855,7 +1855,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( @@ -1903,7 +1903,7 @@ parent class constructor: ```js -const { Writable } = require('stream'); +const { Writable } = require('node:stream'); class MyWritable extends Writable { constructor({ highWaterMark, ...options }) { @@ -1953,7 +1953,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) { @@ -2033,7 +2033,7 @@ changes: ```js -const { Writable } = require('stream'); +const { Writable } = require('node:stream'); class MyWritable extends Writable { constructor(options) { @@ -2047,8 +2047,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)) @@ -2061,7 +2061,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) { @@ -2078,7 +2078,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({ @@ -2111,8 +2111,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) { @@ -2262,7 +2262,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) { @@ -2283,7 +2283,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) { @@ -2304,8 +2304,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) { @@ -2383,7 +2383,7 @@ changes: ```js -const { Readable } = require('stream'); +const { Readable } = require('node:stream'); class MyReadable extends Readable { constructor(options) { @@ -2397,8 +2397,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)) @@ -2411,7 +2411,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) { @@ -2425,7 +2425,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) { @@ -2455,8 +2455,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) { @@ -2623,7 +2623,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) { @@ -2645,7 +2645,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) { @@ -2714,7 +2714,7 @@ changes: ```js -const { Duplex } = require('stream'); +const { Duplex } = require('node:stream'); class MyDuplex extends Duplex { constructor(options) { @@ -2727,8 +2727,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)) @@ -2741,7 +2741,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) { @@ -2756,8 +2756,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') @@ -2804,7 +2804,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 { @@ -2845,7 +2845,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({ @@ -2909,7 +2909,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) { @@ -2922,8 +2922,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)) @@ -2936,7 +2936,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) { @@ -3080,7 +3080,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'); async function * generate() { yield 'a'; @@ -3102,9 +3102,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 e0e1323cf331e3..cfab2a0a5facc2 100644 --- a/doc/api/string_decoder.md +++ b/doc/api/string_decoder.md @@ -11,13 +11,13 @@ 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 cb43312f358746..0fc73b760c8633 100644 --- a/doc/api/synopsis.md +++ b/doc/api/synopsis.md @@ -53,7 +53,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 4b3ec8d5e79e80..be811f0989fbcc 100644 --- a/doc/api/timers.md +++ b/doc/api/timers.md @@ -173,7 +173,7 @@ This method has a custom variant for promises that is available using [`util.promisify()`][]: ```js -const util = require('util'); +const util = require('node:util'); const setImmediatePromise = util.promisify(setImmediate); setImmediatePromise('foobar').then((value) => { @@ -235,7 +235,7 @@ This method has a custom variant for promises that is available using [`util.promisify()`][]: ```js -const util = require('util'); +const util = require('node:util'); const setTimeoutPromise = util.promisify(setTimeout); setTimeoutPromise(40, 'foobar').then((value) => { @@ -257,7 +257,7 @@ returned Promises will be rejected with an `'AbortError'`. For `setImmediate()`: ```js -const util = require('util'); +const util = require('node:util'); const setImmediatePromise = util.promisify(setImmediate); const ac = new AbortController(); @@ -276,7 +276,7 @@ ac.abort(); For `setTimeout()`: ```js -const util = require('util'); +const util = require('node:util'); const setTimeoutPromise = util.promisify(setTimeout); const ac = new AbortController(); @@ -346,7 +346,7 @@ const { setTimeout, setImmediate, setInterval, -} = require('timers/promises'); +} = require('node:timers/promises'); ``` ### `timersPromises.setTimeout([delay[, value[, options]]])` @@ -377,7 +377,7 @@ console.log(res); // Prints 'result' ```cjs const { setTimeout, -} = require('timers/promises'); +} = require('node:timers/promises'); setTimeout(100, 'result').then((res) => { console.log(res); // Prints 'result' @@ -410,7 +410,7 @@ console.log(res); // Prints 'result' ```cjs const { setImmediate, -} = require('timers/promises'); +} = require('node:timers/promises'); setImmediate('result').then((res) => { console.log(res); // Prints 'result' @@ -453,7 +453,7 @@ console.log(Date.now()); ```cjs const { setInterval, -} = require('timers/promises'); +} = require('node:timers/promises'); const interval = 100; (async function() { diff --git a/doc/api/tls.md b/doc/api/tls.md index b82de483f9b825..ecc449471ea425 100644 --- a/doc/api/tls.md +++ b/doc/api/tls.md @@ -11,7 +11,7 @@ The `tls` module provides an implementation of the Transport Layer Security The module can be accessed using: ```js -const tls = require('tls'); +const tls = require('node:tls'); ``` ## TLS/SSL concepts @@ -1558,8 +1558,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. @@ -1958,8 +1958,8 @@ 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 5c56360319a69c..0cb7886bf71a23 100644 --- a/doc/api/tracing.md +++ b/doc/api/tracing.md @@ -58,7 +58,7 @@ node --trace-event-categories v8,node,node.async_hooks Alternatively, trace events may be enabled using the `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 @@ -127,7 +127,7 @@ Only trace event categories *not* covered by other enabled `Tracing` objects and *not* specified by the `--trace-event-categories` flag will be disabled. ```js -const trace_events = require('trace_events'); +const trace_events = require('node:trace_events'); const t1 = trace_events.createTracing({ categories: ['node', 'v8'] }); const t2 = trace_events.createTracing({ categories: ['node.perf', 'node'] }); t1.enable(); @@ -171,7 +171,7 @@ added: v10.0.0 Creates and returns a `Tracing` object for the given set of `categories`. ```js -const trace_events = require('trace_events'); +const trace_events = require('node:trace_events'); const categories = ['node.perf', 'node.async_hooks']; const tracing = trace_events.createTracing({ categories }); tracing.enable(); @@ -196,7 +196,7 @@ Given the file `test.js` below, the command `'node.async_hooks,node.perf'` to the console. ```js -const trace_events = require('trace_events'); +const trace_events = require('node:trace_events'); const t1 = trace_events.createTracing({ categories: ['node.async_hooks'] }); const t2 = trace_events.createTracing({ categories: ['node.perf'] }); const t3 = trace_events.createTracing({ categories: ['v8'] }); diff --git a/doc/api/tty.md b/doc/api/tty.md index 3cf37ff9cb7cdf..c8f7720537070f 100644 --- a/doc/api/tty.md +++ b/doc/api/tty.md @@ -11,7 +11,7 @@ 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 1063baefc849bb..bc362469945e0d 100644 --- a/doc/api/url.md +++ b/doc/api/url.md @@ -14,7 +14,7 @@ import url from 'url'; ``` ```cjs -const url = require('url'); +const url = require('node:url'); ``` ## URL strings and URL objects @@ -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'); ``` @@ -146,12 +146,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 @@ -943,7 +943,7 @@ invalid domain, the empty string is returned. It performs the inverse operation to [`url.domainToUnicode()`][]. ```mjs -import url from 'url'; +import url from 'node:url'; console.log(url.domainToASCII('español.com')); // Prints xn--espaol-zwa.com @@ -954,7 +954,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 @@ -980,7 +980,7 @@ domain, the empty string is returned. It performs the inverse operation to [`url.domainToASCII()`][]. ```mjs -import url from 'url'; +import url from 'node:url'; console.log(url.domainToUnicode('xn--espaol-zwa.com')); // Prints español.com @@ -991,7 +991,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 @@ -1115,7 +1115,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)); @@ -1134,7 +1134,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)); @@ -1470,7 +1470,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 HREF. ```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 35b93ba198f3b9..675404b014d7a5 100644 --- a/doc/api/util.md +++ b/doc/api/util.md @@ -11,7 +11,7 @@ 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)` @@ -29,7 +29,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'; @@ -88,7 +88,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); @@ -107,7 +107,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); @@ -128,7 +128,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 @@ -150,7 +150,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); @@ -192,7 +192,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. @@ -209,7 +209,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'); @@ -423,8 +423,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); @@ -450,7 +450,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) { @@ -620,7 +620,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]; @@ -638,7 +638,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 })); ``` @@ -646,7 +646,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, [[ @@ -702,7 +702,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 }; @@ -716,8 +716,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], @@ -845,7 +845,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) { @@ -880,7 +880,7 @@ 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) => { @@ -942,7 +942,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 @@ -978,8 +978,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) => { @@ -992,8 +992,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); @@ -1016,7 +1016,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() { @@ -1046,7 +1046,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) { // ... @@ -2077,7 +2077,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 @@ -2101,7 +2101,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 @@ -2125,7 +2125,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 @@ -2149,7 +2149,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 @@ -2174,7 +2174,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 @@ -2189,7 +2189,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); @@ -2214,7 +2214,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 = () => {}; @@ -2242,7 +2242,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 @@ -2268,7 +2268,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 @@ -2292,7 +2292,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 @@ -2321,7 +2321,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 @@ -2350,7 +2350,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 @@ -2386,7 +2386,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 @@ -2410,7 +2410,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 @@ -2436,7 +2436,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 @@ -2460,7 +2460,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); @@ -2485,7 +2485,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 41e4c7456284ca..e5421956e77b00 100644 --- a/doc/api/v8.md +++ b/doc/api/v8.md @@ -8,7 +8,7 @@ The `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()` @@ -69,7 +69,7 @@ V8 engine. Therefore, the schema may change from one version of V8 to the next. ```js // Print heap snapshot to the console -const v8 = require('v8'); +const v8 = require('node:v8'); const stream = v8.getHeapSnapshot(); stream.pipe(process.stdout); ``` @@ -218,7 +218,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); ``` @@ -276,12 +276,12 @@ A heap snapshot is specific to a single V8 isolate. When using not contain any information about the workers, and vice versa. ```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); diff --git a/doc/api/vm.md b/doc/api/vm.md index acb07299399440..c83f1f67c94851 100644 --- a/doc/api/vm.md +++ b/doc/api/vm.md @@ -24,7 +24,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; @@ -162,7 +162,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', @@ -243,7 +243,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"'); @@ -287,7 +287,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; @@ -338,7 +338,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() @@ -480,7 +480,7 @@ await bar.evaluate(); ``` ```cjs -const vm = require('vm'); +const vm = require('node:vm'); const contextifiedObject = vm.createContext({ secret: 42, @@ -782,7 +782,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( @@ -852,7 +852,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() { @@ -913,7 +913,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); @@ -1025,7 +1025,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; @@ -1129,7 +1129,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); @@ -1231,7 +1231,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', @@ -1306,7 +1306,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";'); @@ -1336,11 +1336,11 @@ to the `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' }); @@ -1387,7 +1387,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'); @@ -1407,7 +1407,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 b246ad3aae7ffa..d857a7c2a6c8c6 100644 --- a/doc/api/wasi.md +++ b/doc/api/wasi.md @@ -31,8 +31,8 @@ wasi.start(instance); ```cjs 'use strict'; -const fs = require('fs'); -const { WASI } = require('wasi'); +const fs = require('node:fs'); +const { WASI } = require('node:wasi'); const wasi = new WASI({ args: process.argv, env: process.env, diff --git a/doc/api/webcrypto.md b/doc/api/webcrypto.md index 66d577192f5648..a982d1591daa32 100644 --- a/doc/api/webcrypto.md +++ b/doc/api/webcrypto.md @@ -9,7 +9,7 @@ Node.js provides an implementation of the standard [Web Crypto API][]. Use `require('crypto').webcrypto` to access this module. ```js -const { subtle } = require('crypto').webcrypto; +const { subtle } = require('node:crypto').webcrypto; (async function() { @@ -36,7 +36,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({ @@ -51,7 +51,7 @@ async function generateAesKey(length = 256) { #### Elliptic curve key pairs ```js -const { subtle } = require('crypto').webcrypto; +const { subtle } = require('node:crypto').webcrypto; async function generateEcKey(namedCurve = 'P-521') { const { @@ -69,7 +69,7 @@ async function generateEcKey(namedCurve = 'P-521') { #### ED25519/ED448/X25519/X448 Elliptic curve key pairs ```js -const { subtle } = require('crypto').webcrypto; +const { subtle } = require('node:crypto').webcrypto; async function generateEd25519Key() { return subtle.generateKey({ @@ -89,7 +89,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({ @@ -104,7 +104,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') { @@ -125,7 +125,7 @@ async function generateRsaKey(modulusLength = 2048, hash = 'SHA-256') { ### Encryption and decryption ```js -const { subtle, getRandomValues } = require('crypto').webcrypto; +const { subtle, getRandomValues } = require('node:crypto').webcrypto; async function aesEncrypt(plaintext) { const ec = new TextEncoder(); @@ -158,7 +158,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({ @@ -182,7 +182,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 [ @@ -225,7 +225,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(); @@ -249,7 +249,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(); @@ -292,7 +292,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(); diff --git a/doc/api/worker_threads.md b/doc/api/worker_threads.md index 05490a8bb50745..81063d7683a6e3 100644 --- a/doc/api/worker_threads.md +++ b/doc/api/worker_threads.md @@ -10,7 +10,7 @@ The `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) { @@ -83,7 +83,7 @@ const { isMainThread, setEnvironmentData, getEnvironmentData, -} = require('worker_threads'); +} = require('node:worker_threads'); if (isMainThread) { setEnvironmentData('Hello', 'World!'); @@ -103,7 +103,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. @@ -132,7 +132,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); @@ -192,7 +192,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); @@ -227,7 +227,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' }); @@ -271,7 +271,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'. @@ -318,7 +318,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!' }); @@ -344,7 +344,7 @@ const { isMainThread, BroadcastChannel, Worker -} = require('worker_threads'); +} = require('node:worker_threads'); const bc = new BroadcastChannel('hello'); @@ -431,7 +431,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)); @@ -468,7 +468,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: @@ -577,7 +577,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)); @@ -602,7 +602,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)); @@ -818,10 +818,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(); @@ -1053,7 +1053,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); diff --git a/doc/api/zlib.md b/doc/api/zlib.md index 3187195a0e0a3a..607966cbf934f4 100644 --- a/doc/api/zlib.md +++ b/doc/api/zlib.md @@ -12,7 +12,7 @@ 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'); @@ -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'); @@ -318,9 +318,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. From 8e6349f02fda4f70747812bae727724bb05bb77d Mon Sep 17 00:00:00 2001 From: "Jerome T.K. Covington" Date: Mon, 10 May 2021 14:47:48 -0400 Subject: [PATCH 3/4] doc: ensure line <= 80 for markdown linter --- doc/api/async_hooks.md | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/doc/api/async_hooks.md b/doc/api/async_hooks.md index be59b4727abac6..1c90086b91abe6 100644 --- a/doc/api/async_hooks.md +++ b/doc/api/async_hooks.md @@ -508,7 +508,10 @@ but having an object representing the top-level can be helpful. ```js const { open } = require('node:fs'); -const { executionAsyncId, executionAsyncResource } = require('node:async_hooks'); +const { + executionAsyncId, + executionAsyncResource +} = require('node:async_hooks'); console.log(executionAsyncId(), executionAsyncResource()); // 1 {} open(__filename, 'r', (err, fd) => { From 7737f62ad57948e0af461061e30cfea24cca9fd7 Mon Sep 17 00:00:00 2001 From: "Jerome T.K. Covington" Date: Tue, 18 May 2021 19:50:06 -0400 Subject: [PATCH 4/4] doc: remove errant usage of node:cjs --- doc/api/esm.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/doc/api/esm.md b/doc/api/esm.md index a8b044b6b28c1d..c23f5a52ad74a7 100644 --- a/doc/api/esm.md +++ b/doc/api/esm.md @@ -350,11 +350,11 @@ module default import or its corresponding sugar syntax: ```js -import { default as cjs } from 'node:cjs'; +import { default as cjs } from 'cjs'; // The following import statement is "syntax sugar" (equivalent but sweeter) // for `{ default as cjsSugar }` in the above import statement: -import cjsSugar from 'node:cjs'; +import cjsSugar from 'cjs'; console.log(cjs); console.log(cjs === cjsSugar); @@ -368,11 +368,11 @@ a namespace with a `default` export key pointing to the CommonJS `module.exports` value. This Module Namespace Exotic Object can be directly observed either when using -`import * as m from 'node:cjs'` or a dynamic import: +`import * as m from 'cjs'` or a dynamic import: ```js -import * as m from 'node:cjs'; +import * as m from 'cjs'; console.log(m); console.log(m === await import('cjs')); // Prints: