简体   繁体   中英

How can I recursively read a directory in Deno?

I'm trying to recursively read a file in Deno using Deno.readDir , but the example they provide only does the folder given:

for await (const entry of Deno.readDir(Deno.cwd())) {
  console.log(entry.name);
}

How can I make this recursive?

Since that function returns an async generator, you can make your own generator function that wraps around Deno.readDir :

(Do note that the example provided will join the path and name, giving you strings such as /directory/name.txt )

import { join } from "https://deno.land/std/path/mod.ts";

export async function* recursiveReaddir(
  path: string
): AsyncGenerator<string, void> {
  for await (const dirEntry of Deno.readDir(path)) {
    if (dirEntry.isDirectory) {
      yield* recursiveReaddir(join(path, dirEntry.name));
    } else if (dirEntry.isFile) {
      yield join(path, dirEntry.name);
    }
  }
}
for await (const entry of recursiveReaddir(Deno.cwd())) {
  console.log(entry)
}

OR, you can use recursive_readdir , which is a 3rd party library in Deno made for this purpose.

Deno's standard library includes a function called walk for this purpose. It's available in std/fs/walk.ts . Here's an example:

/Users/deno/so-74953935/main.ts :

import { walk } from "https://deno.land/std@0.170.0/fs/walk.ts";

for await (const walkEntry of walk(Deno.cwd())) {
  const type = walkEntry.isSymlink
    ? "symlink"
    : walkEntry.isFile
    ? "file"
    : "directory";

  console.log(type, walkEntry.path);
}

Running in the terminal:

% pwd
/Users/deno/so-74953935

% ls -AF
.vscode/    deno.jsonc  deno.lock   main.ts

% ls -AF .vscode 
settings.json

% deno --version
deno 1.29.1 (release, x86_64-apple-darwin)
v8 10.9.194.5
typescript 4.9.4

% deno run --allow-read main.ts
directory /Users/deno/so-74953935
file /Users/deno/so-74953935/main.ts
file /Users/deno/so-74953935/deno.jsonc
file /Users/deno/so-74953935/deno.lock
directory /Users/deno/so-74953935/.vscode
file /Users/deno/so-74953935/.vscode/settings.json

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM