Skip to main content
Module

std/path/_to_file_url.ts

Deno standard library
Go to Latest
File
// Copyright 2018-2023 the Deno authors. All rights reserved. MIT license.// This module is browser compatible.
import { posixIsAbsolute, windowsIsAbsolute } from "./_is_absolute.ts";
const WHITESPACE_ENCODINGS: Record<string, string> = { "\u0009": "%09", "\u000A": "%0A", "\u000B": "%0B", "\u000C": "%0C", "\u000D": "%0D", "\u0020": "%20",};
function encodeWhitespace(string: string): string { return string.replaceAll(/[\s]/g, (c) => { return WHITESPACE_ENCODINGS[c] ?? c; });}
/** * Converts a path string to a file URL. * * ```ts * import { toFileUrl } from "https://deno.land/std@$STD_VERSION/path/posix.ts"; * * toFileUrl("/home/foo"); // new URL("file:///home/foo") * ``` * @param path to convert to file URL */export function posixToFileUrl(path: string) { if (!posixIsAbsolute(path)) { throw new TypeError("Must be an absolute path."); }
const url = new URL("file:///"); url.pathname = encodeWhitespace( path.replace(/%/g, "%25").replace(/\\/g, "%5C"), ); return url;}
/** * Converts a path string to a file URL. * * ```ts * import { toFileUrl } from "https://deno.land/std@$STD_VERSION/path/win32.ts"; * * toFileUrl("\\home\\foo"); // new URL("file:///home/foo") * toFileUrl("C:\\Users\\foo"); // new URL("file:///C:/Users/foo") * toFileUrl("\\\\127.0.0.1\\home\\foo"); // new URL("file://127.0.0.1/home/foo") * ``` * @param path to convert to file URL */export function windowsToFileUrl(path: string): URL { if (!windowsIsAbsolute(path)) { throw new TypeError("Must be an absolute path."); }
const [, hostname, pathname] = path.match( /^(?:[/\\]{2}([^/\\]+)(?=[/\\](?:[^/\\]|$)))?(.*)/, )!; const url = new URL("file:///"); url.pathname = encodeWhitespace(pathname.replace(/%/g, "%25")); if (hostname !== undefined && hostname !== "localhost") { url.hostname = hostname; if (!url.hostname) { throw new TypeError("Invalid hostname."); } } return url;}