Skip to content

Instantly share code, notes, and snippets.

@MakotoUwaya
Last active December 2, 2020 12:46
Show Gist options
  • Select an option

  • Save MakotoUwaya/78ad25b2264975388aebfed3b388e344 to your computer and use it in GitHub Desktop.

Select an option

Save MakotoUwaya/78ad25b2264975388aebfed3b388e344 to your computer and use it in GitHub Desktop.
Retrieving files recursively for nodejs with flatMap(ES2019)
import fs from 'fs';
const targetDirectoryPath = 'directoryPath';
const listFiles = (dir: string): string[] => {
return fs.readdirSync(dir, { withFileTypes: true }).flatMap(dirent => {
const path = `${dir}/${dirent.name}`;
return dirent.isFile() ? [path] : listFiles(path);
});
};
console.log(listFiles(targetDirectoryPath));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment