Skip to content

Commit

Permalink
loader: make require.resolve throw error for unknown builtin modules
Browse files Browse the repository at this point in the history
Fixes: #43274
  • Loading branch information
zhmushan committed Jun 7, 2022
1 parent 797e41c commit edc7a8e
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 7 deletions.
19 changes: 12 additions & 7 deletions lib/internal/modules/cjs/loader.js
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down Expand Up @@ -854,9 +854,14 @@ 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
15 changes: 15 additions & 0 deletions test/parallel/test-require-resolve.js
Original file line number Diff line number Diff line change
Expand Up @@ -80,3 +80,18 @@ require(fixtures.path('resolve-paths', 'default', 'verify-paths.js'));
assert.strictEqual(resolvedPaths.includes('/node_modules'), false);
});
}

// For direct use of require expressions inside of CJS modules,
// all kinds of specifiers should work without issue.
{
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',
message: /^Cannot find module 'node:unknown'/,
},
);
}

0 comments on commit edc7a8e

Please sign in to comment.