Skip to content

Commit

Permalink
feat: add url.fileURLToPath
Browse files Browse the repository at this point in the history
  • Loading branch information
ruyadorno committed Jul 7, 2022
1 parent 91d7c11 commit f5eafe9
Show file tree
Hide file tree
Showing 3 changed files with 39 additions and 0 deletions.
27 changes: 27 additions & 0 deletions polyfills/url.js
Original file line number Diff line number Diff line change
Expand Up @@ -27,12 +27,14 @@ export {
urlParse as parse,
urlResolve as resolve,
urlResolveObject as resolveObject,
urlFileURLToPath as fileURLToPath,
urlFormat as format
};
export default {
parse: urlParse,
resolve: urlResolve,
resolveObject: urlResolveObject,
fileURLToPath: urlFileURLToPath,
format: urlFormat,
Url: Url
}
Expand Down Expand Up @@ -375,6 +377,31 @@ function parse(self, url, parseQueryString, slashesDenoteHost) {
return self;
}

function urlFileURLToPath(path) {
if (typeof path === 'string')
path = new Url().parse(path);
else if (!(url instanceof Url))
throw new TypeError('The "path" argument must be of type string or an instance of URL. Received type ' + (typeof path) + String(path));
if (path.protocol !== 'file:')
throw new TypeError('The URL must be of scheme file');
return getPathFromURLPosix(path);
}

function getPathFromURLPosix(url) {
const pathname = url.pathname;
for (let n = 0; n < pathname.length; n++) {
if (pathname[n] === '%') {
const third = pathname.codePointAt(n + 2) | 0x20;
if (pathname[n + 1] === '2' && third === 102) {
throw new TypeError(
'must not include encoded / characters'
);
}
}
}
return decodeURIComponent(pathname);
}

// format a parsed object into a url string
function urlFormat(obj) {
// ensure it's an object, and not a string url.
Expand Down
11 changes: 11 additions & 0 deletions test/examples/url-file-url-to-path.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import {fileURLToPath} from 'url';

const hello = 'file:///hello world';

if (
fileURLToPath(hello) !== '/hello world'
) {
done(new Error('invalid object'));
}

done();
1 change: 1 addition & 0 deletions test/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ const files = [
'events.js',
'crypto.js',
'url-parse.js',
'url-file-url-to-path.js',
'url-format.js',
'stream.js',
'assert.js',
Expand Down

0 comments on commit f5eafe9

Please sign in to comment.