diff --git a/lib/path.js b/lib/path.js index 2301a6ebb8321f..f7a8612933ad76 100644 --- a/lib/path.js +++ b/lib/path.js @@ -1090,11 +1090,16 @@ const posix = { // For example: from='/'; to='/foo' return to.slice(toStart + i); } - } else if (fromLen > length && - from.charCodeAt(fromStart + i) === CHAR_FORWARD_SLASH) { - // We get here if `to` is the exact base path for `from`. - // For example: from='/foo/bar/baz'; to='/foo/bar' - lastCommonSep = i; + } else if (fromLen > length) { + if (from.charCodeAt(fromStart + i) === CHAR_FORWARD_SLASH) { + // We get here if `to` is the exact base path for `from`. + // For example: from='/foo/bar/baz'; to='/foo/bar' + lastCommonSep = i; + } else if (i === 0) { + // We get here if `to` is the root. + // For example: from='/foo/bar'; to='/' + lastCommonSep = 0; + } } } diff --git a/test/parallel/test-path-relative.js b/test/parallel/test-path-relative.js index 599381cdccfcb9..72f862b6df764e 100644 --- a/test/parallel/test-path-relative.js +++ b/test/parallel/test-path-relative.js @@ -47,7 +47,8 @@ const relativeTests = [ ['/foo/bar/baz-quux', '/foo/bar/baz', '../baz'], ['/foo/bar/baz', '/foo/bar/baz-quux', '../baz-quux'], ['/baz-quux', '/baz', '../baz'], - ['/baz', '/baz-quux', '../baz-quux'] + ['/baz', '/baz-quux', '../baz-quux'], + ['/page1/page2/foo', '/', '../../..'] ] ] ];