Skip to content

Commit

Permalink
loader: require.resolve should throw for unkonw builtin modules
Browse files Browse the repository at this point in the history
  • Loading branch information
zhmushan committed Jun 7, 2022
1 parent 797e41c commit 353c538
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 3 deletions.
8 changes: 5 additions & 3 deletions lib/internal/modules/cjs/loader.js
Original file line number Diff line number Diff line change
Expand Up @@ -854,9 +854,11 @@ 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))) {
return request;
} else if (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 353c538

Please sign in to comment.