From 2b3177e048418a8f31dddf9cf1bf1548b5018530 Mon Sep 17 00:00:00 2001 From: Bartosz Sosnowski Date: Thu, 3 Jan 2019 14:37:58 +0100 Subject: [PATCH] win, url: make fileURLToPath return backslashes Makes fileURLToPath use backslashes as path separator on Windows Fixes: https://github.com/nodejs/node/issues/25265 --- lib/internal/url.js | 5 ++++- test/parallel/test-fs-whatwg-url.js | 15 +++++++++++++-- 2 files changed, 17 insertions(+), 3 deletions(-) diff --git a/lib/internal/url.js b/lib/internal/url.js index 45ed236511ac9a..e55376e9c5fa5a 100644 --- a/lib/internal/url.js +++ b/lib/internal/url.js @@ -1328,6 +1328,7 @@ function getPathFromURLPosix(url) { return decodeURIComponent(pathname); } +const forwardslashRegEx = /\//g; function fileURLToPath(path) { if (typeof path === 'string') path = new URL(path); @@ -1336,7 +1337,9 @@ function fileURLToPath(path) { throw new ERR_INVALID_ARG_TYPE('path', ['string', 'URL'], path); if (path.protocol !== 'file:') throw new ERR_INVALID_URL_SCHEME('file'); - return isWindows ? getPathFromURLWin32(path) : getPathFromURLPosix(path); + return isWindows ? + getPathFromURLWin32(path).replace(forwardslashRegEx, '\\') : + getPathFromURLPosix(path); } // The following characters are percent-encoded when converting from file path diff --git a/test/parallel/test-fs-whatwg-url.js b/test/parallel/test-fs-whatwg-url.js index 91c5c39637d175..61aae63f36912a 100644 --- a/test/parallel/test-fs-whatwg-url.js +++ b/test/parallel/test-fs-whatwg-url.js @@ -6,7 +6,7 @@ const assert = require('assert'); const path = require('path'); const fs = require('fs'); const os = require('os'); -const URL = require('url').URL; +const { fileURLToPath, URL } = require('url'); function pathToFileURL(p) { if (!path.isAbsolute(p)) @@ -30,6 +30,17 @@ fs.readFile(url, common.mustCall((err, data) => { // Check that using a non file:// URL reports an error const httpUrl = new URL('http://example.org'); +// Check that the fileURLToPath uses platform separator +['file:///c:/tmp', 'file://tmp/tmp'].forEach((i) => { + assert(fileURLToPath(i).includes(path.sep)); +}); + +// Check fileURLToPath examples from documentation +if (common.isWindows) { + assert.strictEqual(fileURLToPath('file:///C:/path/'), 'C:\\path\\'); + assert.strictEqual(fileURLToPath('file://nas/foo.txt'), '\\\\nas\\foo.txt'); +} + common.expectsError( () => { fs.readFile(httpUrl, common.mustNotCall()); @@ -63,7 +74,7 @@ if (common.isWindows) { code: 'ERR_INVALID_ARG_VALUE', type: TypeError, message: 'The argument \'path\' must be a string or Uint8Array without ' + - 'null bytes. Received \'c:/tmp/\\u0000test\'' + 'null bytes. Received \'c:\\\\tmp\\\\\\u0000test\'' } ); } else {