Skip to content

path: fix POSIX path.resolve() perf regression #38064

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
Closed
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
32 changes: 19 additions & 13 deletions lib/path.js
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,6 @@

const {
FunctionPrototypeBind,
RegExp,
StringPrototypeCharCodeAt,
StringPrototypeIndexOf,
StringPrototypeLastIndexOf,
Expand All @@ -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;
}
Expand Down Expand Up @@ -1011,24 +1012,29 @@ 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) {
let resolvedPath = '';
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');

Expand Down Expand Up @@ -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;