walk-it
TypeScript icon, indicating that this package has built-in type declarations

5.0.1 • Public • Published

walk-it

TS ready ESM ready Deno ready Bun ready Node.js CI npm jsr npm bundle size codecov GitHub

Recursive file walk-iterator. Requires Node 18+, Deno or Bun.

Install (Node)

npm i walk-it
pnpm i walk-it
yarn add walk-it
bun install walk-it

Install (JSR)

npx jsr add @svarta/walk-it
pnpm jsr add @svarta/walk-it
yarn jsr add @svarta/walk-it
bunx jsr add @svarta/walk-it

Deno usage

import { walk } from "npm:walk-it";

Default behaviour

By default, all folders will be visited recursively starting at the given directory.

Note that subfolders are visited eagerly, meaning the level is not sorted (aka. pre-order traversal is used instead of level-order).

Usage & examples

Walk all folders recursively

import { walk } from "walk-it";

for await (const x of walk(dir)) {
  // x contains:
  // dir    : the scanned folder's absolute path
  // files  : files as directory entries (Dirent)
  // folders: folders as directory entries (Dirent)
  // level  : the tree level (0 being the start directory)
  console.log(x);
}

Get files only

import { walkFiles } from "walk-it";

for await (const { file, path } of walkFiles(dir)) {
  // file is a Dirent object
  // path is the absolute path of the visited file
  console.log(file, path);
}

Limit recursive descent

import { walk } from "walk-it";

// 0 = Only output 'dir'
// 1 = Descent once
// 2 = Descent twice
// ...
for await (const x of walk(dir, { maxLevel: 2 })) {
  console.log(x);
}

Disable recursive descent altogether

Same as maxLevel = 0

import { walk } from "walk-it";

for await (const x of walk(dir, { recursive: false })) {
  console.log(x);
}

Whitelist files by extension

import { walk } from "walk-it";

for await (const x of walk(".", {
  filterFile: ({ name }) => name.endsWith(".jpg"),
})) {
  console.log(x);
}

Blacklist folders

import { walk } from "walk-it";

for await (const x of walk(".", {
  filterFolder: ({ name }) => !["node_modules", ".git"].includes(name),
})) {
  console.log(x);
}

filterFolder should be preferred over filtering after walking because it will stop the recursive descent, thus increasing performance.

Count files

import { countFiles } from "walk-it";

const count = await countFiles(".");
console.log(`${count} files found`);

const count = await countFiles(".", {
  // You can also use the same options as walk and walkFiles
  filterFolder: ({ name }) => !["node_modules", ".git"].includes(name),
});
console.log(`${count} files found`);

Package Sidebar

Install

npm i walk-it

Weekly Downloads

13

Version

5.0.1

License

MIT

Unpacked Size

10.7 kB

Total Files

5

Last publish

Collaborators

  • marvin-j97