diff --git a/lib/internal/url.js b/lib/internal/url.js index baa531cc68b..5c16a8d5a9c 100644 --- a/lib/internal/url.js +++ b/lib/internal/url.js @@ -1725,12 +1725,17 @@ function pathToFileURL(filepath, options = kEmptyObject) { const hostname = StringPrototypeSlice(resolved, prefixLength, hostnameEndIndex); return new URL(StringPrototypeSlice(resolved, hostnameEndIndex), hostname, kCreateURLFromWindowsPathSymbol); } - // path.resolve strips trailing slashes so we must add them back + // path.resolve() keeps a trailing separator only for a root, so put one + // back for other directories. Compare against the separator of the + // platform selected by options.windows. path.sep is the host separator + // and disagrees when those differ, which turns "C:\" into file:///C:// + // on a POSIX host and "/" into file://// on a Windows host. const filePathLast = StringPrototypeCharCodeAt(filepath, filepath.length - 1); + const trailingSep = windows ? CHAR_BACKWARD_SLASH : CHAR_FORWARD_SLASH; if ((filePathLast === CHAR_FORWARD_SLASH || - ((windows ?? isWindows) && filePathLast === CHAR_BACKWARD_SLASH)) && - resolved[resolved.length - 1] !== path.sep) + (windows && filePathLast === CHAR_BACKWARD_SLASH)) && + StringPrototypeCharCodeAt(resolved, resolved.length - 1) !== trailingSep) resolved += '/'; return new URL(resolved, undefined, windows ? kCreateURLFromWindowsPathSymbol : kCreateURLFromPosixPathSymbol); diff --git a/test/parallel/test-url-pathtofileurl-root-slash.js b/test/parallel/test-url-pathtofileurl-root-slash.js new file mode 100644 index 00000000000..4c59d419f91 --- /dev/null +++ b/test/parallel/test-url-pathtofileurl-root-slash.js @@ -0,0 +1,23 @@ +'use strict'; + +// path.resolve() keeps a trailing separator only for a root. pathToFileURL() +// puts that separator back for other directories. The separator has to be the +// one for the platform selected by options.windows, not the host path.sep. +// Otherwise "C:\" on a POSIX host becomes file:///C://, and "/" on a Windows +// host with { windows: false } becomes file:////. + +require('../common'); +const assert = require('node:assert'); +const url = require('node:url'); + +assert.strictEqual(url.pathToFileURL('C:\\', { windows: true }).href, 'file:///C:/'); +assert.strictEqual(url.pathToFileURL('C:/', { windows: true }).href, 'file:///C:/'); +// win32.resolve('C:\\foo\\..\\') is 'C:\\'. The original trailing separator +// must not add a second slash on top of the root. +assert.strictEqual(url.pathToFileURL('C:\\foo\\..\\', { windows: true }).href, 'file:///C:/'); + +assert.strictEqual(url.pathToFileURL('/', { windows: false }).href, 'file:///'); + +// Non-root directories still keep exactly one trailing slash. +assert.strictEqual(url.pathToFileURL('C:\\dir\\', { windows: true }).href, 'file:///C:/dir/'); +assert.strictEqual(url.pathToFileURL('/dir/', { windows: false }).href, 'file:///dir/');