Skip to content

Commit

Permalink
url: provide pathToFileURL and fileURLToPath
Browse files Browse the repository at this point in the history
PR-URL: #22506
Reviewed-By: John-David Dalton <john.david.dalton@gmail.com>
Reviewed-By: Tiancheng "Timothy" Gu <timothygu99@gmail.com>
Reviewed-By: Matteo Collina <matteo.collina@gmail.com>
Reviewed-By: Bradley Farias <bradley.meck@gmail.com>
Reviewed-By: Joyee Cheung <joyeec9h3@gmail.com>
Reviewed-By: Gus Caplan <me@gus.host>
  • Loading branch information
guybedford authored and targos committed Sep 25, 2018
1 parent a3b3485 commit f1b1b73
Show file tree
Hide file tree
Showing 13 changed files with 208 additions and 112 deletions.
43 changes: 43 additions & 0 deletions doc/api/url.md
Original file line number Diff line number Diff line change
Expand Up @@ -880,6 +880,28 @@ console.log(url.domainToUnicode('xn--iñvalid.com'));
// Prints an empty string
```

### url.fileURLToPath(url)

* `url` {URL | string} The file URL string or URL object to convert to a path.
* Returns: {string} The fully-resolved platform-specific Node.js file path.

This function ensures the correct decodings of percent-encoded characters as
well as ensuring a cross-platform valid absolute path string.

```js
new URL('file:///C:/path/').pathname; // Incorrect: /C:/path/
fileURLToPath('file:///C:/path/'); // Correct: C:\path\ (Windows)

new URL('file://nas/foo.txt').pathname; // Incorrect: /foo.txt
fileURLToPath('file://nas/foo.txt'); // Correct: \\nas\foo.txt (Windows)

new URL('file:///你好.txt').pathname; // Incorrect: /%E4%BD%A0%E5%A5%BD.txt
fileURLToPath('file:///你好.txt'); // Correct: /你好.txt (POSIX)

new URL('file:///hello world').pathname; // Incorrect: /hello%20world
fileURLToPath('file:///hello world'); // Correct: /hello world (POSIX)
```

### url.format(URL[, options])
<!-- YAML
added: v7.6.0
Expand Down Expand Up @@ -919,6 +941,27 @@ console.log(url.format(myURL, { fragment: false, unicode: true, auth: false }));
// Prints 'https://你好你好/?abc'
```

### url.pathToFileURL(path)

* `path` {string} The path to convert to a File URL.
* Returns: {URL} The file URL object.

This function ensures that `path` is resolved absolutely, and that the URL
control characters are correctly encoded when converting into a File URL.

```js
new URL(__filename); // Incorrect: throws (POSIX)
new URL(__filename); // Incorrect: C:\... (Windows)
pathToFileURL(__filename); // Correct: file:///... (POSIX)
pathToFileURL(__filename); // Correct: file:///C:/... (Windows)

new URL('/foo#1', 'file:'); // Incorrect: file:///foo#1
pathToFileURL('/foo#1'); // Correct: file:///foo%231 (POSIX)

new URL('/some/path%.js', 'file:'); // Incorrect: file:///some/path%
pathToFileURL('/some/path%.js'); // Correct: file:///some/path%25 (POSIX)
```

## Legacy URL API

### Legacy `urlObject`
Expand Down
Loading

0 comments on commit f1b1b73

Please sign in to comment.