From 18c56df9281ac804ad642bd47134ae57e0a3357a Mon Sep 17 00:00:00 2001 From: Ruben Bridgewater Date: Fri, 5 Jul 2019 13:49:40 +0200 Subject: [PATCH] path: using .relative() should not return a trailing slash Resolving a path against root with `path.relative()` should not include a trailing slash. Fixes: https://github.com/nodejs/node/issues/28549 PR-URL: https://github.com/nodejs/node/pull/28556 Reviewed-By: Rich Trott Reviewed-By: Weijia Wang Reviewed-By: Anna Henningsen Reviewed-By: Jiawen Geng Reviewed-By: Yongsheng Zhang --- lib/path.js | 15 ++++++++++----- test/parallel/test-path-relative.js | 3 ++- 2 files changed, 12 insertions(+), 6 deletions(-) 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', '/', '../../..'] ] ] ];