File.loopDir
$dir.loopDir($loopFunction, $options={}) -> null
Description
Iterate through all items in a directory and apply a function to each.
This function is memory-efficient for large directories, because it handles only one item at a time.
Callback Function
The callback function receives a file or dir TypeString of the current item.
// Count all png files in a directory
$numImages = 0
dir'files:/some/dir'.loopDir(fun ($file) {
if $file.pathParts().fileExt == 'png' {
$numImages += 1
}
})
Early Return
If $loopFunction returns a non-null value, it will stop reading the rest of the directory and return that value.
If it does not return early, it will return null.
// Return the first file found that is larger than 10 MB
$largeFile = dir'files:/some/dir'.loopDir(fun ($file) {
if $file.getSize('MB') >= 10 {
return $file
}
})
Options
| Option | Value | Description |
|---|---|---|
filter |
files, dirs, all |
Type of contents to include |
deep |
true/false | Include contents of subdirectories |
$funEachSubdir = fun ($dir) {
print($dir)
}
// Loop through all subdirectories recursively
dir'files:/some/dir'.loopDir($funEachSubdir, { filter: 'dirs', deep })