Created
March 13, 2023 12:24
-
-
Save florianherrengt/51bec25ba47d0469a0a0b4654a28d4fd to your computer and use it in GitHub Desktop.
All all the files in a folder and sub folders
This file contains 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 path from "path"; | |
import { listFiles } from "./listFiles"; | |
/** | |
└── test | |
├── file1.txt | |
└── folder1 | |
└── file2.txt | |
*/ | |
describe("list files", () => { | |
test("list files in /helpers", async () => { | |
const files = await listFiles({ | |
dir: path.join(module.path.replace("/.build", ""), "./test"), | |
}); | |
expect(files.join(",")).toContain("file1"); | |
expect(files.join(",")).toContain("file2"); | |
}); | |
}); |
This file contains 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 fs from "fs/promises"; | |
import { flattenDeep, zip } from "lodash"; | |
import path from "path"; | |
interface ListFilesParams { | |
dir: string; | |
} | |
export const listFiles = async ({ | |
dir, | |
}: ListFilesParams): Promise<string[]> => { | |
let files: string[] = []; | |
for (const fileOrDir of await fs.readdir(dir)) { | |
const fullPath = path.join(dir, fileOrDir); | |
if ((await fs.lstat(fullPath)).isDirectory()) { | |
files = [...files, ...(await listFiles({ dir: fullPath }))]; | |
} else { | |
files = [...files, fullPath]; | |
} | |
} | |
const list = await fs.readdir(dir); | |
const stats = await Promise.all( | |
list.map((l) => fs.lstat(path.join(dir, l))), | |
); | |
const allFiles = await Promise.all( | |
zip(list, stats).map(([fileOrDir, lstat]) => { | |
const fullPath = path.join(dir, fileOrDir!); | |
if (lstat!.isFile()) { | |
return Promise.resolve(fullPath); | |
} | |
if (lstat!.isDirectory()) { | |
return listFiles({ dir: fullPath }); | |
} | |
return ""; | |
}), | |
); | |
return flattenDeep(allFiles.filter((a) => a)); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment