Skip to content

Commit caff930

Browse files
cjihrigMylesBorins
authored andcommitted
module: replace default paths in require.resolve()
Prior to this commit, the default search paths would be included in the require.resolve() process, even if user specified paths were provided. This commit causes the default paths to be omitted by using a fake parent module. Refs: #5963 PR-URL: #17113 Reviewed-By: Refael Ackermann <[email protected]> Reviewed-By: James M Snell <[email protected]>
1 parent 9c0c336 commit caff930

File tree

5 files changed

+26
-1
lines changed

5 files changed

+26
-1
lines changed

lib/module.js

+4-1
Original file line numberDiff line numberDiff line change
@@ -518,11 +518,14 @@ Module._resolveFilename = function(request, parent, isMain, options) {
518518

519519
if (typeof options === 'object' && options !== null &&
520520
Array.isArray(options.paths)) {
521+
const fakeParent = new Module('', null);
522+
521523
paths = [];
522524

523525
for (var i = 0; i < options.paths.length; i++) {
524526
const path = options.paths[i];
525-
const lookupPaths = Module._resolveLookupPaths(path, parent, true);
527+
fakeParent.paths = Module._nodeModulePaths(path);
528+
const lookupPaths = Module._resolveLookupPaths(request, fakeParent, true);
526529

527530
if (!paths.includes(path))
528531
paths.push(path);

test/fixtures/resolve-paths/default/node_modules/dep/index.js

Whitespace-only changes.
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
'use strict';
2+
require('../../../common');
3+
const assert = require('assert');
4+
const path = require('path');
5+
6+
// By default, resolving 'dep' should return
7+
// fixturesDir/resolve-paths/default/node_modules/dep/index.js. By setting
8+
// the path to fixturesDir/resolve-paths/default, the 'default' directory
9+
// structure should be ignored.
10+
11+
assert.strictEqual(
12+
require.resolve('dep'),
13+
path.join(__dirname, 'node_modules', 'dep', 'index.js')
14+
);
15+
16+
const paths = [path.resolve(__dirname, '..', 'defined')];
17+
18+
assert.strictEqual(
19+
require.resolve('dep', { paths }),
20+
path.join(paths[0], 'node_modules', 'dep', 'index.js')
21+
);

test/fixtures/resolve-paths/defined/node_modules/dep/index.js

Whitespace-only changes.

test/parallel/test-require-resolve.js

+1
Original file line numberDiff line numberDiff line change
@@ -37,3 +37,4 @@ assert.strictEqual('path', require.resolve('path'));
3737

3838
// Test configurable resolve() paths.
3939
require(fixtures.path('require-resolve.js'));
40+
require(fixtures.path('resolve-paths', 'default', 'verify-paths.js'));

0 commit comments

Comments
 (0)