Skip to content

DirList

do- edited this page Jul 28, 2024 · 5 revisions

DirList is an iterator over subdirectories belonging to a given list of roots and satisfying a given condition.

const {DirList} = require ('fs-iterators')

const myDir = new DirList ({
  root: ['/opt/myProject'], 
  filter: (str, arr) => 
    /src/.test (str)            // contains 'src'
    && arr.at (-2) === 'Model', // **/Model/*
  live: false,
})

for (const path of myDir.paths) console.log ({path})

for (const path of myDir.files ()) console.log ({path})
for (const path of myDir.files ('index.js')) console.log ({path})
for (const path of myDir.files (_ => /js$/.test (_))) console.log ({path})

Options

Name Default value Description
root undefined Must be set as a String or an Iterator (e. g. a regular Array) of Strings
filter (str, arr) => true See below
live true See below

filter

This function is called for each subdirectory with two arguments:

Name Type Description
str String The string representation of the path.
arr Array The same value, as an array

arr is never empty. Its 1st element is one of root values, verbatim, not split nor normalized anyhow. All subsequent elements (if any) are local names of nested subdirectories.

str is arr joined with path.sep. Whether it is absolute depends on the way the root was provided. Anyway, all root values must be visible to the application as paths of existing directories, or an Error will be thrown.

The result returned by the filter is converted to Boolean. When it's true, the str value is yielded.

live

The boolean valued live option, true by default, means:

  • true: the directory tree will be scanned each time .paths is read;
  • false: the directory tree may be scanned only once, then the cached copy will be used;

Propreties

paths

The value of this property is an iterable listing requested directories.

Methods

files (filter)

This method returns an iterable over the list of all files in .paths satisfying the filter condition. See FilePaths for details about filter.

Clone this wiki locally