fileurl2path
Version:
A tiny function for converting a file URL to a file path.
36 lines (35 loc) • 1.23 kB
JavaScript
/* IMPORT */
import { IS_WINDOWS } from './constants.js';
import { castURL } from './utils.js';
/* MAIN */
const fileurl2path = (url) => {
return IS_WINDOWS ? fileurl2path.win32(url) : fileurl2path.posix(url);
};
/* UTILITIES */
fileurl2path.posix = (url) => {
let { protocol, hostname, pathname } = castURL(url);
if (protocol !== 'file:')
throw new Error('Unsupported protocol');
if (hostname !== '')
throw new Error('Unsupported hostname');
if (/%2f/i.test(pathname))
throw new Error('Unsupported pathname');
return decodeURIComponent(pathname);
};
fileurl2path.win32 = (url) => {
let { protocol, hostname, pathname } = castURL(url);
if (protocol !== 'file:')
throw new Error('Unsupported protocol');
if (hostname !== '')
throw new Error('Unsupported hostname'); //TODO: Support this
if (/%2f|%5c/i.test(pathname))
throw new Error('Unsupported pathname');
pathname = pathname.replaceAll('/', '\\');
pathname = decodeURIComponent(pathname);
if (!/^\\[a-z]:/i.test(pathname))
throw new Error('Unsupported pathname');
pathname = pathname.slice(1);
return pathname;
};
/* EXPORT */
export default fileurl2path;