Last active
April 14, 2022 14:23
-
-
Save erikvullings/c7eed546a4be0ba43532f8b83048ef38 to your computer and use it in GitHub Desktop.
Recursively walk a directory in TypeScript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import fs from 'fs'; | |
import path from 'path'; | |
/** | |
* Recursively walk a directory asynchronously and obtain all file names (with full path). | |
* | |
* @param dir Folder name you want to recursively process | |
* @param done Callback function, returns all files with full path. | |
* @param filter Optional filter to specify which files to include, | |
* e.g. for json files: (f: string) => /.json$/.test(f) | |
* @see https://stackoverflow.com/questions/5827612/node-js-fs-readdir-recursive-directory-search/50345475#50345475 | |
*/ | |
const walk = ( | |
dir: string, | |
done: (err: Error | null, results?: string[]) => void, | |
filter?: (f: string) => boolean | |
) => { | |
let results: string[] = []; | |
fs.readdir(dir, { withFileTypes: true }, (err: Error | null, list: string[]) => { | |
if (err) { | |
return done(err); | |
} | |
let pending = list.length; | |
if (!pending) { | |
return done(null, results); | |
} | |
list.forEach((file: string) => { | |
file = path.resolve(dir, file); | |
fs.stat(file, (err2, stat) => { | |
if (stat.isDirectory()) { | |
walk(file, (err3, res) => { | |
if (res) { | |
results = results.concat(res); | |
} | |
if (!--pending) { | |
done(null, results); | |
} | |
}, filter); | |
} else { | |
if (typeof filter === 'undefined' || (filter && filter(file))) { | |
results.push(file); | |
} | |
if (!--pending) { | |
done(null, results); | |
} | |
} | |
}); | |
}); | |
}); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@TheTrashAcc @keyoti Thanks for your suggestions - I've improved the gist with them!