All files / fs / unstable_read_text_file.ts

0.00% Branches 0/2
41.94% Lines 13/31
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
74
75
76
77
78
79
80
81
82
83
 
 
x6
 
x6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
x6
x6
x6
 
x22
x66
 
 
 
 
 
 
 
 
 
 
 
x22
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
x6
x6
 
x19
x19
 
 
 
 
 
 
 
x19


































I







































I






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

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

/**
 * Asynchronously reads and returns the entire contents of a file as an UTF-8 decoded string.
 *
 * Reading a directory throws an error.
 *
 * Requires `allow-read` permission.
 *
 * @example Usage
 * ```ts
 * import { assert } from "@std/assert";
 * import { readTextFile } from "@std/fs/unstable-read-text-file";
 *
 * const content = await readTextFile("README.md"); // full content of README.md
 *
 * assert(content.length > 0);
 * ```
 *
 * @tags allow-read
 *
 * @param path The path of the symbolic link.
 * @param options Options when reading a file. See {@linkcode ReadFileOptions}.
 * @returns A promise that resolves to string of the file content.
 */
export async function readTextFile(
  path: string | URL,
  options?: ReadFileOptions,
): Promise<string> {
  if (isDeno) {
    return Deno.readTextFile(path, { ...options });
  } else {
    const { signal } = options ?? {};
    try {
      return await getNodeFs().promises.readFile(path, {
        encoding: "utf-8",
        signal,
      });
    } catch (error) {
      throw mapError(error);
    }
  }
}

/**
 * Synchronously reads and returns the entire contents of a file as an UTF-8 decoded string.
 *
 * Reading a directory throws an error.
 *
 * Requires `allow-read` permission.
 *
 * @example Usage
 * ```ts
 * import { assert } from "@std/assert";
 * import { readTextFileSync } from "@std/fs/unstable-read-text-file";
 *
 * const content = readTextFileSync("README.md"); // full content of README.md
 *
 * assert(content.length > 0);
 * ```
 *
 * @tags allow-read
 *
 * @param path The path of the symbolic link.
 * @returns The string of file content.
 */
export function readTextFileSync(
  path: string | URL,
): string {
  if (isDeno) {
    return Deno.readTextFileSync(path);
  } else {
    try {
      return getNodeFs().readFileSync(path, "utf-8");
    } catch (error) {
      throw mapError(error);
    }
  }
}