Skip to content

Instantly share code, notes, and snippets.

@florianherrengt
Created March 13, 2023 12:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save florianherrengt/51bec25ba47d0469a0a0b4654a28d4fd to your computer and use it in GitHub Desktop.
Save florianherrengt/51bec25ba47d0469a0a0b4654a28d4fd to your computer and use it in GitHub Desktop.
All all the files in a folder and sub folders
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");
});
});
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