Skip to content

Commit ca37e8f

Browse files
committed
url: skip resolve for already-absolute POSIX paths
pathToFileURL always called path.resolve, even when the input was already an absolute POSIX path with no '.' / '..' or empty segments. Reuse that path and drop a trailing slash the same way posix.resolve does, so the later restore does not append a second slash when path.sep is '\' (Windows host, windows: false). Official benchmark/url/whatwg-url-to-and-from-path.js pathToFileURL is about 27% faster for /dev/null and about 45-48% faster when the path has a query or hash. fileURLToPath is unchanged. Assisted-by: a closed-source coding agent Signed-off-by: Yagiz Nizipli <yagiz@nizipli.com> Co-authored-by: Yagiz Nizipli <anonrig@users.noreply.github.com>
1 parent dd5dfb5 commit ca37e8f

1 file changed

Lines changed: 24 additions & 3 deletions

File tree

‎lib/internal/url.js‎

Lines changed: 24 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1673,9 +1673,30 @@ function fileURLToPathBuffer(path, options = kEmptyObject) {
16731673
function pathToFileURL(filepath, options = kEmptyObject) {
16741674
const windows = options?.windows ?? isWindows;
16751675
const isUNC = windows && StringPrototypeStartsWith(filepath, '\\\\');
1676-
let resolved = isUNC ?
1677-
filepath :
1678-
(windows ? path.win32.resolve(filepath) : path.posix.resolve(filepath));
1676+
let resolved;
1677+
if (isUNC) {
1678+
resolved = filepath;
1679+
} else if (!windows &&
1680+
filepath.length > 0 &&
1681+
StringPrototypeCharCodeAt(filepath, 0) === CHAR_FORWARD_SLASH &&
1682+
StringPrototypeIndexOf(filepath, '.') === -1 &&
1683+
StringPrototypeIndexOf(filepath, '//') === -1) {
1684+
// Already an absolute POSIX path with no '.' / '..' or empty segments.
1685+
// posix.resolve() drops a trailing slash except for '/'. Keep that
1686+
// so the restore below does not append a second slash when path.sep
1687+
// is '\\' (Windows host, windows: false).
1688+
let end = filepath.length;
1689+
while (end > 1 &&
1690+
StringPrototypeCharCodeAt(filepath, end - 1) ===
1691+
CHAR_FORWARD_SLASH) {
1692+
end--;
1693+
}
1694+
resolved = end === filepath.length ?
1695+
filepath :
1696+
StringPrototypeSlice(filepath, 0, end);
1697+
} else {
1698+
resolved = windows ? path.win32.resolve(filepath) : path.posix.resolve(filepath);
1699+
}
16791700
if (isUNC || (windows && StringPrototypeStartsWith(resolved, '\\\\'))) {
16801701
// UNC path format: \\server\share\resource
16811702
// Handle extended UNC path and standard UNC path

0 commit comments

Comments
 (0)