Cela pourrait être une solution possible en utilisant la fonction de générateur asynchrone et en itérant avec for await
boucle. Cette solution inclut la possibilité de filtrer certains répertoires en les passant comme troisième argument facultatif du tableau.
import path from 'path';
import { readdir, copy } from 'fs-extra';
async function* getCopyableFiles(srcDir: string, destDir: string, excludedFolders?: string[]): AsyncGenerator<string> {
const directoryEntries = await readdir(srcDir, { withFileTypes: true });
for (const entry of directoryEntries) {
const fileName = entry.name;
const filePath = path.join(srcDir, fileName);
if (entry.isDirectory()) {
if (!excludedFolders?.includes(filePath)) {
yield* getCopyableFiles(filePath, path.join(destDir, fileName), excludedFolders);
}
} else {
yield filePath;
}
}
}
Ensuite :
for await (const filePath of getCopyableFiles(path1, path2, ['dir1', 'dir2'])) {
await copy(filePath, filePath.replace(path1, path2));
}