All files / fs / unstable_read_link.ts

0.00% Branches 0/2
41.67% Lines 10/24
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
 
 
x1
x1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
x1
x4
x4
 
 
 
 
 
 
 
x4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
x1
x4
x4
 
 
 
 
 
 
 
x4




























I































I






// Copyright 2018-2025 the Deno authors. MIT license.

import { getNodeFs, isDeno } from "./_utils.ts";
import { mapError } from "./_map_error.ts";

/**
 * Resolves to the path destination of the named symbolic link.
 *
 * Throws Error if called with a hard link.
 *
 * Requires `allow-read` permission.
 *
 * @example Usage
 * ```ts ignore
 * import { readLink } from "@std/fs/unstable-read-link";
 * import { symlink } from "@std/fs/unstable-symlink";
 * await symlink("./test.txt", "./test_link.txt");
 * const target = await readLink("./test_link.txt"); // full path of ./test.txt
 * ```
 *
 * @tags allow-read
 *
 * @param path The path of the symbolic link.
 * @returns A promise that resolves to the file path pointed by the symbolic
 * link.
 */
export async function readLink(path: string | URL): Promise<string> {
  if (isDeno) {
    return Deno.readLink(path);
  } else {
    try {
      return await getNodeFs().promises.readlink(path);
    } catch (error) {
      throw mapError(error);
    }
  }
}

/**
 * Synchronously returns the path destination of the named symbolic link.
 *
 * Throws Error if called with a hard link.
 *
 * Requires `allow-read` permission.
 *
 * @example Usage
 * ```ts ignore
 * import { readLinkSync } from "@std/fs/unstable-read-link";
 * import { symlinkSync } from "@std/fs/unstable-symlink";
 * symlinkSync("./test.txt", "./test_link.txt");
 * const target = readLinkSync("./test_link.txt"); // full path of ./test.txt
 * ```
 *
 * @tags allow-read
 *
 * @param path The path of the symbolic link.
 * @returns The file path pointed by the symbolic link.
 */
export function readLinkSync(path: string | URL): string {
  if (isDeno) {
    return Deno.readLinkSync(path);
  } else {
    try {
      return getNodeFs().readlinkSync(path);
    } catch (error) {
      throw mapError(error);
    }
  }
}