Skip to content

Commit 8578e81

Browse files
committed
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: nodejs#5963 PR-URL: nodejs#17113 Reviewed-By: Refael Ackermann <refack@gmail.com> Reviewed-By: James M Snell <jasnell@gmail.com>
1 parent 4b34e6f commit 8578e81

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
@@ -521,11 +521,14 @@ Module._resolveFilename = function(request, parent, isMain, options) {
521521

522522
if (typeof options === 'object' && options !== null &&
523523
Array.isArray(options.paths)) {
524+
const fakeParent = new Module('', null);
525+
524526
paths = [];
525527

526528
for (var i = 0; i < options.paths.length; i++) {
527529
const path = options.paths[i];
528-
const lookupPaths = Module._resolveLookupPaths(path, parent, true);
530+
fakeParent.paths = Module._nodeModulePaths(path);
531+
const lookupPaths = Module._resolveLookupPaths(request, fakeParent, true);
529532

530533
if (!paths.includes(path))
531534
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)