pathToFileUrl
Converts a filesystem path into a file:/// URL, percent-encoding it with encodeUrl.
The backslashes are turned into forward slashes after the encoding, not before — a Windows path is encoded to %5C first and only then rewritten to /, which is what makes C:\a b\c produce the working file:///C:/a%20b/c rather than a link broken at the first space.
The file:/// prefix always ends up with exactly three slashes: any leading slashes the path already has are dropped first, because file:////home/x parses as the path //home/x, not /home/x. A Windows UNC path (\\server\share) is therefore rendered as file:///server/share rather than the canonical host form file://server/share, which this function deliberately does not produce.
Import:
import { pathToFileUrl } from 'obsidian-dev-utils/url';Example:
pathToFileUrl(String.raw`C:\a b\c.txt`) // 'file:///C:/a%20b/c.txt'pathToFileUrl('/home/user/a b.txt') // 'file:///home/user/a%20b.txt'Signature:
function pathToFileUrl(path: string, shouldEncodePercent: boolean | undefined): stringParameters:
| Parameter | Type | Description |
|---|---|---|
path | string | The filesystem path to convert. |
shouldEncodePercent | boolean | undefined | Whether to encode a literal % in the path as %25. Defaults to false. See encodeUrl for the trade-off. |
Returns: string — The file:/// URL.
Example:
pathToFileUrl(String.raw`C:\a b\c.txt`) // 'file:///C:/a%20b/c.txt'pathToFileUrl('/home/user/a b.txt') // 'file:///home/user/a%20b.txt'