Skip to content

Instantly share code, notes, and snippets.

@abhishekmunie
Last active March 15, 2020 18:15
Show Gist options
  • Save abhishekmunie/f6bd2053cfc950f3cc00418944849e9c to your computer and use it in GitHub Desktop.
Save abhishekmunie/f6bd2053cfc950f3cc00418944849e9c to your computer and use it in GitHub Desktop.
TypeScript: for async of directory walk
import { promises as fs } from 'fs';
import { resolve as resolvePath } from 'path';
/**
* Recursively walk a directory asynchronously and yeild file names (with full path).
*
* @param path Directory path you want to recursively process
* @param filter Optional filter to specify which files to include
*/
async function* walk(path: string, filter?: (file: string) => boolean) {
let stat;
try {
stat = await fs.stat(path);
} catch (error) {
throw error;
}
if (!stat.isDirectory()) {
if (typeof filter === 'undefined' || (filter && filter(path))) {
yield path;
}
return;
}
let children;
try {
children = await fs.readdir(path);
} catch (error) {
throw error;
}
for (const child of children) {
const childPath = resolvePath(path, child);
for await (const res of walk(childPath, filter)) {
yield res;
}
}
}
function walkFilter(file: string): boolean {
return ! /\/.DS_Store$/.test(file);
}
(async () => {
const srcDir = 'images'
try {
for await (const filepath of walk(srcDir, walkFilter)) {
console.log("doing something awesome with", filepath)
}
} catch (error) {
console.error(error);
}
})();
@abhishekmunie
Copy link
Author

Asynchronous directory walk in typescript with filtering

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