Last active
March 15, 2020 18:15
-
-
Save abhishekmunie/f6bd2053cfc950f3cc00418944849e9c to your computer and use it in GitHub Desktop.
TypeScript: for async of directory walk
This file contains hidden or 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 { 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); | |
} | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Asynchronous directory walk in typescript with filtering