All files / fs / unstable_read_dir.ts

33.33% Branches 1/3
35.48% Lines 11/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
 
 
x3
x3
x3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
x3
x7
x7
 
 
 
 
 
 
 
 
 
 
x7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
x3
x7
x7
 
 
 
 
 
 
 
 
 
 
x7
































I





































I









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

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

/**
 * Reads the directory given by `path` and returns an async iterable of
 * {@linkcode DirEntry}. The order of entries is not guaranteed.
 *
 * Throws Error if `path` is not a directory.
 *
 * Requires `allow-read` permission.
 *
 * @example Usage
 * ```ts no-assert
 * import { readDir } from "@std/fs/unstable-read-dir";
 *
 * for await (const dirEntry of readDir("/")) {
 *   console.log(dirEntry.name);
 * }
 * ```
 *
 * @tags allow-read
 * @category File System
 *
 * @param path The path to the directory to read.
 * @returns An async iterable of {@linkcode DirEntry}.
 */
export async function* readDir(path: string | URL): AsyncIterable<DirEntry> {
  if (isDeno) {
    yield* Deno.readDir(path);
  } else {
    try {
      const dir = await getNodeFs().promises.opendir(path);
      for await (const entry of dir) {
        yield toDirEntry(entry);
      }
    } catch (error) {
      throw mapError(error);
    }
  }
}

/**
 * Synchronously reads the directory given by `path` and returns an iterable
 * of {@linkcode DirEntry}. The order of entries is not guaranteed.
 *
 * Throws Error if `path` is not a directory.
 *
 * Requires `allow-read` permission.
 *
 * @example Usage
 * ```ts no-assert
 * import { readDirSync } from "@std/fs/unstable-read-dir";
 *
 * for (const dirEntry of readDirSync("/")) {
 *   console.log(dirEntry.name);
 * }
 * ```
 *
 * @tags allow-read
 * @category File System
 *
 * @param path The path to the directory to read.
 * @returns An iterable of {@linkcode DirEntry}.
 */
export function* readDirSync(path: string | URL): Iterable<DirEntry> {
  if (isDeno) {
    return yield* Deno.readDirSync(path);
  } else {
    try {
      const dir = getNodeFs().readdirSync(path, { withFileTypes: true });
      for (const entry of dir) {
        yield toDirEntry(entry);
      }
    } catch (error) {
      throw mapError(error);
    }
  }
}