-
-
Save pampanelson/ea9d962d60711d79ba886d437f0b584f to your computer and use it in GitHub Desktop.
async/await recursive fs readdir
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 { join } from 'path' | |
| import { readdir, stat } from 'fs-promise' | |
| async function rreaddir (dir, allFiles = []) { | |
| const files = (await readdir(dir)).map(f => join(dir, f)) | |
| allFiles.push(...files) | |
| await Promise.all(files.map(async f => ( | |
| (await stat(f)).isDirectory() && rreaddir(f, allFiles) | |
| ))) | |
| return allFiles | |
| } |
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
| // straight synchronous version for perf comparison | |
| import { join } from 'path' | |
| import fs from 'fs' | |
| function rreaddirSync (dir, allFiles = []) { | |
| const files = fs.readdirSync(dir).map(f => join(dir, f)) | |
| allFiles.push(...files) | |
| files.forEach(f => { | |
| fs.statSync(f).isDirectory() && rreaddirSync(f, allFiles) | |
| }) | |
| return allFiles | |
| } |
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 assert from 'assert' | |
| console.time('parallel') | |
| rreaddir(__dirname).then(pFiles => { | |
| console.timeEnd('parallel') | |
| console.time('sync') | |
| const sFiles = rreaddirSync(__dirname) | |
| console.timeEnd('sync') | |
| assert.deepEqual(pFiles.sort(alpha), sFiles.sort(alpha)) | |
| }) | |
| function alpha (a, b) { | |
| return a.localeCompare(b) | |
| } |
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
| parallel: 313.899ms | |
| sync: 80.259ms |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment