Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 16 additions & 9 deletions lib/internal/modules/cjs/loader.js
Original file line number Diff line number Diff line change
Expand Up @@ -575,18 +575,25 @@ Module._resolveFilename = function(request, parent, isMain, options) {

if (typeof options === 'object' && options !== null &&
Array.isArray(options.paths)) {
const fakeParent = new Module('', null);
const isRelative = request.startsWith('./') || request.startsWith('../') ||
(isWindows && request.startsWith('.\\') || request.startsWith('..\\'));

paths = [];
if (isRelative) {
paths = options.paths;
} else {
const fakeParent = new Module('', null);

for (var i = 0; i < options.paths.length; i++) {
const path = options.paths[i];
fakeParent.paths = Module._nodeModulePaths(path);
const lookupPaths = Module._resolveLookupPaths(request, fakeParent);
paths = [];

for (var j = 0; j < lookupPaths.length; j++) {
if (!paths.includes(lookupPaths[j]))
paths.push(lookupPaths[j]);
for (var i = 0; i < options.paths.length; i++) {
const path = options.paths[i];
fakeParent.paths = Module._nodeModulePaths(path);
const lookupPaths = Module._resolveLookupPaths(request, fakeParent);

for (var j = 0; j < lookupPaths.length; j++) {
if (!paths.includes(lookupPaths[j]))
paths.push(lookupPaths[j]);
}
}
}
} else {
Expand Down
32 changes: 31 additions & 1 deletion test/fixtures/require-resolve.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
'use strict';
require('../common');
const common = require('../common');
const assert = require('assert');
const path = require('path');
const nodeModules = path.join(__dirname, 'node_modules');
Expand Down Expand Up @@ -54,3 +54,33 @@ assert.throws(() => {
path.join(nodeModules, 'bar.js')
);
}

// Verify that relative request paths work properly.
{
const searchIn = './' + path.relative(process.cwd(), nestedIndex);

// Search in relative paths.
assert.strictEqual(
require.resolve('./three.js', { paths: [searchIn] }),
path.join(nestedIndex, 'three.js')
);

// Search in absolute paths.
assert.strictEqual(
require.resolve('./three.js', { paths: [nestedIndex] }),
path.join(nestedIndex, 'three.js')
);

// Repeat the same tests with Windows slashes in the request path.
if (common.isWindows) {
assert.strictEqual(
require.resolve('.\\three.js', { paths: [searchIn] }),
path.join(nestedIndex, 'three.js')
);

assert.strictEqual(
require.resolve('.\\three.js', { paths: [nestedIndex] }),
path.join(nestedIndex, 'three.js')
);
}
}