Skip to content

Commit

Permalink
fix: Refactor copy to use opendir (jprichardson/node-fs-extra#1028)
Browse files Browse the repository at this point in the history
  • Loading branch information
Exponential-Workload committed Mar 1, 2024
1 parent 7098d35 commit 70d0cfd
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 23 deletions.
12 changes: 11 additions & 1 deletion packages/@3xpo/fs-extra/src/copy/copy-sync.ts
Expand Up @@ -157,7 +157,17 @@ export const mkDirAndCopy = (
};

export const copyDir = (src: string, dest: string, opts?: CopyOpts) => {
fs.readdirSync(src).forEach(item => copyDirItem(item, src, dest, opts));
const dir = fs.opendirSync(src);

try {
let dirent: fs.Dirent;

while ((dirent = dir.readSync()) !== null) {
copyDirItem(dirent.name, src, dest, opts);
}
} finally {
dir.closeSync();
}
};

export const copyDirItem = (
Expand Down
43 changes: 21 additions & 22 deletions packages/@3xpo/fs-extra/src/copy/copy.ts
Expand Up @@ -159,30 +159,29 @@ export const onDir = async (
await fs.mkdir(dest);
}

const items = await fs.readdir(src);
const promises = [] as Promise<void>[];

// loop through the files in the current directory to copy everything
await Promise.all(
items.map(async item => {
const srcItem = path.join(src, item);
const destItem = path.join(dest, item);

// skip the item if it is matches by the filter function
const include = await runFilter(srcItem, destItem, opts);
if (!include) return;

const { destStat } = await stat.checkPaths(
srcItem,
destItem,
'copy',
opts,
);

// If the item is a copyable file, `getStatsAndPerformCopy` will copy it
// If the item is a directory, `getStatsAndPerformCopy` will call `onDir` recursively
return getStatsAndPerformCopy(destStat, srcItem, destItem, opts);
}),
);
for await (const item of await fs.opendir(src)) {
const srcItem = path.join(src, item.name);
const destItem = path.join(dest, item.name);

promises.push(
runFilter(srcItem, destItem, opts).then(include => {
if (include) {
// only copy the item if it matches the filter function
return stat
.checkPaths(srcItem, destItem, 'copy', opts)
.then(({ destStat }) => {
// If the item is a copyable file, `getStatsAndPerformCopy` will copy it
// If the item is a directory, `getStatsAndPerformCopy` will call `onDir` recursively
return getStatsAndPerformCopy(destStat, srcItem, destItem, opts);
});
}
}),
);
}
await Promise.all(promises);

if (!destStat) {
await fs.chmod(
Expand Down

0 comments on commit 70d0cfd

Please sign in to comment.