From 02deafb84147ef4e2dbbe0a9db6be2447236a1c2 Mon Sep 17 00:00:00 2001 From: Brian White Date: Sat, 3 Apr 2021 17:04:50 -0400 Subject: [PATCH] path: fix POSIX path.resolve() perf regression --- lib/path.js | 32 +++++++++++++++++++------------- 1 file changed, 19 insertions(+), 13 deletions(-) diff --git a/lib/path.js b/lib/path.js index 95cb3201bf2fe0..09c40b927ba0d9 100644 --- a/lib/path.js +++ b/lib/path.js @@ -23,7 +23,6 @@ const { FunctionPrototypeBind, - RegExp, StringPrototypeCharCodeAt, StringPrototypeIndexOf, StringPrototypeLastIndexOf, @@ -48,6 +47,8 @@ const { validateString, } = require('internal/validators'); +const platformIsWin32 = (process.platform === 'win32'); + function isPathSeparator(code) { return code === CHAR_FORWARD_SLASH || code === CHAR_BACKWARD_SLASH; } @@ -1011,6 +1012,21 @@ const win32 = { posix: null }; +const posixCwd = (() => { + if (platformIsWin32) { + // Converts Windows' backslash path separators to POSIX forward slashes + // and truncates any drive indicator + const regexp = /\\/g; + return () => { + const cwd = StringPrototypeReplace(process.cwd(), regexp, '/'); + return StringPrototypeSlice(cwd, StringPrototypeIndexOf(cwd, '/')); + }; + } + + // We're already on POSIX, no need for any transformations + return () => process.cwd(); +})(); + const posix = { // path.resolve([from ...], to) resolve(...args) { @@ -1018,17 +1034,7 @@ const posix = { let resolvedAbsolute = false; for (let i = args.length - 1; i >= -1 && !resolvedAbsolute; i--) { - let path; - if (i >= 0) { - path = args[i]; - } else { - const _ = StringPrototypeReplace( - process.cwd(), - new RegExp(`\\${module.exports.sep}`, 'g'), - posix.sep - ); - path = StringPrototypeSlice(_, StringPrototypeIndexOf(_, posix.sep)); - } + const path = i >= 0 ? args[i] : posixCwd(); validateString(path, 'path'); @@ -1431,4 +1437,4 @@ posix.posix = win32.posix = posix; win32._makeLong = win32.toNamespacedPath; posix._makeLong = posix.toNamespacedPath; -module.exports = process.platform === 'win32' ? win32 : posix; +module.exports = platformIsWin32 ? win32 : posix;