files

Paths and globs that are correct at the edges

A glob, a walk of the folders or a path with ~ is easy to get almost right. @mark1russell7/files gets the edge cases right, with only the node: modules. Each demo on this page runs the real functions of the package in your browser, on a sample project in memory.

pnpm add @mark1russell7/files

1. Match a path with a glob

A script often makes a glob into a regular expression: it changes * to .* and ? to .. That quick version goes across a /, and it knows no **, no group and no set. The demo matches each file of the sample project with matchesGlob and with the quick version.

Each file of the sample project
PathmatchesGlobQuick

2. Find the files of a project

findFiles starts in the base folder of each pattern. It does not go into a skipped folder or an ignored folder, and it does not follow a link. The tree shows each file that it found and each folder that it read. A gray entry is in a folder that it did not read.

3. Walk names in order

walk gives each entry at and under the names, depth first: a folder before its contents, and the contents in the order of their names. It gives a link as a link. It gives each name one time. A missing name stops the walk with the error of lstat.

    4. Is a path in a folder?

    A check with path.startsWith(folder) lets in /home/you/shop-old and a path with ... isInside compares the path after its .. and . segments.

    5. Expand the home folder

    The home folder of the sample user is /home/you. path.replace("~", home) changes the first ~ at any place in the path. expandHome changes only a ~ at the start, alone or before a separator.

    6. Find the nearest file up the folders

    findUp looks for a name in a folder, then in each folder above it, up to the root. A tool finds its package.json or its .git folder this way. The list shows each path that it looked at.

      Use it

      import { expandHome, findFiles, findUp, isInside, walk } from "@mark1russell7/files";
      import { matchesGlob } from "@mark1russell7/files/glob";
      
      const sources = findFiles({ root, include: ["src/**/*.{ts,tsx}"], ignore: ["**/*.test.ts"] });
      const manifest = findUp("package.json", process.cwd());
      if (!isInside(root, expandHome(target))) throw new Error("The path is out of the project.");
      for await (const entry of walk(root, ["src"])) console.log(entry.name, entry.kind);
      const isSource = matchesGlob("src/view/list.tsx", "src/**/*.{ts,tsx}");

      The glob functions are also in the entry @mark1russell7/files/glob, which uses no node: module. Releases shows each version, and Status shows the open work.