deno.land / std@0.201.0 / path / _to_file_url.ts

_to_file_url.ts
نووسراو ببینە
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
// 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;}
std

Version Info

Tagged at
a year ago