I want to implement a function that enumerates all files in directory. I think the function should
- Return a Promise, because underlying
readdir
call is prefered overreaddirSync
. - Be a generator function, because checking
statSync(...).isFile()
might take some time and maybe, I will need only first few files…
So my attempt
import * as fs from 'fs'; import * as path from 'path'; function enumerateFiles(dir: string): Promise<IterableIterator<string>> { let result = function* (files: string[]): IterableIterator<string> { for (let enty of files) { let fullpath = path.join(dir, enty); if (fs.statSync(fullpath).isFile()) yield fullpath; } }; return new Promise<IterableIterator<string>>((resolve, reject) => { fs.readdir(dir, (err, files) => { if (err) reject(err); else resolve(result(files)); }); }); }
And usage
for (let file of await enumerateFiles(String.raw`C:\Windows\Web\Screen`)) console.log(file); // C:\Windows\Web\Screen\img100.jpg // C:\Windows\Web\Screen\img101.jpg // ...
What do you think? I’m really not sure about combining Promises with generator functions. Especially in this order…