From f9f9389d83ccfd094a2be375d3f0cbad1e52077e Mon Sep 17 00:00:00 2001 From: ExE Boss <3889017+ExE-Boss@users.noreply.github.com> Date: Sat, 6 Feb 2021 12:10:00 +0100 Subject: [PATCH] =?UTF-8?q?module:=20add=C2=A0support=20for=C2=A0`node:`?= =?UTF-8?q?=E2=80=91prefixed=20`require(=E2=80=A6)`=C2=A0calls?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Fixes: https://github.com/nodejs/node/issues/36098 Co-authored-by: Antoine du Hamel Co-authored-by: Guy Bedford Co-authored-by: Darshan Sen PR-URL: https://github.com/nodejs/node/pull/37246 Reviewed-By: Bradley Farias Reviewed-By: Antoine du Hamel Reviewed-By: Benjamin Gruenbaum Reviewed-By: Darshan Sen Reviewed-By: Matteo Collina --- doc/api/esm.md | 8 ++++- doc/api/modules.md | 26 ++++++++++++-- lib/internal/modules/cjs/helpers.js | 3 +- lib/internal/modules/cjs/loader.js | 17 +++++++-- lib/internal/modules/esm/translators.js | 2 +- test/es-module/test-esm-dynamic-import.js | 2 ++ test/parallel/test-require-node-prefix.js | 42 +++++++++++++++++++++++ 7 files changed, 93 insertions(+), 7 deletions(-) create mode 100644 test/parallel/test-require-node-prefix.js diff --git a/doc/api/esm.md b/doc/api/esm.md index e4a865752d7ee7..f53d5561888302 100644 --- a/doc/api/esm.md +++ b/doc/api/esm.md @@ -199,7 +199,13 @@ import _ from 'data:application/json,"world!"'; #### `node:` Imports `node:` URLs are supported as an alternative means to load Node.js builtin diff --git a/doc/api/modules.md b/doc/api/modules.md index 1667c149953773..b17bd9eb390538 100644 --- a/doc/api/modules.md +++ b/doc/api/modules.md @@ -280,6 +280,12 @@ irrespective of whether or not `./foo` and `./FOO` are the same file. ## Core modules + Node.js has several modules compiled into the binary. These modules are described in greater detail elsewhere in this documentation. @@ -291,6 +297,11 @@ Core modules are always preferentially loaded if their identifier is passed to `require()`. For instance, `require('http')` will always return the built in HTTP module, even if there is a file by that name. +Core modules can also be identified using the `node:` prefix, in which case +it bypasses the `require` cache. For instance, `require('node:http')` will +always return the built in HTTP module, even if there is `require.cache` entry +by that name. + ## Cycles @@ -642,8 +653,19 @@ error. Adding or replacing entries is also possible. This cache is checked before native modules and if a name matching a native module is added to the cache, -no require call is -going to receive the native module anymore. Use with care! +only `node:`-prefixed require calls are going to receive the native module. +Use with care! + +```js +const assert = require('assert'); +const realFs = require('fs'); + +const fakeFs = {}; +require.cache.fs = { exports: fakeFs }; + +assert.strictEqual(require('fs'), fakeFs); +assert.strictEqual(require('node:fs'), realFs); +``` #### `require.extensions`