Skip to content

Commit f1b1b73

Browse files
guybedfordtargos
authored andcommitted
url: provide pathToFileURL and fileURLToPath
PR-URL: #22506 Reviewed-By: John-David Dalton <[email protected]> Reviewed-By: Tiancheng "Timothy" Gu <[email protected]> Reviewed-By: Matteo Collina <[email protected]> Reviewed-By: Bradley Farias <[email protected]> Reviewed-By: Joyee Cheung <[email protected]> Reviewed-By: Gus Caplan <[email protected]>
1 parent a3b3485 commit f1b1b73

File tree

13 files changed

+208
-112
lines changed

13 files changed

+208
-112
lines changed

doc/api/url.md

+43
Original file line numberDiff line numberDiff line change
@@ -880,6 +880,28 @@ console.log(url.domainToUnicode('xn--iñvalid.com'));
880880
// Prints an empty string
881881
```
882882

883+
### url.fileURLToPath(url)
884+
885+
* `url` {URL | string} The file URL string or URL object to convert to a path.
886+
* Returns: {string} The fully-resolved platform-specific Node.js file path.
887+
888+
This function ensures the correct decodings of percent-encoded characters as
889+
well as ensuring a cross-platform valid absolute path string.
890+
891+
```js
892+
new URL('file:///C:/path/').pathname; // Incorrect: /C:/path/
893+
fileURLToPath('file:///C:/path/'); // Correct: C:\path\ (Windows)
894+
895+
new URL('file://nas/foo.txt').pathname; // Incorrect: /foo.txt
896+
fileURLToPath('file://nas/foo.txt'); // Correct: \\nas\foo.txt (Windows)
897+
898+
new URL('file:///你好.txt').pathname; // Incorrect: /%E4%BD%A0%E5%A5%BD.txt
899+
fileURLToPath('file:///你好.txt'); // Correct: /你好.txt (POSIX)
900+
901+
new URL('file:///hello world').pathname; // Incorrect: /hello%20world
902+
fileURLToPath('file:///hello world'); // Correct: /hello world (POSIX)
903+
```
904+
883905
### url.format(URL[, options])
884906
<!-- YAML
885907
added: v7.6.0
@@ -919,6 +941,27 @@ console.log(url.format(myURL, { fragment: false, unicode: true, auth: false }));
919941
// Prints 'https://你好你好/?abc'
920942
```
921943

944+
### url.pathToFileURL(path)
945+
946+
* `path` {string} The path to convert to a File URL.
947+
* Returns: {URL} The file URL object.
948+
949+
This function ensures that `path` is resolved absolutely, and that the URL
950+
control characters are correctly encoded when converting into a File URL.
951+
952+
```js
953+
new URL(__filename); // Incorrect: throws (POSIX)
954+
new URL(__filename); // Incorrect: C:\... (Windows)
955+
pathToFileURL(__filename); // Correct: file:///... (POSIX)
956+
pathToFileURL(__filename); // Correct: file:///C:/... (Windows)
957+
958+
new URL('/foo#1', 'file:'); // Incorrect: file:///foo#1
959+
pathToFileURL('/foo#1'); // Correct: file:///foo%231 (POSIX)
960+
961+
new URL('/some/path%.js', 'file:'); // Incorrect: file:///some/path%
962+
pathToFileURL('/some/path%.js'); // Correct: file:///some/path%25 (POSIX)
963+
```
964+
922965
## Legacy URL API
923966

924967
### Legacy `urlObject`

0 commit comments

Comments
 (0)