Skip to content

Commit

Permalink
feat(fs/unstable): added readDir function and test denoland#6255
Browse files Browse the repository at this point in the history
  • Loading branch information
jbronder committed Jan 8, 2025
1 parent e331aec commit 06ffac6
Show file tree
Hide file tree
Showing 2 changed files with 91 additions and 0 deletions.
50 changes: 50 additions & 0 deletions fs/unstable_read_dir.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
// Copyright 2018-2025 the Deno authors. MIT license.

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

async function* getDirEntries(path: string | URL): AsyncIterable<DirEntry> {
const fsPromises = getNodeFsPromises();
try {
const dir = await fsPromises.opendir(path);
for await (const entry of dir) {
const dirEntry = toDirEntry(entry);
yield dirEntry;
}
} catch (error) {
throw error;
}
}

/** Reads the directory given by `path` and returns an async iterable of
* {@linkcode DirEntry}. The order of entries is not guaranteed.
*
* ```ts
* import { readDir } from "@std/fs/unstable-read-dir";
*
* for await (const dirEntry of readDir("/")) {
* console.log(dirEntry.name);
* }
* ```
*
* Throws error if `path` is not a directory.
*
* Requires `allow-read` permission.
*
* @tags allow-read
* @category File System
*/
export function readDir(path: string | URL): AsyncIterable<DirEntry> {
if (isDeno) {
return Deno.readDir(path);
} else {
try {
const dirEntries = getDirEntries(path);
return dirEntries;
} catch (error) {
throw mapError(error);
}
}
}
41 changes: 41 additions & 0 deletions fs/unstable_read_dir_test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
// Copyright 2018-2025 the Deno authors. MIT license.

import { assert, assertEquals, assertRejects } from "@std/assert";
import { fromFileUrl, join, resolve } from "@std/path";
import { readDir } from "./unstable_read_dir.ts";
import { NotFound } from "./unstable_errors.js";

const testdataDir = resolve(fromFileUrl(import.meta.url), "../testdata");

Deno.test("readDir() reads from the directory and its subdirectories", async () => {
const files = [];
for await (const e of readDir(testdataDir)) {
files.push(e);
}

let counter = 0;
for (const f of files) {
if (f.name === "walk") {
assert(f.isDirectory);
counter++;
}
}

assertEquals(counter, 1);
});

Deno.test("readDir() rejects when the path is not a directory", async () => {
await assertRejects(async () => {
const testFile = join(testdataDir, "0.txt");
await readDir(testFile)[Symbol.asyncIterator]().next();
}, Error);
});

Deno.test("readDir() rejects when the directory does not exist", async () => {
await assertRejects(
async () => {
await readDir("non_existent_dir")[Symbol.asyncIterator]().next();
},
NotFound,
);
});

0 comments on commit 06ffac6

Please sign in to comment.