From 455ad0e4d3e0b49bc42cb75f1c15af9cad6a2214 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=9C=A8=E6=9D=89?= Date: Fri, 17 Jun 2022 16:20:48 +0800 Subject: [PATCH] loader: make `require.resolve` throw for unknown builtin modules Fixes: https://github.com/nodejs/node/issues/43274 PR-URL: https://github.com/nodejs/node/pull/43336 Reviewed-By: Antoine du Hamel Reviewed-By: Benjamin Gruenbaum Reviewed-By: James M Snell Reviewed-By: Luigi Pinca --- lib/internal/modules/cjs/loader.js | 20 +++++++++++++------- test/parallel/test-require-resolve.js | 10 ++++++++++ 2 files changed, 23 insertions(+), 7 deletions(-) diff --git a/lib/internal/modules/cjs/loader.js b/lib/internal/modules/cjs/loader.js index d8c5bf86fb6..30fb3cdc8ea 100644 --- a/lib/internal/modules/cjs/loader.js +++ b/lib/internal/modules/cjs/loader.js @@ -780,19 +780,19 @@ Module._load = function(request, parent, isMain) { } } - const filename = Module._resolveFilename(request, parent, isMain); - if (StringPrototypeStartsWith(filename, 'node:')) { + if (StringPrototypeStartsWith(request, 'node:')) { // Slice 'node:' prefix - const id = StringPrototypeSlice(filename, 5); + const id = StringPrototypeSlice(request, 5); const module = loadNativeModule(id, request); if (!module?.canBeRequiredByUsers) { - throw new ERR_UNKNOWN_BUILTIN_MODULE(filename); + throw new ERR_UNKNOWN_BUILTIN_MODULE(request); } return module.exports; } + const filename = Module._resolveFilename(request, parent, isMain); const cachedModule = Module._cache[filename]; if (cachedModule !== undefined) { updateChildren(parent, cachedModule, true); @@ -854,9 +854,15 @@ Module._load = function(request, parent, isMain) { }; Module._resolveFilename = function(request, parent, isMain, options) { - if (StringPrototypeStartsWith(request, 'node:') || - (NativeModule.canBeRequiredByUsers(request) && - NativeModule.canBeRequiredWithoutScheme(request))) { + if ( + ( + StringPrototypeStartsWith(request, 'node:') && + NativeModule.canBeRequiredByUsers(StringPrototypeSlice(request, 5)) + ) || ( + NativeModule.canBeRequiredByUsers(request) && + NativeModule.canBeRequiredWithoutScheme(request) + ) + ) { return request; } diff --git a/test/parallel/test-require-resolve.js b/test/parallel/test-require-resolve.js index e7125e39faf..ab58033e2c9 100644 --- a/test/parallel/test-require-resolve.js +++ b/test/parallel/test-require-resolve.js @@ -80,3 +80,13 @@ require(fixtures.path('resolve-paths', 'default', 'verify-paths.js')); assert.strictEqual(resolvedPaths.includes('/node_modules'), false); }); } + +{ + assert.strictEqual(require.resolve('node:test'), 'node:test'); + assert.strictEqual(require.resolve('node:fs'), 'node:fs'); + + assert.throws( + () => require.resolve('node:unknown'), + { code: 'MODULE_NOT_FOUND' }, + ); +}