Skip to content

Instantly share code, notes, and snippets.

@federicofazzeri
Last active September 18, 2017 15:05
Show Gist options
  • Save federicofazzeri/a08b2f88e95633e35cfe36d9b6853a65 to your computer and use it in GitHub Desktop.
Save federicofazzeri/a08b2f88e95633e35cfe36d9b6853a65 to your computer and use it in GitHub Desktop.
async/await + recursion = concise and highly expressive async code
/*
Crawl a directory and return a list containing all subdirectories paths
*/
const fs = require('fs-extra');
const { promisify } = require('util');
const { resolve } = require('path');
const EventEmitter = require('events');
const isDir = folder => fs.lstatSync( folder ).isDirectory();
const listDir = path => promisify( fs.readdir )( resolve( path ) )
const getFoldersFromList = ( filesList, baseFolder ) =>
filesList
.map( file => `${baseFolder}/${file}`)
.filter( folderPath => isDir( folderPath ) )
async function foldersCrawler( folder, accumulator = [] ) {
try {
let foldersList = getFoldersFromList( await listDir( folder ), folder );
if( foldersList.length ) accumulator.push( ...foldersList );
await Promise.all(
foldersList
.map( folderPath => foldersCrawler( folderPath , accumulator ) )
);
return accumulator;
} catch(err) {
throw err;
}
}
module.exports = async function listFolders(basePath) {
try {
return await foldersCrawler( basePath );
} catch(err) {
throw err;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment