Skip to content

Instantly share code, notes, and snippets.

@erikvullings
Last active April 14, 2022 14:23
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save erikvullings/c7eed546a4be0ba43532f8b83048ef38 to your computer and use it in GitHub Desktop.
Save erikvullings/c7eed546a4be0ba43532f8b83048ef38 to your computer and use it in GitHub Desktop.
Recursively walk a directory in TypeScript
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);
}
}
});
});
});
};
@keyoti
Copy link

keyoti commented Apr 23, 2021

import fs from 'fs';
import path from 'path';

fs.readdir(dir, (err: Error | null, list: string[]) => {

@cprovatas
Copy link

import fs from 'fs';
import path from 'path';

fs.readdir(dir, (err: Error | null, list: string[]) => {

+1 Thank you @keyoti

@TheTrashAcc
Copy link

You could also use:

fs.readdir(dir, { withFileTypes: true }, (err: Error, list: Dirent[])

This way you can then leave the stat part and simply check:

if (file.isDirectory()) {

@erikvullings
Copy link
Author

@TheTrashAcc @keyoti Thanks for your suggestions - I've improved the gist with them!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment