Skip to content

Commit

Permalink
loader: make require.resolve throw for unknown builtin modules
Browse files Browse the repository at this point in the history
Fixes: #43274

PR-URL: #43336
Reviewed-By: Antoine du Hamel <duhamelantoine1995@gmail.com>
Reviewed-By: Benjamin Gruenbaum <benjamingr@gmail.com>
Reviewed-By: James M Snell <jasnell@gmail.com>
Reviewed-By: Luigi Pinca <luigipinca@gmail.com>
  • Loading branch information
zhmushan authored Jun 17, 2022
1 parent 7f19518 commit 7fd4cf4
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 7 deletions.
20 changes: 13 additions & 7 deletions lib/internal/modules/cjs/loader.js
Original file line number Diff line number Diff line change
Expand Up @@ -784,19 +784,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);
Expand Down Expand Up @@ -858,9 +858,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;
}

Expand Down
10 changes: 10 additions & 0 deletions test/parallel/test-require-resolve.js
Original file line number Diff line number Diff line change
Expand Up @@ -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' },
);
}

0 comments on commit 7fd4cf4

Please sign in to comment.